@testim/testim-cli 4.127.0 → 4.129.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -1,33 +1,33 @@
1
1
  #! /usr/bin/env node
2
- "use strict";var xT=Object.create;var ti=Object.defineProperty;var CT=Object.getOwnPropertyDescriptor;var PT=Object.getOwnPropertyNames;var kT=Object.getPrototypeOf,_T=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)ti(s,t,{get:e[t],enumerable:!0})},sd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of PT(e))!_T.call(s,n)&&n!==t&&ti(s,n,{get:()=>e[n],enumerable:!(r=CT(e,n))||r.enumerable});return s};var S=(s,e,t)=>(t=s!=null?xT(kT(s)):{},sd(e||!s||!s.__esModule?ti(t,"default",{value:s,enumerable:!0}):t,s)),Ue=s=>sd(ti({},"__esModule",{value:!0}),s);var $e={};H($e,{log:()=>U,measure:()=>LT});function U(...s){if(!id)return;let e=Date.now();console.log(`${e-OT} ${e-nd} `,...s),nd=e}function LT(s,e){if(!id)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var id,OT,nd,We=w(()=>{"use strict";id=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,OT=Date.now(),nd=Date.now()});var Ht,Fr=w(()=>{"use strict";Ht="element-6066-11e4-a52e-4f735466cecf"});function se(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function Xa(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function _e(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 Qa=w(()=>{"use strict"});var ec,od,ad,li=w(()=>{ec={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},od={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"1.3.0","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4","coralogix-logger":"1.1.28",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.19.2",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.22.10",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"4.9.18",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","unzip-stream":"0.3.4","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},ad={node:">= 18.0.0"}});var Ls,NT,cd,ld,ud,ui,Ds,pd,fe,dd,md,pi,Oe,tc,fd,di,gd,SR,ER,hd,yd,Ms,bd,Td,wd,vd,Sd,rc,sc,nc,ic,Ed,Ns,Id,oc,pe=w(()=>{"use strict";Ls=process.env.SERVICES_HOST||"https://services.testim.io",NT="https://testimstatic.blob.core.windows.net",cd="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:Ls,Ls=process.env.SERVICES_HOST);ld=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),ud=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),ui=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ds=process.env.EDITOR_URL,pd=process.env.WEBSOCKET_HOST||`${Ls}/ws`,fe=Ls,dd=parseInt(process.env.LOGGER_CONSOLE||"0",10),md=parseInt(process.env.LOGGER_DEBUG||"0",10),pi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Oe=parseInt(process.env.IS_ON_PREM||"0",10),tc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,fd=parseInt(process.env.DEBUG_MODE||"0",10),di=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,gd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",SR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),ER=process.env.APPIUM_VERSION||"1.10.1",hd=process.env.GATEWAY_URL,yd=process.env.EXTENSION_SERVICES_HOST||Ls,Ms=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:NT,bd=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:cd,Td=cd,wd=5*60*1e3,vd=40,Sd=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api",rc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",sc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",nc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",ic=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Ed=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Ns=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Id=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,oc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var ac={};H(ac,{CoralogixTransport:()=>Br});var Ie,Rd,UT,FT,Br,cc=w(()=>{"use strict";Ie=require("coralogix-logger"),Rd=S(require("winston-transport")),UT={debug:Ie.Severity.debug,silly:Ie.Severity.verbose,verbose:Ie.Severity.verbose,silent:Ie.Severity.verbose,info:Ie.Severity.info,http:Ie.Severity.info,warn:Ie.Severity.warning,warning:Ie.Severity.warning,error:Ie.Severity.error,critical:Ie.Severity.critical,crit:Ie.Severity.critical},FT=["err","error","reason","e"],Br=class extends Rd.default{constructor(t){t={...Br.options,...t};super(t);this.options=t,this.logger=new Ie.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:i,message:o,meta:a={},...l}=t,c={...a,...this.options.extraFields,...l},d=new Ie.Log;d.severity=UT[i],d.text=o,d.category=n,c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,o&&(c.msg=`${o}
3
- ${c.msg}`));for(let u of FT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=c),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Br.options=t}}});var gc={};H(gc,{getLogger:()=>A,sessionPlayerLoggerFormatter:()=>pc,setExecutionId:()=>dc,setProjectId:()=>mc,setProxyUri:()=>fc});function $T(){let s=[],e=()=>Promise.resolve();if(!Oe){let{CoralogixTransport:t}=(cc(),Ue(ac));t.configure(kd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}if(dd){let t={depth:5,colors:!0};s.push(new dt.transports.Console({format:dt.format.combine(dt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),dt.format.timestamp({format:"HH:mm:ss:SSS"}),dt.format.printf(r=>`[${r.timestamp}] ${r.level} ${r.category}: ${r.message} ${fi.inspect(r.meta,t)}`))}))}return[s,e]}function dc(s){lc=s}function mc(s){_d=s}function fc(s){if(Oe||!s)return;let{CoralogixTransport:e}=(cc(),Ue(ac));e.configure({...kd,proxyUri:s})}function xd(s){return{projectId:_d,time:new Date().toISOString(),...lc&&!s&&{executionId:lc}}}function A(s){return new uc(qT.child({category:s}))}var Cd,dt,fi,mi,Pd,BT,jT,kd,Ad,pc,WT,VT,GT,HT,qT,lc,_d,uc,$=w(()=>{"use strict";Cd=S(require("os")),dt=S(require("winston"));pe();fi=S(require("util")),mi=S(require("chalk")),Pd=S(require("dayjs"));F();BT=Cd.hostname(),jT=ze(),kd={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};Ad={depth:5,colors:!0},pc=(s,e,t)=>{let r=`[${(0,Pd.default)().format("HH:mm:ss:SSS")}]`,n=fi.inspect(e,Ad),i=fi.inspect(t,Ad);return`${mi.default.white(r)} ${mi.default.reset()}SessionPlayer-${mi.default.red(s)} ${n} ${i}`},[WT,VT]=$T(),GT=md?"debug":"info",HT={release:Boolean(!0),branch:"production"},qT=dt.createLogger({levels:dt.config.syslog.levels,level:GT,transports:WT,defaultMeta:{name:"runner",hostname:BT,nodeVersion:process.version,runnerVersion:jT,...HT}}),lc=null,_d=null;uc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...xd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...xd(n)})}catch{}}}waitForFlush(){return VT()}}});var bi,jr,x,qt,dr,It,gi,$r,ie,Us,Ke,zt,Rt,hi,Wr,yi,Fs,J=w(()=>{"use strict";bi=require("p-retry"),jr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},dr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},It=class extends bi.AbortError{},gi=class extends bi.AbortError{},$r=class extends bi.AbortError{},ie=class extends Error{},Us=class extends Error{},Ke=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},zt=class extends Ke{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},hi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Wr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},yi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Fs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function hc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ce(s){return(0,Dd.setTimeout)(s)}function yc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function oe(s,e,t="Timeout Error"){ui&&!Od&&(Od=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ie(t);return e=ui?Number(ui)||6e5:e,Promise.race([s,ce(e).then(()=>{throw r})])}async function ae(s,e,{concurrency:t}={}){if(t){Ld||=(await import("p-limit")).default;let r=Ld(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Dd,Od,Ld,bc=w(()=>{"use strict";Dd=require("timers/promises");J();pe();Od=!1});var js,Md,zT,Bs,Nd,KT,JT,Ud,Fd=w(()=>{"use strict";js=S(require("lodash"));pe();Md=require("dns");$();bc();zT=A("http-request-counters"),Bs=!1,Nd=async()=>{if(Oe)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ae(s,t=>Md.promises.lookup(t)));return e||(Bs=!0),e}catch{return zT.error("network connectivity test failed"),Bs=!0,!1}},KT=js.throttle(Nd,10*1e3),JT=60*1e3*15,Ud=()=>{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)},JT)}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),Bs||KT(),a}}}async function r(){if(Bs||!await Nd())return!1;let n=js.sum([...s.fail.values()]),i=js.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Bs,t}});var Je={};H(Je,{deleteReq:()=>$s,didNetworkConnectivityTestFail:()=>Rc,download:()=>Ec,get:()=>be,getFullRes:()=>ew,getText:()=>Vs,head:()=>tw,isNetworkHealthy:()=>Ic,post:()=>Ve,postForm:()=>Ws,postText:()=>vc,put:()=>Sc});function XT(){return global.caFileContent}function QT(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function ZT(){return!mt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(mt.default),global.proxyUri}function mr(s,e=!1){let t=XT();t&&s.ca(t);let r=!e&&ZT();r&&s.proxy(r)}async function Bd(s,e,t={},r=Vr,n=0){let i=mt.default.post(s).send(e).timeout(r).set(t);mr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function wc(s,e,t={},r=Vr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=mt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),mr(o,i),await o}var mt,Tc,rt,Vr,YT,Dt,$s,Ve,Ws,Vs,vc,be,ew,tw,Sc,Ec,Ic,Rc,Ge=w(()=>{"use strict";mt=S(require("superagent"));$();Fd();Tc=A("http-request"),rt=Ud(),Vr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,YT=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof mt.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 Tc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};$s=rt(async(s,e={},t={},r=Vr)=>{try{let n=mt.default.delete(s).send(e).timeout(r).set(t);mr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),Ve=rt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Bd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});Ws=rt(async(s,e,t,r={},n=Vr)=>{let i=mt.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)}),mr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Vs=rt(async(s,e,t)=>{try{return(await wc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),vc=rt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Bd(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),be=rt(async(s,e,t,r,n)=>{try{return(await wc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),ew=rt((s,e,t,r)=>wc(s,e,t,r)),tw=rt(async s=>{let e=mt.default.head(s).timeout(Vr);mr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),Sc=rt(async(s,e,t={},r=Vr)=>{let n=mt.default.put(s).send(e).timeout(r).set(t);mr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),Ec=rt(async s=>{Tc.info("start to download",{url:s});let e=mt.default.get(s).timeout(YT).buffer(!0).parse(QT);mr(e);try{let t=await e;return Tc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Ic=rt.isNetworkHealthy,Rc=rt.didNetworkConnectivityTestFail});function ft(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Mt.resolve(__dirname,"../../"):s=Mt.resolve(__dirname,""),s):process.cwd()}function Ti(s,e){return _e(s)?e||Mt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Mt.basename(s)}function ze(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function sw(){try{return ad.node}catch{return""}}async function Wd(s,e,t=!0){let r=await st.promises.readdir(s,{withFileTypes:!0});await st.promises.mkdir(e,{recursive:t});for(let n of r){let i=Mt.join(s,n.name),o=Mt.join(e,n.name);n.isDirectory()?await Wd(i,o):await st.promises.copyFile(i,o)}}async function he(s){try{return await st.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Mt,jd,$d,st,rw,Nt,Ye,wi,Ac,nt,xc,Vd=w(()=>{"use strict";Mt=S(require("path"));Qa();li();jd=S(require("unzip-stream")),$d=S(require("p-retry")),st=require("fs"),rw=3;Nt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Je));return(0,$d.default)(()=>e.download(s),{retries:rw,factor:1})},Ye=async(s,e)=>{let t=await Nt(s);return st.promises.writeFile(e,t.body)};wi=async(s,e)=>{let t=Ti(s,e);return _e(s)?Ye(s,t):st.promises.copyFile(s,t)},Ac=async s=>_e(s)?Nt(s):st.promises.readFile(s),nt=async(s,e)=>await(0,st.createReadStream)(s).pipe(jd.Extract({path:e})),xc=s=>(0,st.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>Oc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>vi,MOBILE_RUN_SKIP_REASON:()=>_c,gridMessages:()=>gt,gridTypes:()=>O,mobileWeb:()=>Pc,runnerStatus:()=>Cc,runnerTestStatus:()=>me,socketEventTypes:()=>At,stepResult:()=>Hs,test:()=>kc,testRunStatus:()=>Gs,testStatus:()=>Xe,timeoutMessages:()=>Fe});var Fe,Gs,Cc,me,Xe,gt,Pc,kc,At,q,O,Hs,vi,_c,Oc,ne=w(()=>{"use strict";Fe={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Gs={COMPLETED:"completed"},Cc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Xe={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},gt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Pc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},kc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},At={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",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"},Hs={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"},vi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},_c={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Oc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"}});function qs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function nw(){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 zs,Gd,Qe,iw,ow,aw,cw,lw,Lc,Dc,Hd=w(()=>{"use strict";ne();zs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},Gd=s=>Boolean(s.resultId&&s.source==="remote-run"),Qe=(s,e)=>s.testStatus===Xe.QUARANTINE&&!Gd(e)&&!e.runQuarantinedTests;iw=s=>Boolean(s.loginMode),ow=s=>Boolean(s.tunnelOnlyMode),aw=s=>Boolean(s.createPrefechedData),cw=s=>Boolean(s.installLazyDepsMode),lw=s=>Boolean(s.agentMode),Lc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Dc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ei(s=0){return Si.default.duration(s).format("HH:mm:ss.SSS")}function Mc(s=0){return Si.default.duration(s).asSeconds()}var Si,qd,zd=w(()=>{"use strict";Si=S(require("dayjs")),qd=S(require("dayjs/plugin/duration"));Si.default.extend(qd.default)});var Ks,Gr,Jt,Kd,Hr,Jd=w(()=>{"use strict";ne();Ks=s=>!(!s||"fileName"in s),Gr=(s,e)=>{if(e===O.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Jt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Kd=s=>s===O.TESTIM_TVC,Hr=(s,e)=>Kd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Nc(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 Yd=w(()=>{"use strict"});var K={};H(K,{OSS:()=>qr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>Xa,calcPercentile:()=>Ai,copyDir:()=>Wd,delay:()=>ce,doesPathExist:()=>he,download:()=>Nt,downloadAndSave:()=>Ye,extractElementId:()=>De,getArgsOnRemoteRunFailure:()=>nw,getBrowserInfo:()=>pw,getCdpAddressForHost:()=>hr,getCliLocation:()=>ft,getDuration:()=>Ei,getDurationSec:()=>Mc,getEnginesVersion:()=>sw,getEnvironmentGitBranch:()=>gr,getLinksFromUnescapeHTML:()=>Xs,getLocalFileSizeInMB:()=>xc,getMemorySnapshot:()=>Nc,getPlanType:()=>Ri,getRunConfigByBrowserName:()=>Js,getRunnerVersion:()=>ze,getSource:()=>wi,getSourceAsBuffer:()=>Ac,getSourcePath:()=>Ti,getTestUrl:()=>qe,getUniqBrowsers:()=>qs,groupTestsByRetries:()=>Fc,guid:()=>se,hasTestPlanFlag:()=>zs,isAgentMode:()=>lw,isAppFromDevice:()=>Ks,isAppFromDeviceDisabled:()=>Hr,isCreatePrefetchedDataMode:()=>aw,isInstallLazyDepsMode:()=>cw,isLoginMode:()=>iw,isMobileProject:()=>Jt,isPromise:()=>hc,isQuarantineAndNotRemoteRun:()=>Qe,isRemoteRun:()=>Gd,isTestimVirtualGrid:()=>Kd,isTunnelOnlyMode:()=>ow,isURL:()=>_e,promiseAbort:()=>yc,promiseFromCallback:()=>Kt,promiseMap:()=>ae,promiseTimeout:()=>oe,removePropertyFromObject:()=>Ii,replaceArgsWithNoDashes:()=>Lc,sanitizeNumberValue:()=>fr,shouldBlockVirtualIosBuild:()=>Gr,spreadObjectToArgs:()=>Dc,unescapeHTML:()=>Ys,unzipFile:()=>nt});function fr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function pw(s){return s=s.toLowerCase(),Uc.find(e=>e.browserValue===s)}function Js(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Uc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Uc[0],n=qr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=qr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=qr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=qr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=qr.find(i=>i.bs.platform===t.platform))),zr.merge(r,n)}function gr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Ii(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Ii(s[r],e,t))}function De(s){return s.ELEMENT||s[Ht]}function Ri(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Fc(s=[]){return zr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=zr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Ys(s){return em.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Xs(s){return[...em.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function hr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Je));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 Xd,zr,Qd,Zd,uw,Ft,qr,Uc,Ai,em,F=w(()=>{"use strict";Xd=S(require("os")),zr=S(require("lodash")),Qd=S(require("path")),Zd=require("linkedom");Fr();Vd();Hd();zd();Qa();bc();Jd();Yd();uw=Xd.homedir(),Ft=Qd.join(uw,".testim-browser-profile"),qr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Uc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Ai=(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]};em=new Zd.DOMParser});var Bc={};H(Bc,{$schema:()=>dw,default:()=>yw,definitions:()=>mw,properties:()=>hw,required:()=>gw,type:()=>fw});var dw,mw,fw,gw,hw,yw,tm=w(()=>{dw="http://json-schema.org/draft-07/schema#",mw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},fw="object",gw=["entries"],hw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},yw={$schema:dw,definitions:mw,type:fw,required:gw,properties:hw}});async function cm(){try{return await oe(xi.promises.readFile(_i()).then(async s=>{let e=await am;return ww(e,s)}),3e4)}catch{return{}}}function ww(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Jr.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 ht(s,e,t=bw,r=void 0){return async()=>{if(!nm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await vw(e);if(i)return Qs.debug("cache hit:",{fnName:e}),i;if(Qs.debug("cache miss:",{fnName:e}),!im)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 Sw(e,o,t),o}}async function vw(s){let t=(await Oi)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Sw(s,e,t){if(jc)throw Qs.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 Oi;r[s]={value:e,expiry:Date.now()+t},om=new Promise(n=>{ki=n}),Tw(r)}catch{Qs.error("failed updating cache")}}async function Yr(){let s=await Oi;Object.keys(s).forEach(e=>{delete s[e]})}function lm(s){nm=s}function Ew(s=!0){im=s}async function um(){try{return jc=!0,await om}finally{jc=!1}}function pm(s){Pi=s,Oi=cm()}var xi,Ci,Jr,rm,Qs,Pi,sm,ki,nm,im,jc,om,am,bw,_i,Oi,Tw,dm,mm,YR,fm,Bt=w(()=>{"use strict";xi=S(require("fs")),Ci=S(require("path")),Jr=S(require("crypto"));F();rm=require("lodash");$();Qs=A("local cache"),Pi=Ci.resolve(ft(),"testim-cache"),nm=!0,im=!0,jc=!1,om=new Promise(s=>{ki=s}),am=new Promise(s=>{sm=s}),bw=1e3*60*60*3,_i=()=>Ci.resolve(Ci.resolve(Pi,"testim.cache"));Oi=cm(),Tw=(0,rm.debounce)(async s=>{let e;try{let t=await am,r=Jr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Jr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await he(Pi)||await xi.promises.mkdir(Pi,{recursive:!0}),await xi.promises.writeFile(_i(),a)}catch(t){Qs.error("failed saving cache",{err:t}),e=t}ki(e?{success:!1,error:e}:{success:!0})},200);dm=sm,mm=lm.bind(void 0,!1),YR=lm.bind(void 0,!0),fm=()=>Ew(!1)});function Li(){return{cliLocation:ft(),userInfo:Xr.userInfo(),platform:Xr.platform(),release:Xr.release()}}var Xr,$c=w(()=>{"use strict";Xr=S(require("os"));F()});function Iw(s){try{return Di.resolve(Di.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Xt(s){let e=Iw(s);return require(e)}var Di,Zs=w(()=>{"use strict";Di=S(require("path"))});function Rw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Aw(s){return/The "to" argument must be of type string./.exec(s)}function bm(s,e,t){let r=Rw(s),n=Aw(s);return r||n?(ym.info("Failed to install package due to insufficient write access",{...Li(),package:t,path:r}),console.error(`
2
+ "use strict";var xT=Object.create;var ti=Object.defineProperty;var CT=Object.getOwnPropertyDescriptor;var PT=Object.getOwnPropertyNames;var kT=Object.getPrototypeOf,_T=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)ti(s,t,{get:e[t],enumerable:!0})},sd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of PT(e))!_T.call(s,n)&&n!==t&&ti(s,n,{get:()=>e[n],enumerable:!(r=CT(e,n))||r.enumerable});return s};var S=(s,e,t)=>(t=s!=null?xT(kT(s)):{},sd(e||!s||!s.__esModule?ti(t,"default",{value:s,enumerable:!0}):t,s)),Ue=s=>sd(ti({},"__esModule",{value:!0}),s);var $e={};H($e,{log:()=>U,measure:()=>LT});function U(...s){if(!id)return;let e=Date.now();console.log(`${e-OT} ${e-nd} `,...s),nd=e}function LT(s,e){if(!id)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var id,OT,nd,We=w(()=>{"use strict";id=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,OT=Date.now(),nd=Date.now()});var Ht,Fr=w(()=>{"use strict";Ht="element-6066-11e4-a52e-4f735466cecf"});function se(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function Xa(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function _e(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 Qa=w(()=>{"use strict"});var ec,od,ad,li=w(()=>{ec={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},od={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"1.3.0","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4","coralogix-logger":"1.1.28",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.19.2",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.22.10",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"4.9.18",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","unzip-stream":"0.3.4","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},ad={node:">= 18.0.0"}});var Os,NT,cd,ld,ud,ui,Ls,pd,fe,dd,md,pi,Oe,tc,fd,di,gd,vR,SR,hd,yd,Ds,bd,Td,wd,vd,Sd,rc,sc,nc,ic,Ed,Ms,Id,oc,pe=w(()=>{"use strict";Os=process.env.SERVICES_HOST||"https://services.testim.io",NT="https://testimstatic.blob.core.windows.net",cd="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:Os,Os=process.env.SERVICES_HOST);ld=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),ud=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),ui=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ls=process.env.EDITOR_URL,pd=process.env.WEBSOCKET_HOST||`${Os}/ws`,fe=Os,dd=parseInt(process.env.LOGGER_CONSOLE||"0",10),md=parseInt(process.env.LOGGER_DEBUG||"0",10),pi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Oe=parseInt(process.env.IS_ON_PREM||"0",10),tc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,fd=parseInt(process.env.DEBUG_MODE||"0",10),di=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,gd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",vR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),SR=process.env.APPIUM_VERSION||"1.10.1",hd=process.env.GATEWAY_URL,yd=process.env.EXTENSION_SERVICES_HOST||Os,Ds=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:NT,bd=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:cd,Td=cd,wd=5*60*1e3,vd=40,Sd=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api",rc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",sc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",nc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",ic=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Ed=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Ms=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Id=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,oc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var ac={};H(ac,{CoralogixTransport:()=>Br});var Ie,Rd,UT,FT,Br,cc=w(()=>{"use strict";Ie=require("coralogix-logger"),Rd=S(require("winston-transport")),UT={debug:Ie.Severity.debug,silly:Ie.Severity.verbose,verbose:Ie.Severity.verbose,silent:Ie.Severity.verbose,info:Ie.Severity.info,http:Ie.Severity.info,warn:Ie.Severity.warning,warning:Ie.Severity.warning,error:Ie.Severity.error,critical:Ie.Severity.critical,crit:Ie.Severity.critical},FT=["err","error","reason","e"],Br=class extends Rd.default{constructor(t){t={...Br.options,...t};super(t);this.options=t,this.logger=new Ie.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:i,message:o,meta:a={},...l}=t,c={...a,...this.options.extraFields,...l},d=new Ie.Log;d.severity=UT[i],d.text=o,d.category=n,c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,o&&(c.msg=`${o}
3
+ ${c.msg}`));for(let u of FT)a[u]instanceof Error&&(c[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(c).length>0&&(o&&!m&&(c.msg=o),d.text=c),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Br.options=t}}});var gc={};H(gc,{getLogger:()=>A,sessionPlayerLoggerFormatter:()=>pc,setExecutionId:()=>dc,setProjectId:()=>mc,setProxyUri:()=>fc});function $T(){let s=[],e=()=>Promise.resolve();if(!Oe){let{CoralogixTransport:t}=(cc(),Ue(ac));t.configure(kd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}if(dd){let t={depth:5,colors:!0};s.push(new dt.transports.Console({format:dt.format.combine(dt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),dt.format.timestamp({format:"HH:mm:ss:SSS"}),dt.format.printf(r=>`[${r.timestamp}] ${r.level} ${r.category}: ${r.message} ${fi.inspect(r.meta,t)}`))}))}return[s,e]}function dc(s){lc=s}function mc(s){_d=s}function fc(s){if(Oe||!s)return;let{CoralogixTransport:e}=(cc(),Ue(ac));e.configure({...kd,proxyUri:s})}function xd(s){return{projectId:_d,time:new Date().toISOString(),...lc&&!s&&{executionId:lc}}}function A(s){return new uc(qT.child({category:s}))}var Cd,dt,fi,mi,Pd,BT,jT,kd,Ad,pc,WT,VT,GT,HT,qT,lc,_d,uc,$=w(()=>{"use strict";Cd=S(require("os")),dt=S(require("winston"));pe();fi=S(require("util")),mi=S(require("chalk")),Pd=S(require("dayjs"));F();BT=Cd.hostname(),jT=ze(),kd={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};Ad={depth:5,colors:!0},pc=(s,e,t)=>{let r=`[${(0,Pd.default)().format("HH:mm:ss:SSS")}]`,n=fi.inspect(e,Ad),i=fi.inspect(t,Ad);return`${mi.default.white(r)} ${mi.default.reset()}SessionPlayer-${mi.default.red(s)} ${n} ${i}`},[WT,VT]=$T(),GT=md?"debug":"info",HT={release:Boolean(!0),branch:"production"},qT=dt.createLogger({levels:dt.config.syslog.levels,level:GT,transports:WT,defaultMeta:{name:"runner",hostname:BT,nodeVersion:process.version,runnerVersion:jT,...HT}}),lc=null,_d=null;uc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...xd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...xd(n)})}catch{}}}waitForFlush(){return VT()}}});var bi,jr,x,qt,dr,It,gi,$r,ie,Ns,Ke,zt,Rt,hi,Wr,yi,Us,J=w(()=>{"use strict";bi=require("p-retry"),jr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},x=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},dr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},It=class extends bi.AbortError{},gi=class extends bi.AbortError{},$r=class extends bi.AbortError{},ie=class extends Error{},Ns=class extends Error{},Ke=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},zt=class extends Ke{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},hi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Wr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},yi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Us=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function hc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ce(s){return(0,Dd.setTimeout)(s)}function yc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function oe(s,e,t="Timeout Error"){ui&&!Od&&(Od=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ie(t);return e=ui?Number(ui)||6e5:e,Promise.race([s,ce(e).then(()=>{throw r})])}async function ae(s,e,{concurrency:t}={}){if(t){Ld||=(await import("p-limit")).default;let r=Ld(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Dd,Od,Ld,bc=w(()=>{"use strict";Dd=require("timers/promises");J();pe();Od=!1});var Bs,Md,zT,Fs,Nd,KT,JT,Ud,Fd=w(()=>{"use strict";Bs=S(require("lodash"));pe();Md=require("dns");$();bc();zT=A("http-request-counters"),Fs=!1,Nd=async()=>{if(Oe)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ae(s,t=>Md.promises.lookup(t)));return e||(Fs=!0),e}catch{return zT.error("network connectivity test failed"),Fs=!0,!1}},KT=Bs.throttle(Nd,10*1e3),JT=60*1e3*15,Ud=()=>{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)},JT)}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),Fs||KT(),a}}}async function r(){if(Fs||!await Nd())return!1;let n=Bs.sum([...s.fail.values()]),i=Bs.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>Fs,t}});var Je={};H(Je,{deleteReq:()=>js,didNetworkConnectivityTestFail:()=>Rc,download:()=>Ec,get:()=>be,getFullRes:()=>ew,getText:()=>Ws,head:()=>tw,isNetworkHealthy:()=>Ic,post:()=>Ve,postForm:()=>$s,postText:()=>vc,put:()=>Sc});function XT(){return global.caFileContent}function QT(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function ZT(){return!mt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(mt.default),global.proxyUri}function mr(s,e=!1){let t=XT();t&&s.ca(t);let r=!e&&ZT();r&&s.proxy(r)}async function Bd(s,e,t={},r=Vr,n=0){let i=mt.default.post(s).send(e).timeout(r).set(t);mr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function wc(s,e,t={},r=Vr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=mt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),mr(o,i),await o}var mt,Tc,rt,Vr,YT,Dt,js,Ve,$s,Ws,vc,be,ew,tw,Sc,Ec,Ic,Rc,Ge=w(()=>{"use strict";mt=S(require("superagent"));$();Fd();Tc=A("http-request"),rt=Ud(),Vr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,YT=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof mt.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 Tc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};js=rt(async(s,e={},t={},r=Vr)=>{try{let n=mt.default.delete(s).send(e).timeout(r).set(t);mr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),Ve=rt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Bd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});$s=rt(async(s,e,t,r={},n=Vr)=>{let i=mt.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)}),mr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Ws=rt(async(s,e,t)=>{try{return(await wc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),vc=rt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Bd(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),be=rt(async(s,e,t,r,n)=>{try{return(await wc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),ew=rt((s,e,t,r)=>wc(s,e,t,r)),tw=rt(async s=>{let e=mt.default.head(s).timeout(Vr);mr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),Sc=rt(async(s,e,t={},r=Vr)=>{let n=mt.default.put(s).send(e).timeout(r).set(t);mr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),Ec=rt(async s=>{Tc.info("start to download",{url:s});let e=mt.default.get(s).timeout(YT).buffer(!0).parse(QT);mr(e);try{let t=await e;return Tc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Ic=rt.isNetworkHealthy,Rc=rt.didNetworkConnectivityTestFail});function ft(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Mt.resolve(__dirname,"../../"):s=Mt.resolve(__dirname,""),s):process.cwd()}function Ti(s,e){return _e(s)?e||Mt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Mt.basename(s)}function ze(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function sw(){try{return ad.node}catch{return""}}async function Wd(s,e,t=!0){let r=await st.promises.readdir(s,{withFileTypes:!0});await st.promises.mkdir(e,{recursive:t});for(let n of r){let i=Mt.join(s,n.name),o=Mt.join(e,n.name);n.isDirectory()?await Wd(i,o):await st.promises.copyFile(i,o)}}async function he(s){try{return await st.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Mt,jd,$d,st,rw,Nt,Ye,wi,Ac,nt,xc,Vd=w(()=>{"use strict";Mt=S(require("path"));Qa();li();jd=S(require("unzip-stream")),$d=S(require("p-retry")),st=require("fs"),rw=3;Nt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Je));return(0,$d.default)(()=>e.download(s),{retries:rw,factor:1})},Ye=async(s,e)=>{let t=await Nt(s);return st.promises.writeFile(e,t.body)};wi=async(s,e)=>{let t=Ti(s,e);return _e(s)?Ye(s,t):st.promises.copyFile(s,t)},Ac=async s=>_e(s)?Nt(s):st.promises.readFile(s),nt=async(s,e)=>await(0,st.createReadStream)(s).pipe(jd.Extract({path:e})),xc=s=>(0,st.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>Oc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>vi,MOBILE_RUN_SKIP_REASON:()=>_c,gridMessages:()=>gt,gridTypes:()=>O,mobileWeb:()=>Pc,runnerStatus:()=>Cc,runnerTestStatus:()=>me,socketEventTypes:()=>At,stepResult:()=>Gs,test:()=>kc,testRunStatus:()=>Vs,testStatus:()=>Xe,timeoutMessages:()=>Fe});var Fe,Vs,Cc,me,Xe,gt,Pc,kc,At,q,O,Gs,vi,_c,Oc,ne=w(()=>{"use strict";Fe={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Vs={COMPLETED:"completed"},Cc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Xe={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},gt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Pc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},kc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},At={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",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"},Gs={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"},vi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},_c={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Oc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"}});function Hs(s,e){var t,r,n;return(t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function nw(){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 qs,Gd,Qe,iw,ow,aw,cw,lw,Lc,Dc,Hd=w(()=>{"use strict";ne();qs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},Gd=s=>Boolean(s.resultId&&s.source==="remote-run"),Qe=(s,e)=>s.testStatus===Xe.QUARANTINE&&!Gd(e)&&!e.runQuarantinedTests;iw=s=>Boolean(s.loginMode),ow=s=>Boolean(s.tunnelOnlyMode),aw=s=>Boolean(s.createPrefechedData),cw=s=>Boolean(s.installLazyDepsMode),lw=s=>Boolean(s.agentMode),Lc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Dc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ei(s=0){return Si.default.duration(s).format("HH:mm:ss.SSS")}function Mc(s=0){return Si.default.duration(s).asSeconds()}var Si,qd,zd=w(()=>{"use strict";Si=S(require("dayjs")),qd=S(require("dayjs/plugin/duration"));Si.default.extend(qd.default)});var zs,Gr,Jt,Kd,Hr,Jd=w(()=>{"use strict";ne();zs=s=>!(!s||"fileName"in s),Gr=(s,e)=>{if(e===O.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Jt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},Kd=s=>s===O.TESTIM_TVC,Hr=(s,e)=>Kd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Nc(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 Yd=w(()=>{"use strict"});var K={};H(K,{OSS:()=>qr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>Xa,calcPercentile:()=>Ai,copyDir:()=>Wd,delay:()=>ce,doesPathExist:()=>he,download:()=>Nt,downloadAndSave:()=>Ye,extractElementId:()=>De,getArgsOnRemoteRunFailure:()=>nw,getBrowserInfo:()=>pw,getCdpAddressForHost:()=>hr,getCliLocation:()=>ft,getDuration:()=>Ei,getDurationSec:()=>Mc,getEnginesVersion:()=>sw,getEnvironmentGitBranch:()=>gr,getLinksFromUnescapeHTML:()=>Ys,getLocalFileSizeInMB:()=>xc,getMemorySnapshot:()=>Nc,getPlanType:()=>Ri,getRunConfigByBrowserName:()=>Ks,getRunnerVersion:()=>ze,getSource:()=>wi,getSourceAsBuffer:()=>Ac,getSourcePath:()=>Ti,getTestUrl:()=>qe,getUniqBrowsers:()=>Hs,groupTestsByRetries:()=>Fc,guid:()=>se,hasTestPlanFlag:()=>qs,isAgentMode:()=>lw,isAppFromDevice:()=>zs,isAppFromDeviceDisabled:()=>Hr,isCreatePrefetchedDataMode:()=>aw,isInstallLazyDepsMode:()=>cw,isLoginMode:()=>iw,isMobileProject:()=>Jt,isPromise:()=>hc,isQuarantineAndNotRemoteRun:()=>Qe,isRemoteRun:()=>Gd,isTestimVirtualGrid:()=>Kd,isTunnelOnlyMode:()=>ow,isURL:()=>_e,promiseAbort:()=>yc,promiseFromCallback:()=>Kt,promiseMap:()=>ae,promiseTimeout:()=>oe,removePropertyFromObject:()=>Ii,replaceArgsWithNoDashes:()=>Lc,sanitizeNumberValue:()=>fr,shouldBlockVirtualIosBuild:()=>Gr,spreadObjectToArgs:()=>Dc,unescapeHTML:()=>Js,unzipFile:()=>nt});function fr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function pw(s){return s=s.toLowerCase(),Uc.find(e=>e.browserValue===s)}function Ks(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Uc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Uc[0],n=qr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=qr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=qr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=qr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=qr.find(i=>i.bs.platform===t.platform))),zr.merge(r,n)}function gr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Ii(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Ii(s[r],e,t))}function De(s){return s.ELEMENT||s[Ht]}function Ri(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Fc(s=[]){return zr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=zr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Js(s){return em.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Ys(s){return[...em.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function hr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Je));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 Xd,zr,Qd,Zd,uw,Ft,qr,Uc,Ai,em,F=w(()=>{"use strict";Xd=S(require("os")),zr=S(require("lodash")),Qd=S(require("path")),Zd=require("linkedom");Fr();Vd();Hd();zd();Qa();bc();Jd();Yd();uw=Xd.homedir(),Ft=Qd.join(uw,".testim-browser-profile"),qr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Uc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Ai=(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]};em=new Zd.DOMParser});var Bc={};H(Bc,{$schema:()=>dw,default:()=>yw,definitions:()=>mw,properties:()=>hw,required:()=>gw,type:()=>fw});var dw,mw,fw,gw,hw,yw,tm=w(()=>{dw="http://json-schema.org/draft-07/schema#",mw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},fw="object",gw=["entries"],hw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},yw={$schema:dw,definitions:mw,type:fw,required:gw,properties:hw}});async function cm(){try{return await oe(xi.promises.readFile(_i()).then(async s=>{let e=await am;return ww(e,s)}),3e4)}catch{return{}}}function ww(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Jr.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 ht(s,e,t=bw,r=void 0){return async()=>{if(!nm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await vw(e);if(i)return Xs.debug("cache hit:",{fnName:e}),i;if(Xs.debug("cache miss:",{fnName:e}),!im)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 Sw(e,o,t),o}}async function vw(s){let t=(await Oi)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Sw(s,e,t){if(jc)throw Xs.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 Oi;r[s]={value:e,expiry:Date.now()+t},om=new Promise(n=>{ki=n}),Tw(r)}catch{Xs.error("failed updating cache")}}async function Yr(){let s=await Oi;Object.keys(s).forEach(e=>{delete s[e]})}function lm(s){nm=s}function Ew(s=!0){im=s}async function um(){try{return jc=!0,await om}finally{jc=!1}}function pm(s){Pi=s,Oi=cm()}var xi,Ci,Jr,rm,Xs,Pi,sm,ki,nm,im,jc,om,am,bw,_i,Oi,Tw,dm,mm,JR,fm,Bt=w(()=>{"use strict";xi=S(require("fs")),Ci=S(require("path")),Jr=S(require("crypto"));F();rm=require("lodash");$();Xs=A("local cache"),Pi=Ci.resolve(ft(),"testim-cache"),nm=!0,im=!0,jc=!1,om=new Promise(s=>{ki=s}),am=new Promise(s=>{sm=s}),bw=1e3*60*60*3,_i=()=>Ci.resolve(Ci.resolve(Pi,"testim.cache"));Oi=cm(),Tw=(0,rm.debounce)(async s=>{let e;try{let t=await am,r=Jr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Jr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await he(Pi)||await xi.promises.mkdir(Pi,{recursive:!0}),await xi.promises.writeFile(_i(),a)}catch(t){Xs.error("failed saving cache",{err:t}),e=t}ki(e?{success:!1,error:e}:{success:!0})},200);dm=sm,mm=lm.bind(void 0,!1),JR=lm.bind(void 0,!0),fm=()=>Ew(!1)});function Li(){return{cliLocation:ft(),userInfo:Xr.userInfo(),platform:Xr.platform(),release:Xr.release()}}var Xr,$c=w(()=>{"use strict";Xr=S(require("os"));F()});function Iw(s){try{return Di.resolve(Di.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Xt(s){let e=Iw(s);return require(e)}var Di,Qs=w(()=>{"use strict";Di=S(require("path"))});function Rw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Aw(s){return/The "to" argument must be of type string./.exec(s)}function bm(s,e,t){let r=Rw(s),n=Aw(s);return r||n?(ym.info("Failed to install package due to insufficient write access",{...Li(),package:t,path:r}),console.error(`
4
4
 
5
5
  Testim failed installing the package ${t||""} due to insufficient permissions.
6
6
  This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
7
7
  Testim had missing write access to ${r||e}
8
8
 
9
9
  `),!0):!1}async function Tm(s){return(await hm(`npm view ${s} version`)).stdout.trim()}function Gc(s){try{return Xt(s)}catch{return!1}}function wm(s,e){return require(yr.join(s,`./node_modules/${e}/package.json`)).version}function vm(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=vm(s[e]);if(t)return t}}function Sm(s){let e=require(yr.join(s,"package.json"));if(!("exports"in e))return"";let t=vm(e);if(!t)throw new yi(e.name);return t}async function Ni(s,e,t){let r=yr.join(s,"npm-shrinkwrap.json"),n=yr.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await he(r)&&(await Vc.promises.rename(r,n),i=!0)}catch{}return await hm(`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 Wr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await Vc.promises.rename(n,r)}catch{}}}function Em(s,e,t,r){return new Promise((n,i)=>{let o=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",c="",d="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),m=(0,Mi.spawn)("node",[Wc,"i","--prefix",s,...d,...e,...o],a);m.stderr.pipe(process.stderr),m.stdout.pipe(process.stdout),m.stdout.on("data",u=>{l+=u}),m.stderr.on("data",u=>{c+=u}),m.on("close",u=>{var f,h;if(u){let g;try{let y=(f=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(c))==null?void 0:f[1],T=(h=/No matching version found for (\S+)@/gm.exec(c))==null?void 0:h[1];y||T?g=`404 Not Found - GET https://registry.npmjs.org/${T??y} - Not found`:bm(c,Wc)?g=`insufficient write access in location ${Wc}`:g=`Npm Installation closed with exit code ${u} with error: ${c}`}catch{g=`Npm Install closed with exit code ${u}
10
- stdout: ${l} stderr: ${c}`}ym.info(`Npm Install closed with exit code ${u}`,{message:g,stderr:c}),i(new Rt(g))}else n(l)}),setTimeout(()=>{try{m.kill()}finally{i(new ie)}},r)})}var Vc,yr,gm,Mi,hm,ym,Wc,Qr=w(()=>{"use strict";Vc=S(require("fs")),yr=S(require("path"));F();gm=require("util"),Mi=require("child_process");$();$c();Zs();J();hm=(0,gm.promisify)(Mi.exec),ym=A("cli-service");Wc=yr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var B,Rm,xw,Cw,Pw,Im,Fi,Hc,L,le=w(()=>{"use strict";B=S(require("rox-node"));$();F();pe();Rm=A("FeatureFlagsService"),xw=!Oe&&!0&&!hd,Cw=2e4,Pw=60*60*24,Im=["labs","disabled","enabled"],Fi=class extends B.default.Variant{constructor(e="disabled"){super(e,Im)}getValue(){let e=super.getValue();return Im.includes(e)?e:(Rm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Hc=class{constructor(){this.flags={useNewWSCLI:new B.default.Flag,useSafariWebdriverVisibilityChecks:new B.default.Flag,useClickimVisibilityChecks:new B.default.Flag,runGetElementCodeInAut:new B.default.Flag,enableFrameSwitchOptimization:new B.default.Flag,maximumJsResultSize:new B.default.Configuration(2e3*1024),skipFileInputClicks:new B.default.Flag,errorMessageOnBadNetwork:new B.default.Flag(!0),warnOnBadNetwork:new B.default.Flag(!1),overrideAzureStorageUrl:new B.default.Flag,autoSaveDownloadFileFireFox:new B.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new B.default.Flag(!0),experimentalPreCodeCompilation:new B.default.Flag(!0),experimentalAsyncCustomCode:new B.default.Flag,useSameBrowserForMultiTests:new Fi("labs"),highSpeedMode:new Fi,usePortedHtml5DragDrop:new B.default.Flag,testNamesToBeforeSuiteHook:new B.default.Flag,addCustomCapabilities:new B.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new B.default.Variant("{}"),LTNetworkCapabilities:new B.default.Flag,downloadToBase64:new B.default.Flag,publicGridURL:new B.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new B.default.Flag(!0),unsupportedCapsFields:new B.default.Variant("[]"),dontFocusOnInit:new B.default.Flag,retryOnSeleniumHubError:new B.default.Flag,enableLambdaTestTunnelNTLM:new B.default.Flag,enableLambdaTestTunnelSkipUpgrade:new B.default.Flag,tdcHsPreventNetworkCapture:new B.default.Flag,headSpinTdcEnableFlagCapability:new B.default.Flag,enableBatchTDC:new B.default.Flag,enableBatchHeadSpin:new B.default.Flag,clearRunnerFileCache:new B.default.Flag,forceTurboModeIfNeeded:new B.default.Flag,redisSlotManager:new B.default.Flag,tunnelBinaryNewVersion:new B.default.Flag(!1),encryptedCredentials:new B.default.Flag,computePackagePathFromPackageJsonExports:new B.default.Flag,sendExtensionOnEdgeNonLinux:new B.default.Flag,enableAppium2pCloudy:new B.default.Flag,reuseCliPkgInstallFolder:new B.default.Flag,getPublicIpFrom3rdPartyServices:new B.default.Flag,chromedriverCdnBinariesUrl:new B.default.Variant(""),sfdcHybridCompany:new B.default.Flag,allowFixingAppIdStructure:new B.default.Flag,enableAppium2BrowserStack:new B.default.Flag,increaseTDCRequestTimeout:new B.default.Flag,accessTokenExpiryMargin:new B.default.Configuration(300*1e3),useMV3Extension:new B.default.Flag,testimHeadlessExtensionDownloadUrl:new B.default.Variant("",[]),useStepResultIdForStepTransactions:new B.default.Flag,applyMobileRestrictionFromDate:new B.default.Configuration(17235072e5),removeMobileTrialRestrictions:new B.default.Flag,appiumConnectionRetryCount:new B.default.Configuration(0),appiumConnectionRequestTimeout:new B.default.Configuration(12e4)},B.default.register("default",this.flags)}setProjectId(e){B.default.setCustomStringProperty("projectId",e)}setProjectType(e){B.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){B.default.setCustomStringProperty("productType",e)}setCompanyId(e){B.default.setCustomStringProperty("companyId",e)}setPlanType(e){B.default.setCustomStringProperty("planType",e)}setIsPOC(e){B.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){B.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){B.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!xw)return;let e={fetchIntervalInSec:Pw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return oe(B.default.setup(gd,e),Cw).catch(t=>Rm.error("failed to get feature flag status",t))}},L=new Hc});var Pm={};H(Pm,{install:()=>_w,isReady:()=>Lw,start:()=>Ow});var Am,xm,Cm,zc,qc,kw,_w,Ow,Lw,km=w(()=>{"use strict";Am=S(require("fkill")),xm=S(require("p-retry"));Qr();Ge();F();Zs();le();Cm="chromedriver",zc=9515,qc=`http://localhost:${zc}/wd/hub`,kw=[`--port=${zc}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],_w=async()=>{let s=L.flags.chromedriverCdnBinariesUrl.getValue(),e=_e(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await Ni(ft(),`${Cm} --detect_chromedriver_version ${e}`)},Ow=async()=>{process.env.NODE_OPTIONS="",await(0,Am.default)(`:${zc}`,{silent:!0}),await Xt(Cm).start(kw,!0)},Lw=async({chromeBinaryLocation:s})=>{await(0,xm.default)(async()=>{var n;let e=await be(`${qc}/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:`${qc}/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 $s(`${qc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var tn={};H(tn,{getSessionPlayerFolder:()=>Xc,prepareChromeDriver:()=>en,prepareCustomExtension:()=>Jc,prepareExtension:()=>Yc,preparePlayer:()=>br});async function Jc(s,e=!1){if(!s)return;if(_e(s)){let n=Zr.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Dw(s)>Kc&&!e)throw new x(_m);return await Ye(s,n),n}let t=Zr.resolve(s);if(!Lm.existsSync(t))throw new x(`Failed to find custom extension in location: ${t}`);if(xc(t)>Kc&&!e)throw new x(_m);return t}async function Dw(s){let e=(Ge(),Ue(Je));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Bi.warn("failed to download custom extension",{err:t}),new x(`Failed to download custom extension from location: ${s}`)}}function Yc(s){Bi.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ti(t)}));return ht(()=>ae(e,({location:t,path:r})=>wi(t,r)),"prepareExtension",Mm,e)()}async function en(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(km(),Pm));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 Wr||(Bi.error(a,{...s,...Li(),error:(0,Dm.serializeError)(o)}),console.log(`
10
+ stdout: ${l} stderr: ${c}`}ym.info(`Npm Install closed with exit code ${u}`,{message:g,stderr:c}),i(new Rt(g))}else n(l)}),setTimeout(()=>{try{m.kill()}finally{i(new ie)}},r)})}var Vc,yr,gm,Mi,hm,ym,Wc,Qr=w(()=>{"use strict";Vc=S(require("fs")),yr=S(require("path"));F();gm=require("util"),Mi=require("child_process");$();$c();Qs();J();hm=(0,gm.promisify)(Mi.exec),ym=A("cli-service");Wc=yr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var B,Rm,xw,Cw,Pw,Im,Fi,Hc,L,le=w(()=>{"use strict";B=S(require("rox-node"));$();F();pe();Rm=A("FeatureFlagsService"),xw=!Oe&&!0&&!hd,Cw=2e4,Pw=60*60*24,Im=["labs","disabled","enabled"],Fi=class extends B.default.Variant{constructor(e="disabled"){super(e,Im)}getValue(){let e=super.getValue();return Im.includes(e)?e:(Rm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Hc=class{constructor(){this.flags={useNewWSCLI:new B.default.Flag,useSafariWebdriverVisibilityChecks:new B.default.Flag,useClickimVisibilityChecks:new B.default.Flag,runGetElementCodeInAut:new B.default.Flag,enableFrameSwitchOptimization:new B.default.Flag,maximumJsResultSize:new B.default.Configuration(2e3*1024),skipFileInputClicks:new B.default.Flag,errorMessageOnBadNetwork:new B.default.Flag(!0),warnOnBadNetwork:new B.default.Flag(!1),overrideAzureStorageUrl:new B.default.Flag,autoSaveDownloadFileFireFox:new B.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new B.default.Flag(!0),experimentalPreCodeCompilation:new B.default.Flag(!0),experimentalAsyncCustomCode:new B.default.Flag,useSameBrowserForMultiTests:new Fi("labs"),highSpeedMode:new Fi,usePortedHtml5DragDrop:new B.default.Flag,testNamesToBeforeSuiteHook:new B.default.Flag,addCustomCapabilities:new B.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new B.default.Variant("{}"),LTNetworkCapabilities:new B.default.Flag,downloadToBase64:new B.default.Flag,publicGridURL:new B.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new B.default.Flag(!0),unsupportedCapsFields:new B.default.Variant("[]"),dontFocusOnInit:new B.default.Flag,retryOnSeleniumHubError:new B.default.Flag,enableLambdaTestTunnelNTLM:new B.default.Flag,enableLambdaTestTunnelSkipUpgrade:new B.default.Flag,tdcHsPreventNetworkCapture:new B.default.Flag,headSpinTdcEnableFlagCapability:new B.default.Flag,enableBatchTDC:new B.default.Flag,enableBatchHeadSpin:new B.default.Flag,clearRunnerFileCache:new B.default.Flag,forceTurboModeIfNeeded:new B.default.Flag,redisSlotManager:new B.default.Flag,tunnelBinaryNewVersion:new B.default.Flag(!1),encryptedCredentials:new B.default.Flag,computePackagePathFromPackageJsonExports:new B.default.Flag,sendExtensionOnEdgeNonLinux:new B.default.Flag,enableAppium2pCloudy:new B.default.Flag,reuseCliPkgInstallFolder:new B.default.Flag,getPublicIpFrom3rdPartyServices:new B.default.Flag,chromedriverCdnBinariesUrl:new B.default.Variant(""),sfdcHybridCompany:new B.default.Flag,allowFixingAppIdStructure:new B.default.Flag,enableAppium2BrowserStack:new B.default.Flag,increaseTDCRequestTimeout:new B.default.Flag,accessTokenExpiryMargin:new B.default.Configuration(300*1e3),useMV3Extension:new B.default.Flag,testimHeadlessExtensionDownloadUrl:new B.default.Variant("",[]),useStepResultIdForStepTransactions:new B.default.Flag,applyMobileRestrictionFromDate:new B.default.Configuration(17235072e5),removeMobileTrialRestrictions:new B.default.Flag,appiumConnectionRetryCount:new B.default.Configuration(0),appiumConnectionRequestTimeout:new B.default.Configuration(12e4)},B.default.register("default",this.flags)}setProjectId(e){B.default.setCustomStringProperty("projectId",e)}setProjectType(e){B.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){B.default.setCustomStringProperty("productType",e)}setCompanyId(e){B.default.setCustomStringProperty("companyId",e)}setPlanType(e){B.default.setCustomStringProperty("planType",e)}setIsPOC(e){B.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){B.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){B.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!xw)return;let e={fetchIntervalInSec:Pw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return oe(B.default.setup(gd,e),Cw).catch(t=>Rm.error("failed to get feature flag status",t))}},L=new Hc});var Pm={};H(Pm,{install:()=>_w,isReady:()=>Lw,start:()=>Ow});var Am,xm,Cm,zc,qc,kw,_w,Ow,Lw,km=w(()=>{"use strict";Am=S(require("fkill")),xm=S(require("p-retry"));Qr();Ge();F();Qs();le();Cm="chromedriver",zc=9515,qc=`http://localhost:${zc}/wd/hub`,kw=[`--port=${zc}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],_w=async()=>{let s=L.flags.chromedriverCdnBinariesUrl.getValue(),e=_e(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await Ni(ft(),`${Cm} --detect_chromedriver_version ${e}`)},Ow=async()=>{process.env.NODE_OPTIONS="",await(0,Am.default)(`:${zc}`,{silent:!0}),await Xt(Cm).start(kw,!0)},Lw=async({chromeBinaryLocation:s})=>{await(0,xm.default)(async()=>{var n;let e=await be(`${qc}/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:`${qc}/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(`${qc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var en={};H(en,{getSessionPlayerFolder:()=>Xc,prepareChromeDriver:()=>Zs,prepareCustomExtension:()=>Jc,prepareExtension:()=>Yc,preparePlayer:()=>br});async function Jc(s,e=!1){if(!s)return;if(_e(s)){let n=Zr.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Dw(s)>Kc&&!e)throw new x(_m);return await Ye(s,n),n}let t=Zr.resolve(s);if(!Lm.existsSync(t))throw new x(`Failed to find custom extension in location: ${t}`);if(xc(t)>Kc&&!e)throw new x(_m);return t}async function Dw(s){let e=(Ge(),Ue(Je));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Bi.warn("failed to download custom extension",{err:t}),new x(`Failed to download custom extension from location: ${s}`)}}function Yc(s){Bi.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ti(t)}));return ht(()=>ae(e,({location:t,path:r})=>wi(t,r)),"prepareExtension",Mm,e)()}async function Zs(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(km(),Pm));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 Wr||(Bi.error(a,{...s,...Li(),error:(0,Dm.serializeError)(o)}),console.log(`
11
11
  1. If you don't have Chrome, please install it from https://www.google.com/chrome.
12
12
  2. If Chrome is installed, please verify it's binary directory:
13
13
  - installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
14
14
  - exists in your PATH environment variables.
15
15
  3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
16
- 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 Mw(){let s=`${Ms}/extension/sessionPlayer_LATEST_RELEASE`;return(await Nt(s)).body.toString("utf8")}async function Nw(s,e){if(!_e(s)||_e(s)&&e||Oe)return s;let t=await Mw();return`${s}-${t}`}function Xc(){let s=ft();return Zr.resolve(s,"testim-bin")}function Uw(){let s=Xc();return Zr.resolve(s,"sessionPlayer.zip")}async function Nm(s,e,t=!1){try{return await wi(s,e),await nt(e,Xc())}catch(r){if(t)throw r;return await Nm(s,e,!0)}}async function br(s,e){Bi.info("prepare player",{location:s,canary:e});let t=Uw();return ht(async()=>{let r=await Nw(s,e);return await Nm(r,t),{}},"preparePlayer",Mm,[s,e,t])()}var Om,Lm,Zr,Dm,Bi,Mm,Kc,_m,rn=w(()=>{"use strict";Om=S(require("ms")),Lm=S(require("fs")),Zr=S(require("path"));pe();Bt();Dm=require("serialize-error");$();$c();J();F();Bi=A("prepare runner and testim start"),Mm=(0,Om.default)("0.5 day"),Kc=16,_m=`The size of the custom extension is more than ${Kc}MB`});function Fw(){let s=sn.type().toLowerCase();return s==="darwin"?sn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?sn.arch()==="x64"?"win64":"win32":"linux"}async function $i(){let s=Fw(),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 x(`Unsupported platform: ${s}`);let r=parseInt(nn,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]}/${nn}/${n[s]}.zip`,a=ji.join(Qc,n[s]),l=`${a}.zip`,c=ji.join(a,i[s]);if(await he(c))return c;if(!await he(l)){let m=(0,Zc.default)("Downloading Chromium").start();try{await Um.promises.mkdir(Qc),await Ye(o,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Zc.default)("Extracting Chromium").start();try{await nt(l,Qc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Um,sn,ji,Zc,nn,Qc,el=w(()=>{"use strict";Um=S(require("fs")),sn=S(require("os")),ji=S(require("path")),Zc=S(require("ora"));J();F();nn="1000968",Qc=ji.join(Ft,`chrome-${nn}`)});async function jm(s,e){return Tr=s,nl=e,await tl()}function $m(s,e){Tr=e.projectId,nl=e.token,on=e.userAccessKey,it=s.token,cn=il(it),ln=s.refreshToken,rl=s.ngrokToken,sl=s.isNgrokWhitelisted,Fm=e.publicIp,Bm=e.initializedFromCache}function jw(s=Tr,e=nl){return ht(()=>(an.info("request to get cli token from server"),Ve({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Bw*10,{projectId:s,token:e})()}async function $w(){an.info("request to refresh JWT cli token from server");let s=await Ve({url:`${fe}/auth/refreshToken`,body:{token:it,refreshToken:ln}});return it=s.token,cn=il(it),s.refreshToken&&(ln=s.refreshToken),it}async function tl(){try{let s=await jw();return an.info("successfully get cli token from server"),it=s.token,cn=il(it),ln=s.refreshToken,rl=s.ngrokToken,sl=s.isNgrokWhitelisted,it}catch(s){throw s.message.includes("Unauthorized")?new x("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."):(an.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Tr}),new x(`While trying to retrieve CLI token, caught error: ${s}`))}}function il(s){return require("jsonwebtoken").decode(s).exp*1e3}async function xt(){if(!cn)return tl();let s=L.flags.accessTokenExpiryMargin.getValue();if(cn<Date.now()+4*s)try{return await $w()}catch(e){return an.error("failed to refresh token, executing fallback",e),tl()}return it}function Wi(){return ln}function wr(){return it?{uid:require("jsonwebtoken").decode(it).id,ngrokToken:rl,isNgrokWhitelisted:sl}:{}}async function Vi(){if(!on||!Tr)return;if(await ol({userAccessKey:on,projectId:Tr}))return on;let e=`user access key "${on}" is invalid for project "${Tr}"`;throw new x(e)}function Gi(){return Fm}function Hi(){return Bm}var an,it,cn,ln,rl,sl,Tr,nl,on,Fm,Bm,Bw,ot=w(()=>{"use strict";pe();Ge();Bt();J();$();ge();le();an=A("testim-custom-token"),Tr=null,nl=null,Bw=5*60*1e3});var Wm={};H(Wm,{isCi:()=>es});var es,qi=w(()=>{"use strict";es=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Ae={};H(Ae,{addTestRetry:()=>Pl,clearTestResult:()=>Al,deleteCloudflareTunnel:()=>Ll,fetchLambdatestConfig:()=>El,fixGridAppIDStructure:()=>Ul,forceUpdateCloudflareTunnelRoutes:()=>Ol,getAllGrids:()=>Sl,getAppDetails:()=>mn,getApplitoolsIntegrationData:()=>kl,getBrowserStackSessionMetaData:()=>Xw,getCloudflareTunnel:()=>_l,getEditorUrl:()=>Kw,getGridById:()=>Ki,getGridByName:()=>wl,getHybridGridProvider:()=>Tl,getLabFeaturesByProjectId:()=>Il,getMobileDevicesFromGrid:()=>Ml,getRealData:()=>Rl,getS3Artifact:()=>pn,getS3ArtifactText:()=>cl,getSuiteTestList:()=>fl,getTestPlan:()=>zw,getTestPlanTestList:()=>ml,getTestResults:()=>Sr,getUsageForCurrentBillingPeriod:()=>gl,initializeUserWithAuth:()=>vl,isTestResultCompleted:()=>hl,keepAliveCompanySlots:()=>$l,keepAliveGrid:()=>yl,loadSfdcCredential:()=>ll,loadTest:()=>dn,releaseCompanySlot:()=>Bl,releaseGridSlot:()=>bl,reportExecutionFinished:()=>zi,reportExecutionStarted:()=>dl,requestCompanySlot:()=>Fl,saveRemoteStep:()=>xl,saveTestPlanResult:()=>ul,updateCompanySlot:()=>jl,updateExecutionTests:()=>pl,updateRemoteRunFailure:()=>Dl,updateTestDataArtifact:()=>Yi,updateTestResult:()=>Ji,updateTestStatus:()=>vr,uploadAppToGrid:()=>Nl,uploadRunDataArtifact:()=>Cl,validateUserAccessKey:()=>ol});async function ts(){let s=await xt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await ts(),o={...t,...i};return Ve({url:`${fe}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function Gw(s,e,t,r={},n=void 0){let i=await ts(),o={...r,...i};return await Ws(`${fe}${s||""}`,e,t,o,n)}async function un(s,e){let t=await ts();return await Sc(`${fe}${s||""}`,e,t)}async function Hw(s,e){let t=await ts();return await $s(`${fe}${s||""}`,e,t)}async function qw(s,e){let t=await ts();return await Vs(`${fe}${s||""}`,e||void 0,t)}async function Se(s,e,t,r){let n=await ts();return await be(`${fe}${s||""}`,e||void 0,n,r,t)}function pn(s,e){return(0,X.default)(()=>Se(`/storage${s}`,null,{isBinary:!0},e),{retries:ee,factor:1})}function cl(s){return(0,X.default)(()=>qw(`/storage${s}`))}async function zw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,X.default)(()=>Se("/testPlan",{projectId:s,name:e.join(",")}),{retries:ee,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function ll({branch:s,projectId:e}){let t=await(0,X.default)(()=>Se(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:ee,factor:1});return t==null?void 0:t.sfdcCredential}function dn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,X.default)(()=>Se(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:ee,factor:1})}function ul(s,e,t){return(0,X.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:ee,factor:1})}function vr(s,e,t,r,n,i,o=ee){return(0,X.default)(()=>un("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:Ww,...i}),{retries:o,factor:1})}function pl(s,e,t,r,n,i,o,a){return(0,X.default)(()=>un("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:ee,factor:1})}async function dl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(qi(),Wm));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function zi(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,X.default)(()=>un("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:ee,factor:1})}async function ml(s,e,t,r,n){return(0,X.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:ee,factor:1})}function fl({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,X.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:ee,factor:1})}async function mn({appId:s,projectId:e}){try{return await(0,X.default)(()=>Se(`/mobile-app/app/${s}?projectId=${e}`),{retries:ee,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function gl(s){try{return await(0,X.default)(()=>Se(`/plan/project/${s}/usage-current-billing-period`),{retries:ee,factor:1})}catch(e){jt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function hl(s,e,t){return(0,X.default)(()=>Se(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ee,factor:1})}function Sr(s,e,t,r){return(0,X.default)(()=>Se(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:ee,factor:1})}function yl(s,e){return Re({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function bl(s,e,t,r,n){return Re({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Tl(s){return Re({url:"/grid/hybrid/provider",body:s})}function wl(s,e,t,r,n){return(0,X.default)(()=>Se("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}function Ki(s,e,t,r,n){return(0,X.default)(()=>Se(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}async function vl({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a}){var l,c;try{return await(0,X.default)(()=>Ve({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a}}),{retries:ee,factor:1})}catch(d){throw jt.error("error initializing info from server",d),(l=d==null?void 0:d.message)!=null&&l.includes("Bad Request")?new x("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."):(c=d==null?void 0:d.code)!=null&&c.includes("ENOTFOUND")?new x("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):d}}async function Kw(){if(Ds)return{editorUrl:Ds};try{return await(0,X.default)(()=>Se("/system-info/editor-url"),{retries:ee,onFailedAttempt:s=>{if(s.attemptNumber>=ee)throw s},factor:1})}catch(s){return jt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Sl(s){return(0,X.default)(()=>Se("/grid",{companyId:s}),{retries:ee,factor:1})}function Rl(s,e,t){return(0,X.default)(()=>Se(`/real-data/${e}?${t}&projectId=${s}`),{retries:ee,factor:1})}function Ji(s,e,t,r,n){return(0,X.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:ee,factor:1})}function Al(s,e,t,r){return(0,X.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:ee,factor:1})}function xl(s,e,t,r){return(0,X.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:ee,factor:1})}function Jw(s){return s.startsWith("/")?s:`/${s}`}function Yw(s,e,t){let r=Jw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Gm(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${se()}${o||""}`,l=`${e}/${t}/${a}`,c=Yw(l,"test-result-artifacts",s),d=Buffer.from(Vm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,X.default)(()=>Gw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ee,factor:1}),c}function Pl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,X.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:ee,factor:1})}async function kl(s){try{return await Se(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return jt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function _l(s,e){try{return await un("/tunnel",{companyId:s,routes:e})}catch(t){return jt.warn("could'nt get tunnel.",{err:t}),{}}}async function Ol(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}async function Ll(s,e){try{return await Hw(`/tunnel/${e}`,{companyId:s})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}function Dl(s){return Ve({url:`${fe}/result/remoteRunFailure`,body:s})}async function Ml({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${Vw}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,X.default)(()=>Se(i,{projectId:s}),{retries:ee,factor:1})}catch(o){return jt.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Nl({projectId:s,gridId:e,app:t,timeout:r}){return(0,X.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:ee,factor:1})}async function Ul(s){return(0,X.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:ee,factor:1})}async function Fl(s,e){return(0,X.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:ee,factor:1})}async function Bl(s,e,t){return(0,X.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:ee,factor:1})}async function jl(s,e,t){return(0,X.default)(()=>un("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:ee,factor:1})}function $l(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function Xw(s,e){return await be(`${Ns}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function ol(s){try{return await Se("/v2/project/validateUserAccessKey",s),!0}catch(e){return jt.error("error validating user access key",{error:e}),!1}}var Zt,Vm,X,al,Ww,jt,ee,Vw,El,Il,Cl,Yi,ge=w(()=>{"use strict";Zt=S(require("lodash")),Vm=S(require("pako"));F();pe();ne();Ge();ot();X=S(require("p-retry")),al=S(require("object-hash"));J();$();Ww=ze(),jt=A("testim service api"),ee=3,Vw="/grid";El=async()=>(0,X.default)(()=>Se("/grid/lt/config"),{retries:ee,factor:1}),Il=async s=>(0,X.default)(()=>Se(`/labFeature/v2/project/${s}`),{retries:ee,factor:1});Cl=Zt.memoize(async(s,e,t,r)=>{if(!Zt.isEmpty(r))return await Gm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,al.default)(r)}:${e}:${t}`),Yi=Zt.memoize(async(s,e,t,r,n)=>!r||Zt.isEmpty(r)?void 0:await Gm(s,e,t,JSON.stringify((()=>{let o=Zt.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{o[l]&&Object.assign(o,{[l]:kc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,al.default)(r)}:${e}:${t}`)});async function Hm(){let s=await Promise.any(Qw.map(async e=>{try{return await be(e)}catch{return null}}));return s==null?void 0:s.ip}var Qw,qm=w(()=>{"use strict";Ge();Qw=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});var er={};H(er,{getSessionPlayer:()=>Q,options:()=>Vl});var Xi,Vl,Wl,Q,Te=w(()=>{"use strict";Xi=require("path");$();Vl={playerPath:void 0},Q=()=>{if(Wl)return Wl;let s=(We(),Ue($e));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(rn(),Ue(tn)),t=e(),r=Vl.playerPath?(0,Xi.resolve)(Vl.playerPath,"src/background/sessionPlayerInit.ts"):(0,Xi.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Wl=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(pc),n}});function tv(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(Te(),Ue(er)).getSessionPlayer()}catch{}})}async function fn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?ev:Zw,f=null;if(L.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{f=await Hm()}catch(y){zm.error("failed to get public ip",y)}let h=!0;U("before initializeUserWithAuth");let g=await ht(async()=>(tv(a),h=!1,await vl({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:f,gridId:l,grid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:f})();return s.publicIps=[g.clientPublicIp],U("after initializeUserWithAuth"),f&&g.clientPublicIp&&g.clientPublicIp!==f&&(zm.error("public ip mismatch",{publicIpFromExternalService:f,publicIpFromServices:g.clientPublicIp}),s.publicIps.push(f)),$m(g.authData,{projectId:e,token:t,userAccessKey:r,publicIp:g.clientPublicIp,initializedFromCache:h}),g}var zm,Zw,ev,Km=w(()=>{"use strict";We();ge();Bt();ot();qm();ne();$();le();zm=A("initializeUserWithAuth"),Zw=1e3*60*5,ev=1e3*60*60*10});async function Xm(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await $i():s.chromeBinaryLocation,e=en({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await Yc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Jc(s.installCustomExtension,n)}return await e,t}async function Qm(s){var o;rv.info("prepare MockNetwork",{location:s});let e=await Ac(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Jm*1e6)throw new Error(`${Gl} exceeded ${Jm}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Gl} cannot be parsed.${Qi.EOL}${a}`)}let n=new Ym.default;if(!n.validate(Bc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Qi.EOL);throw new Error(`${Gl} is malformed.${Qi.EOL}${a}`)}return r.entries}var Qi,Ym,Jm,Gl,rv,Hl=w(()=>{"use strict";Qi=S(require("os"));F();tm();rn();Ym=S(require("ajv"));ne();el();Km();Jm=1,Gl="JSON file supplied to --mock-network-pattern",rv=($(),Ue(gc)).getLogger("prepare runner")});function ef(s,e=process){async function t(r){await oe(ae(Zm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{gn.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(gn.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",()=>{gn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw gn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw gn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function rs(s){Zm.push(s)}var gn,Zm,hn=w(()=>{"use strict";$();F();gn=A("process-handler"),Zm=[]});function Jl(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?Td:Ms}/extension/testim-headless${t}`,n=L.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project});return n||(cv.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),n="https://testimstatic.blob.core.windows.net/extension/testim-headless.zip"),!(s.ext||s.extensionPath)&&n&&(r=n,s.testimHeadlessExtensionDownloadUrl=n),{chrome:r,"edge-chromium":r}}function of(s){let{chrome:e}=Jl(s,!1);return e}function eo(s){let e=`${Ms}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var cv,yn=w(()=>{"use strict";pe();le();$();cv=A("runOptionsUtils")});function pf(s){Oe||(s!=null&&s.userId||(s={anonymousId:uf}),lf.identify(s))}function yt(s,e){return bn("ci",s,e)}function bn(s,e,t){if(Oe)return;let r=s?{userId:s}:{anonymousId:uf};lf.track(Object.assign(r,{event:e,properties:t}))}var cf,lf,uf,ss=w(()=>{"use strict";pe();cf=require("@segment/analytics-node"),lf=new cf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),uf=require("crypto").randomBytes(20).toString("hex")});function df(s){return s.start&&bn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function mf(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new x("Agent port is not number");let t=eo(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 ff=w(()=>{"use strict";yn();ss();J()});var gf,uv,pv,Yl,hf=w(()=>{"use strict";gf="TST_CREDS",uv=["username","password"],pv="$encrypted",Yl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of uv)t[r]={[pv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(gf)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[gf]:this.proxyPlaceholder})}}});async function bf(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await fl({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 Xl(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 Ql(s,e){let t=s.mode===q.EXTENSION?Er:wn,r=yf.difference(qs(s,e),t);if(r.length>0)throw yt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new x(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var yf,Er,wn,to=w(()=>{"use strict";yf=S(require("lodash"));F();ss();ge();J();ne();Er=["edge-chromium","chrome"],wn=[...Er,"firefox","safari","safari technology preview"]});function so(s){let{platform:e}=process;e==="win32"?(0,ro.exec)(`start chrome ${s}`):e==="darwin"?(0,ro.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,ro.exec)(`google-chrome ${s}`)}var ro,Zl=w(()=>{"use strict";ro=require("child_process")});var nu={};H(nu,{doLogin:()=>su,getProjectId:()=>dv,getToken:()=>mv});async function dv(){return vf("projectId")}async function mv(){return vf("token")}function wf(s,e){return Promise.race([s,ce(e).then(()=>{throw new ie("timeout")})])}async function fv(){let s=(await import("express")).default(),e=async function(){return wf(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Ae)),{editorUrl:n}=await r();so(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function su({overwriteExisting:s=!0,projects:e=null}={}){let t=eu.homedir(),r=tu.join(t,".testim");if(await he(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await wf(fv(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Tf(r,i);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=c.project.ci.token,i.projectId=c.project.id,await Tf(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Tf(s,e){await ru.promises.writeFile(s,no.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function vf(s){let e=eu.homedir(),t=tu.join(e,".testim"),r=await he(t),n={};if(r)try{n=no.parse((await ru.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var eu,tu,no,ru,io=w(()=>{"use strict";eu=S(require("os")),tu=S(require("path")),no=S(require("yaml"));F();ru=require("fs");J();Zl()});var Pf={};H(Pf,{process:()=>Sv});var ou,Rf,oo,Af,$t,Ne,xf,gv,Me,lu,hv,yv,Ef,Cf,bv,au,cu,uu,iu,Ct,Tv,p,wv,vv,If,Sv,kf=w(()=>{"use strict";ou=S(require("ms")),Rf=S(require("chalk")),oo=S(require("fs")),Af=S(require("url")),$t=S(require("lodash")),Ne=S(require("path"));F();yn();ff();Bt();xf=require("commander");ne();J();Fr();F();le();hf();to();gv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(s,e)=>(e.push(s),e),lu=new xf.Command,hv=s=>s.split(","),yv=(s,e)=>!s||s.length===0?e:s,Ef=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Cf=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}lu.help(g=>g.split(`
16
+ 4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function Mw(){let s=`${Ds}/extension/sessionPlayer_LATEST_RELEASE`;return(await Nt(s)).body.toString("utf8")}async function Nw(s,e){if(!_e(s)||_e(s)&&e||Oe)return s;let t=await Mw();return`${s}-${t}`}function Xc(){let s=ft();return Zr.resolve(s,"testim-bin")}function Uw(){let s=Xc();return Zr.resolve(s,"sessionPlayer.zip")}async function Nm(s,e,t=!1){try{return await wi(s,e),await nt(e,Xc())}catch(r){if(t)throw r;return await Nm(s,e,!0)}}async function br(s,e){Bi.info("prepare player",{location:s,canary:e});let t=Uw();return ht(async()=>{let r=await Nw(s,e);return await Nm(r,t),{}},"preparePlayer",Mm,[s,e,t])()}var Om,Lm,Zr,Dm,Bi,Mm,Kc,_m,tn=w(()=>{"use strict";Om=S(require("ms")),Lm=S(require("fs")),Zr=S(require("path"));pe();Bt();Dm=require("serialize-error");$();$c();J();F();Bi=A("prepare runner and testim start"),Mm=(0,Om.default)("0.5 day"),Kc=16,_m=`The size of the custom extension is more than ${Kc}MB`});function Fw(){let s=rn.type().toLowerCase();return s==="darwin"?rn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?rn.arch()==="x64"?"win64":"win32":"linux"}async function $i(){let s=Fw(),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 x(`Unsupported platform: ${s}`);let r=parseInt(sn,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]}/${sn}/${n[s]}.zip`,a=ji.join(Qc,n[s]),l=`${a}.zip`,c=ji.join(a,i[s]);if(await he(c))return c;if(!await he(l)){let m=(0,Zc.default)("Downloading Chromium").start();try{await Um.promises.mkdir(Qc),await Ye(o,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Zc.default)("Extracting Chromium").start();try{await nt(l,Qc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Um,rn,ji,Zc,sn,Qc,el=w(()=>{"use strict";Um=S(require("fs")),rn=S(require("os")),ji=S(require("path")),Zc=S(require("ora"));J();F();sn="1000968",Qc=ji.join(Ft,`chrome-${sn}`)});async function jm(s,e){return Tr=s,nl=e,await tl()}function $m(s,e){Tr=e.projectId,nl=e.token,nn=e.userAccessKey,it=s.token,an=il(it),cn=s.refreshToken,rl=s.ngrokToken,sl=s.isNgrokWhitelisted,Fm=e.publicIp,Bm=e.initializedFromCache}function jw(s=Tr,e=nl){return ht(()=>(on.info("request to get cli token from server"),Ve({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Bw*10,{projectId:s,token:e})()}async function $w(){on.info("request to refresh JWT cli token from server");let s=await Ve({url:`${fe}/auth/refreshToken`,body:{token:it,refreshToken:cn}});return it=s.token,an=il(it),s.refreshToken&&(cn=s.refreshToken),it}async function tl(){try{let s=await jw();return on.info("successfully get cli token from server"),it=s.token,an=il(it),cn=s.refreshToken,rl=s.ngrokToken,sl=s.isNgrokWhitelisted,it}catch(s){throw s.message.includes("Unauthorized")?new x("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."):(on.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Tr}),new x(`While trying to retrieve CLI token, caught error: ${s}`))}}function il(s){return require("jsonwebtoken").decode(s).exp*1e3}async function xt(){if(!an)return tl();let s=L.flags.accessTokenExpiryMargin.getValue();if(an<Date.now()+4*s)try{return await $w()}catch(e){return on.error("failed to refresh token, executing fallback",e),tl()}return it}function Wi(){return cn}function wr(){return it?{uid:require("jsonwebtoken").decode(it).id,ngrokToken:rl,isNgrokWhitelisted:sl}:{}}async function Vi(){if(!nn||!Tr)return;if(await ol({userAccessKey:nn,projectId:Tr}))return nn;let e=`user access key "${nn}" is invalid for project "${Tr}"`;throw new x(e)}function Gi(){return Fm}function Hi(){return Bm}var on,it,an,cn,rl,sl,Tr,nl,nn,Fm,Bm,Bw,ot=w(()=>{"use strict";pe();Ge();Bt();J();$();ge();le();on=A("testim-custom-token"),Tr=null,nl=null,Bw=5*60*1e3});var Wm={};H(Wm,{isCi:()=>es});var es,qi=w(()=>{"use strict";es=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Ae={};H(Ae,{addTestRetry:()=>Pl,clearTestResult:()=>Al,deleteCloudflareTunnel:()=>Ll,fetchLambdatestConfig:()=>El,fixGridAppIDStructure:()=>Ul,forceUpdateCloudflareTunnelRoutes:()=>Ol,getAllGrids:()=>Sl,getAppDetails:()=>dn,getApplitoolsIntegrationData:()=>kl,getBrowserStackSessionMetaData:()=>Xw,getCloudflareTunnel:()=>_l,getEditorUrl:()=>Kw,getGridById:()=>Ki,getGridByName:()=>wl,getHybridGridProvider:()=>Tl,getLabFeaturesByProjectId:()=>Il,getMobileDevicesFromGrid:()=>Ml,getRealData:()=>Rl,getS3Artifact:()=>un,getS3ArtifactText:()=>cl,getSuiteTestList:()=>fl,getTestPlan:()=>zw,getTestPlanTestList:()=>ml,getTestResults:()=>Sr,getUsageForCurrentBillingPeriod:()=>gl,initializeUserWithAuth:()=>vl,isTestResultCompleted:()=>hl,keepAliveCompanySlots:()=>$l,keepAliveGrid:()=>yl,loadSfdcCredential:()=>ll,loadTest:()=>pn,releaseCompanySlot:()=>Bl,releaseGridSlot:()=>bl,reportExecutionFinished:()=>zi,reportExecutionStarted:()=>dl,requestCompanySlot:()=>Fl,saveRemoteStep:()=>xl,saveTestPlanResult:()=>ul,updateCompanySlot:()=>jl,updateExecutionTests:()=>pl,updateRemoteRunFailure:()=>Dl,updateTestDataArtifact:()=>Yi,updateTestResult:()=>Ji,updateTestStatus:()=>vr,uploadAppToGrid:()=>Nl,uploadRunDataArtifact:()=>Cl,validateUserAccessKey:()=>ol});async function ts(){let s=await xt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await ts(),o={...t,...i};return Ve({url:`${fe}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function Gw(s,e,t,r={},n=void 0){let i=await ts(),o={...r,...i};return await $s(`${fe}${s||""}`,e,t,o,n)}async function ln(s,e){let t=await ts();return await Sc(`${fe}${s||""}`,e,t)}async function Hw(s,e){let t=await ts();return await js(`${fe}${s||""}`,e,t)}async function qw(s,e){let t=await ts();return await Ws(`${fe}${s||""}`,e||void 0,t)}async function Se(s,e,t,r){let n=await ts();return await be(`${fe}${s||""}`,e||void 0,n,r,t)}function un(s,e){return(0,X.default)(()=>Se(`/storage${s}`,null,{isBinary:!0},e),{retries:ee,factor:1})}function cl(s){return(0,X.default)(()=>qw(`/storage${s}`))}async function zw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,X.default)(()=>Se("/testPlan",{projectId:s,name:e.join(",")}),{retries:ee,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function ll({branch:s,projectId:e}){let t=await(0,X.default)(()=>Se(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:ee,factor:1});return t==null?void 0:t.sfdcCredential}function pn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,X.default)(()=>Se(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:ee,factor:1})}function ul(s,e,t){return(0,X.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:ee,factor:1})}function vr(s,e,t,r,n,i,o=ee){return(0,X.default)(()=>ln("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:Ww,...i}),{retries:o,factor:1})}function pl(s,e,t,r,n,i,o,a){return(0,X.default)(()=>ln("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:ee,factor:1})}async function dl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(qi(),Wm));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function zi(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,X.default)(()=>ln("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:ee,factor:1})}async function ml(s,e,t,r,n){return(0,X.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:ee,factor:1})}function fl({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,X.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:ee,factor:1})}async function dn({appId:s,projectId:e}){try{return await(0,X.default)(()=>Se(`/mobile-app/app/${s}?projectId=${e}`),{retries:ee,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function gl(s){try{return await(0,X.default)(()=>Se(`/plan/project/${s}/usage-current-billing-period`),{retries:ee,factor:1})}catch(e){jt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function hl(s,e,t){return(0,X.default)(()=>Se(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ee,factor:1})}function Sr(s,e,t,r){return(0,X.default)(()=>Se(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:ee,factor:1})}function yl(s,e){return Re({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function bl(s,e,t,r,n){return Re({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Tl(s){return Re({url:"/grid/hybrid/provider",body:s})}function wl(s,e,t,r,n){return(0,X.default)(()=>Se("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}function Ki(s,e,t,r,n){return(0,X.default)(()=>Se(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}async function vl({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a}){var l,c;try{return await(0,X.default)(()=>Ve({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a}}),{retries:ee,factor:1})}catch(d){throw jt.error("error initializing info from server",d),(l=d==null?void 0:d.message)!=null&&l.includes("Bad Request")?new x("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."):(c=d==null?void 0:d.code)!=null&&c.includes("ENOTFOUND")?new x("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):d}}async function Kw(){if(Ls)return{editorUrl:Ls};try{return await(0,X.default)(()=>Se("/system-info/editor-url"),{retries:ee,onFailedAttempt:s=>{if(s.attemptNumber>=ee)throw s},factor:1})}catch(s){return jt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Sl(s){return(0,X.default)(()=>Se("/grid",{companyId:s}),{retries:ee,factor:1})}function Rl(s,e,t){return(0,X.default)(()=>Se(`/real-data/${e}?${t}&projectId=${s}`),{retries:ee,factor:1})}function Ji(s,e,t,r,n){return(0,X.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:ee,factor:1})}function Al(s,e,t,r){return(0,X.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:ee,factor:1})}function xl(s,e,t,r){return(0,X.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:ee,factor:1})}function Jw(s){return s.startsWith("/")?s:`/${s}`}function Yw(s,e,t){let r=Jw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Gm(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${se()}${o||""}`,l=`${e}/${t}/${a}`,c=Yw(l,"test-result-artifacts",s),d=Buffer.from(Vm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,X.default)(()=>Gw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ee,factor:1}),c}function Pl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,X.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:ee,factor:1})}async function kl(s){try{return await Se(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return jt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function _l(s,e){try{return await ln("/tunnel",{companyId:s,routes:e})}catch(t){return jt.warn("could'nt get tunnel.",{err:t}),{}}}async function Ol(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}async function Ll(s,e){try{return await Hw(`/tunnel/${e}`,{companyId:s})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}function Dl(s){return Ve({url:`${fe}/result/remoteRunFailure`,body:s})}async function Ml({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${Vw}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,X.default)(()=>Se(i,{projectId:s}),{retries:ee,factor:1})}catch(o){return jt.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Nl({projectId:s,gridId:e,app:t,timeout:r}){return(0,X.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:ee,factor:1})}async function Ul(s){return(0,X.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:ee,factor:1})}async function Fl(s,e){return(0,X.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:ee,factor:1})}async function Bl(s,e,t){return(0,X.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:ee,factor:1})}async function jl(s,e,t){return(0,X.default)(()=>ln("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:ee,factor:1})}function $l(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function Xw(s,e){return await be(`${Ms}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function ol(s){try{return await Se("/v2/project/validateUserAccessKey",s),!0}catch(e){return jt.error("error validating user access key",{error:e}),!1}}var Zt,Vm,X,al,Ww,jt,ee,Vw,El,Il,Cl,Yi,ge=w(()=>{"use strict";Zt=S(require("lodash")),Vm=S(require("pako"));F();pe();ne();Ge();ot();X=S(require("p-retry")),al=S(require("object-hash"));J();$();Ww=ze(),jt=A("testim service api"),ee=3,Vw="/grid";El=async()=>(0,X.default)(()=>Se("/grid/lt/config"),{retries:ee,factor:1}),Il=async s=>(0,X.default)(()=>Se(`/labFeature/v2/project/${s}`),{retries:ee,factor:1});Cl=Zt.memoize(async(s,e,t,r)=>{if(!Zt.isEmpty(r))return await Gm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,al.default)(r)}:${e}:${t}`),Yi=Zt.memoize(async(s,e,t,r,n)=>!r||Zt.isEmpty(r)?void 0:await Gm(s,e,t,JSON.stringify((()=>{let o=Zt.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{o[l]&&Object.assign(o,{[l]:kc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,al.default)(r)}:${e}:${t}`)});async function Hm(){let s=await Promise.any(Qw.map(async e=>{try{return await be(e)}catch{return null}}));return s==null?void 0:s.ip}var Qw,qm=w(()=>{"use strict";Ge();Qw=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});var er={};H(er,{getSessionPlayer:()=>Q,options:()=>Vl});var Xi,Vl,Wl,Q,Te=w(()=>{"use strict";Xi=require("path");$();Vl={playerPath:void 0},Q=()=>{if(Wl)return Wl;let s=(We(),Ue($e));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(tn(),Ue(en)),t=e(),r=Vl.playerPath?(0,Xi.resolve)(Vl.playerPath,"src/background/sessionPlayerInit.ts"):(0,Xi.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Wl=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(pc),n}});function tv(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(Te(),Ue(er)).getSessionPlayer()}catch{}})}async function mn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?ev:Zw,f=null;if(L.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{f=await Hm()}catch(y){zm.error("failed to get public ip",y)}let h=!0;U("before initializeUserWithAuth");let g=await ht(async()=>(tv(a),h=!1,await vl({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:f,gridId:l,grid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:f})();return s.publicIps=[g.clientPublicIp],U("after initializeUserWithAuth"),f&&g.clientPublicIp&&g.clientPublicIp!==f&&(zm.error("public ip mismatch",{publicIpFromExternalService:f,publicIpFromServices:g.clientPublicIp}),s.publicIps.push(f)),$m(g.authData,{projectId:e,token:t,userAccessKey:r,publicIp:g.clientPublicIp,initializedFromCache:h}),g}var zm,Zw,ev,Km=w(()=>{"use strict";We();ge();Bt();ot();qm();ne();$();le();zm=A("initializeUserWithAuth"),Zw=1e3*60*5,ev=1e3*60*60*10});async function Xm(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await $i():s.chromeBinaryLocation,e=Zs({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await Yc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Jc(s.installCustomExtension,n)}return await e,t}async function Qm(s){var o;rv.info("prepare MockNetwork",{location:s});let e=await Ac(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Jm*1e6)throw new Error(`${Gl} exceeded ${Jm}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Gl} cannot be parsed.${Qi.EOL}${a}`)}let n=new Ym.default;if(!n.validate(Bc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Qi.EOL);throw new Error(`${Gl} is malformed.${Qi.EOL}${a}`)}return r.entries}var Qi,Ym,Jm,Gl,rv,Hl=w(()=>{"use strict";Qi=S(require("os"));F();tm();tn();Ym=S(require("ajv"));ne();el();Km();Jm=1,Gl="JSON file supplied to --mock-network-pattern",rv=($(),Ue(gc)).getLogger("prepare runner")});function ef(s,e=process){async function t(r){await oe(ae(Zm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{fn.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(fn.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",()=>{fn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw fn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw fn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function rs(s){Zm.push(s)}var fn,Zm,gn=w(()=>{"use strict";$();F();fn=A("process-handler"),Zm=[]});function Jl(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?Td:Ds}/extension/testim-headless${t}`,n=L.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project});return n||(cv.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),n="https://testimstatic.blob.core.windows.net/extension/testim-headless.zip"),!(s.ext||s.extensionPath)&&n&&(r=n,s.testimHeadlessExtensionDownloadUrl=n),{chrome:r,"edge-chromium":r}}function of(s){let{chrome:e}=Jl(s,!1);return e}function eo(s){let e=`${Ds}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var cv,hn=w(()=>{"use strict";pe();le();$();cv=A("runOptionsUtils")});function pf(s){Oe||(s!=null&&s.userId||(s={anonymousId:uf}),lf.identify(s))}function yt(s,e){return yn("ci",s,e)}function yn(s,e,t){if(Oe)return;let r=s?{userId:s}:{anonymousId:uf};lf.track(Object.assign(r,{event:e,properties:t}))}var cf,lf,uf,ss=w(()=>{"use strict";pe();cf=require("@segment/analytics-node"),lf=new cf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),uf=require("crypto").randomBytes(20).toString("hex")});function df(s){return s.start&&yn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function mf(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new x("Agent port is not number");let t=eo(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 ff=w(()=>{"use strict";hn();ss();J()});var gf,uv,pv,Yl,hf=w(()=>{"use strict";gf="TST_CREDS",uv=["username","password"],pv="$encrypted",Yl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of uv)t[r]={[pv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(gf)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[gf]:this.proxyPlaceholder})}}});async function bf(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await fl({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 Xl(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 Ql(s,e){let t=s.mode===q.EXTENSION?Er:Tn,r=yf.difference(Hs(s,e),t);if(r.length>0)throw yt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new x(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var yf,Er,Tn,to=w(()=>{"use strict";yf=S(require("lodash"));F();ss();ge();J();ne();Er=["edge-chromium","chrome"],Tn=[...Er,"firefox","safari","safari technology preview"]});function so(s){let{platform:e}=process;e==="win32"?(0,ro.exec)(`start chrome ${s}`):e==="darwin"?(0,ro.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,ro.exec)(`google-chrome ${s}`)}var ro,Zl=w(()=>{"use strict";ro=require("child_process")});var nu={};H(nu,{doLogin:()=>su,getProjectId:()=>dv,getToken:()=>mv});async function dv(){return vf("projectId")}async function mv(){return vf("token")}function wf(s,e){return Promise.race([s,ce(e).then(()=>{throw new ie("timeout")})])}async function fv(){let s=(await import("express")).default(),e=async function(){return wf(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Ae)),{editorUrl:n}=await r();so(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function su({overwriteExisting:s=!0,projects:e=null}={}){let t=eu.homedir(),r=tu.join(t,".testim");if(await he(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await wf(fv(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Tf(r,i);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=c.project.ci.token,i.projectId=c.project.id,await Tf(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Tf(s,e){await ru.promises.writeFile(s,no.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function vf(s){let e=eu.homedir(),t=tu.join(e,".testim"),r=await he(t),n={};if(r)try{n=no.parse((await ru.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var eu,tu,no,ru,io=w(()=>{"use strict";eu=S(require("os")),tu=S(require("path")),no=S(require("yaml"));F();ru=require("fs");J();Zl()});var Pf={};H(Pf,{process:()=>Sv});var ou,Rf,oo,Af,$t,Ne,xf,gv,Me,lu,hv,yv,Ef,Cf,bv,au,cu,uu,iu,Ct,Tv,p,wv,vv,If,Sv,kf=w(()=>{"use strict";ou=S(require("ms")),Rf=S(require("chalk")),oo=S(require("fs")),Af=S(require("url")),$t=S(require("lodash")),Ne=S(require("path"));F();hn();ff();Bt();xf=require("commander");ne();J();Fr();F();le();hf();to();gv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(s,e)=>(e.push(s),e),lu=new xf.Command,hv=s=>s.split(","),yv=(s,e)=>!s||s.length===0?e:s,Ef=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Cf=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}lu.help(g=>g.split(`
17
17
  `).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!o(T)&&!i(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
18
18
  `))},bv=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Rf.default.yellow(`
19
19
  WARNING: ${s} is deprecated. ${t}
20
- `))},au=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:cu,argv:uu,exit:iu,cwd:Ct}=global.process,Tv=["trace","debug","info","warn","error","silent"];Lc(uu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));lu.description("Testim.io CLI").option("-h --help","output usage information",Cf).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]","").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",hv).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(cu.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,ou.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,ou.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: ${au.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("--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(uu);p=lu.opts(),wv=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},vv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},If=s=>{var r;if(!L.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=oo.readFileSync(s);(r=Yl)!=null&&r.containsEncryptedCredentials(t.toString())&&Yl.injectProxyCredentialsStoreToGlobal()},Sv=async()=>{var y,T,I,b,v,E,C,D;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!uu.slice(2).length)throw Cf(),new jr;if(p.version){let R="Testim CLI Version: ";cu.npm_package_version&&(console.log(R,cu.npm_package_version),iu(0));let N=ze();N&&(console.log(R,N),iu(0)),console.log("Could not find version, please check the package.json manually"),iu(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&mm(),p.clearFileCache&&Yr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=Ne.resolve(n);pm(R)}if(p.usePrefechedData&&fm(),p.playerRequirePath){let R=Ne.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let N=Ne.join(R,"tsconfig.node.json"),_=require("ts-node").register({project:N,ignore:[/node_modules/,new RegExp(`^${$t.escapeRegExp(Ne.relative(Ct(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:_.config.options.paths,baseUrl:_.config.options.baseUrl}),(Te(),Ue(er)).options.playerPath=R;let V=require("module"),Y=V.prototype.require;V.prototype.require=function(de){return de==="rox-alias"?Y.call(this,"rox-node"):de==="canvas"?{}:Y.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=oo.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 x("missing --proxy option");if(df(p))return mf(p);try{let R={};p.configFile?(If(p.configFile),R=require(Ne.join(Ct(),p.configFile)).config):p.optionsFile&&(R=require(Ne.join(Ct(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(N=>{let k=gv(N);p[k]=yv(p[k],R[N])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let i=((y=p.testConfig)==null?void 0:y.length)||((T=p.testConfigId)==null?void 0:T.length),o=((I=p.testPlan)==null?void 0:I.length)||((b=p.testPlanId)==null?void 0:b.length),a=((v=p.suite)==null?void 0:v.length)||((E=p.suiteId)==null?void 0:E.length);if(p.seleniumCapsFile)try{r=require(Ne.join(Ct(),p.seleniumCapsFile))}catch(R){throw new x(`Failed to parse selenium caps file file error: ${R.message}`)}if((C=p.reporters)!=null&&C.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new x("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new x("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new x("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Ne.join(Ct(),p.chromeExtraPrefs))}catch(R){throw new x(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let N of R){let[k]=N.split("=");Ef.includes(k)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(N),k==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${k}), allowed values: ${JSON.stringify(Ef)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&If(p.paramsFile),s={...s,...require(Ne.join(Ct(),p.paramsFile))}}catch(R){throw new x(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new x(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new x("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(wv(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(Ne.join(Ct(),p.sauceOptions)),N=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let _=R.browserName.toLowerCase();switch(_){case"microsoftedge":p.browser="edge";break;default:p.browser=_}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let k=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!N&&p.browser==="chrome"&&k)throw new x("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new x(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new x("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(vv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(Ne.join(Ct(),p.browserstackOptions)),N=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!N&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new x("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new x(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(Ne.join(Ct(),p.perfectoOptions)),N={location:"US East",securityToken:p.perfectoToken};p.perfecto={...N,...R}}catch(R){throw new x(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(Ne.join(Ct(),p.testobjectOptions)),N={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...N,...R}}catch(R){throw new x(`Failed to parse test object options file error: ${R.message}`)}if(!p.project){let N=await(await Promise.resolve().then(()=>(io(),nu))).getProjectId();if(N)p.project=N;else throw new x("missing project-id info, either --login to provide new credentials or use --project <project-id>")}L.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=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let N=await(await Promise.resolve().then(()=>(io(),nu))).getToken();if(N)p.token=N;else throw new x("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=R=>R<=0||!Number.isInteger(R);if(d(p.retries))throw new x("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new x("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new x("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new x("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 x("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new x("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new x("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new x("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new x(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Er,...wn].includes(p.browser))throw new x(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new x("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!Tv.includes(p.appiumLogLevel))throw new x(`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 x("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 x("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 x("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new x("please define exactly one of --grid or --grid-id or --host");if((D=p.host)!=null&&D.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Af.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(N=>N.trim()).filter(Boolean);let R=p.resultLabel.filter(N=>N.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&gr()&&p.resultLabel.unshift(gr()),R.length)throw new x("A result label cannot exceed 250 characters")}let u=eo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new x("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 x("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new x("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 x("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&&!$t.inRange($t.parseInt(p.setRetention),1,11))throw new x("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 f="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new x(`--mock-network-har ${f}`);if(p.mockNetworkPattern)throw new x(`--mock-network-pattern ${f}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new x("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new x("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new x("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new x("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&$t.difference(p.codeCoverageReporter,au).length){let R=$t.difference(p.codeCoverageReporter,au);throw new x(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let h={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"},g=Object.keys(h).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&g.length){let R=g.length>1?"are":"is";throw new x(`${g.map(N=>h[N]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=oo.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new x(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new x("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(bv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new x("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new x("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 x("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},N=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...N}}catch(R){throw new x(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
21
- 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 x("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"?gr():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,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||u,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Df={};H(Df,{installAllLazyDependencies:()=>Rv,lazyRequire:()=>at});async function at(s,e={}){let t=Gc(s);if(t)return t;let r;e.silent||(r=(0,_f.default)(`Installing ${s} before first usage...`).start());try{let n=await Iv(s);return r&&r.succeed(),n}catch(n){Ev.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Lf(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${o}`;throw r&&r.fail(c),n}}async function Iv(s){return ns.has(s)||(ns.set(s,Of(s)),ns.get(s).catch(()=>{ns.delete(s)})),ns.get(s)}async function Of(s){let e=Gc(s);if(e)return e;let t=Lf(s),r=`${s}@${t}`;return await Ni(ft(),r),Xt(s)}async function Rv(){let s=Object.keys(ec);for(let e of s)await Of(e)}function Lf(s){let e=Object.entries(ec).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var _f,Ev,ns,vn=w(()=>{"use strict";_f=S(require("ora"));Qr();$();F();li();Zs();Ev=A("lazy-require"),ns=new Map});var Nf={};H(Nf,{preloadTests:()=>Sn});async function Sn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ht(async()=>{let t=await ae(s.testId,r=>dn({...e,testId:r}),{concurrency:2});return Mf.keyBy(t,"testData.id")},"loadTests",Av,[e,s.testId])()}var Mf,Av,ao=w(()=>{"use strict";Mf=S(require("lodash"));Bt();ge();F();Av=1e3*60*60*10});function pu(){return ze()}async function Bf(){if(!Oe)try{let s=await oe(Cv(),5e3,"The API call to NPM timed out"),e=pu();e&&Ff.lt(e,s)&&console.log(Uf.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){xv.warn("Failed to get NPM version",{err:s})}}var Uf,Ff,xv,Cv,du=w(()=>{"use strict";Uf=S(require("chalk")),Ff=S(require("semver"));F();pe();Qr();Bt();$();xv=A("npm-driver"),Cv=ht(()=>Tm("@testim/testim-cli"),"getNpmVersion")});var mu,kv,is,jf,$f,fu,Wf,Vf=w(()=>{"use strict";F();J();$();vn();mu=A("testimNgrok"),kv=".whitelisted-ngrok.testim.io",is="",$f=async(s,e={})=>{if(!e.ngrokToken)throw new x("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${se()}-${s.projectData.projectId}${kv}`);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 at("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(mu.info("replace https to http"),is=i.replace("https://","http://")):is=i,s.tunnelDiagnostics&&fu(),s.baseUrl=is},fu=async(s=!0)=>{try{let t=(await at("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===is);console.log("ngrok stats",n),mu.info("ngrok stats",{tunnel:n})}catch(e){mu.error("error collecting ngrok stats",{err:e})}s&&(jf=setTimeout(()=>fu(),1e4))},Wf=async s=>{if(!is)return;clearTimeout(jf),s.tunnelDiagnostics&&await fu(!1),await(await at("ngrok")).disconnect(is)}});var tr,hu,Gf,Ov,Lv,gu,co,uo,lo,Dv,Hf,qf,zf=w(()=>{"use strict";tr=S(require("os")),hu=S(require("fs")),Gf=S(require("child_process"));F();ge();Ov="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Lv={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"}},gu=tr.tmpdir(),co=`${gu}/cloudflared`,uo=null,lo=null,Dv=async()=>{if(await he(co))return;let e=Lv[tr.platform()+tr.arch()];if(!e)throw new Error(`tunnel on ${tr.platform()+tr.arch()} platform is not supported.`);let t=e.extract?gu+e.path:co;await Ye(`${Ov}/${e.path}`,t),e.extract&&await nt(t,gu),await hu.promises.chmod(co,"755")},Hf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([_l(s.company.companyId,t),Dv()]);uo=r._id,lo=Gf.spawn(co,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Ol(s.company.companyId,uo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await hu.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},qf=async s=>{let e=[];return uo&&e.push(Ll(s.company.companyId,uo)),lo&&e.push(new Promise((t,r)=>{lo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),lo.kill()})),await Promise.all(e)}});function Wv(s,e){if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=`${e.width}x${e.height}`;return Vv(s,t)}function Vv(s,e){if(e){if(!jv.includes(e)){os.warn("Default resolution is used because the resolution is not supported by LT",{resolutionString:e,testResultId:s});return}return e}}function Kf(s,e){if(e){if(!$v.includes(e)){os.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Jf,Yf,Wt,Xf,Qf,Zf,po,eg,os,Nv,Uv,En,Fv,Bv,re,jv,$v,mo=w(()=>{"use strict";Jf=S(require("ms")),Yf=S(require("p-retry")),Wt=S(require("os")),Xf=S(require("portfinder")),Qf=S(require("child_process"));F();Ge();ge();Zf=S(require("fs")),po=S(require("fs/promises")),eg=require("path");J();$();yn();ne();le();F();os=A("lambdatestService"),Nv="https://downloads.lambdatest.com/tunnel/v3",Uv={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"},En=`${Wt.tmpdir()}/LT`,Fv=`${En}/LT`,Bv=(0,Jf.default)("15m"),re=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.TESTIM_LAMBDATEST||e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){re.isLambdatestGrid(e)&&(re.lambdatestConfigPromise||=El(),re.lambdatestConfig=await re.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Bv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await he(Fv))return;let t=Uv[Wt.platform()+Wt.arch()];if(!t)throw new Error(`tunnel on ${Wt.platform()+Wt.arch()} platform is not supported.`);let r=`${En}.zip`;await Ye(`${Nv}/${t}`,r),await nt(r,En)}static async chmodLtTunnel(e){if(!(Wt.platform()==="win32"||!await he(e))){try{await po.access(e,Zf.constants.X_OK);return}catch{}try{await po.chmod(e,"777")}catch(r){throw os.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){re.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Xf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;re.tunnelName=se();let c=["--tunnelName",re.tunnelName,"--infoAPIPort",String(t)];if(L.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(L.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Dc(u)])}if(L.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new x("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new x("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await re.delay(3e3),await re.chmodLtTunnel((0,eg.join)(En,"LT")),re.tunnel=Qf.spawn("./LT",c,{cwd:En});let d="",m="";re.tunnel.stdout.on("data",u=>{d+=u.toString()}),re.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Yf.default)(()=>be(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});os.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),os.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!re.tunnel))return new Promise((t,r)=>{re.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),re.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,l){var T,I;if(!this.isActive)return{};let c=re.lambdatestConfig.CAPABILITIES[t]||{},d={...re.tunnelName&&{tunnel:!0,tunnelName:re.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Kf(n,a==null?void 0:a.os)||Kf(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||re.lambdatestConfig.PLATFORM,resolution:Wv(n,a==null?void 0:a.resolution)||re.lambdatestConfig.RESOLUTION,version:t==="safari"&&((I=o==null?void 0:o.lt)==null?void 0:I.safari_version)||c.version};if(l!==q.APPIUM&&l!==q.SELENIUM&&!f){let b=Jl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&_e(h)&&(m=[...m,h]),m.length||os.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return g&&_e(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:re.lambdatestConfig.SELENIUM_VERSION,timezone:re.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:L.flags.LTNetworkCapabilities.isEnabled(),ntlm:L.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:L.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},jv=["1024x768","1280x800","1280x1024","1366x768","1440x900","1680x1050","1600x1200","1920x1200","1920x1080","2048x1536","2560x1440"],$v=["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"]});var yu={};H(yu,{connect:()=>go,disconnect:()=>ho,serveTunneling:()=>Hv});var fo,tg,rg,Gv,go,ho,Hv,bu=w(()=>{"use strict";Vf();hn();zf();ot();fo=S(require("ora"));$();ne();mo();tg=A("tunnel"),rg=s=>{var e;return[O.TESTIM_LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Gv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},go=async s=>{if(!s.tunnel)return;let e=wr(),t;try{rg(s)?(t=(0,fo.default)("Starting testim lambdatest tunnel...").start(),await re.connectTunnel(s)):Gv(s)?(t=(0,fo.default)("Starting testim cloudflare tunnel...").start(),await Hf(s)):(t=(0,fo.default)("Starting testim ngrok tunnel...").start(),await $f(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."),tg.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
22
- ${r.stdoutResult}`:n)}},ho=async s=>{if(s.tunnel)try{rg(s)?await re.disconnectTunnel(s):"tunnelRoutes"in s?await qf(s):await Wf(s)}catch(e){let t="catch error - failed to close tunnel";throw tg.error(t,{err:e}),new Error(t)}},Hv=async(s,e=new Promise(()=>{}))=>(await go(s),rs(()=>ho(s)),await e)});function qv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.TESTIM_LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=sg.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function zv(s){let e=sg.exec(s);return e==null?void 0:e[3]}function bo(s){var b,v,E,C,D,R,N,k,_,W,V;let e=s&&zv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&qv(s),i=s==null?void 0:s.token,o=s==null?void 0:s.slotId,a=(b=s==null?void 0:s.hybrid)==null?void 0:b.tunnel,l=(v=s==null?void 0:s.external)==null?void 0:v.user,c=(E=s==null?void 0:s.external)==null?void 0:E.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((R=(D=(C=s.hybrid)==null?void 0:C.external)==null?void 0:D[s.hybrid.tunnel])==null?void 0:R.user):l,u=d===O.HYBRID?a&&((_=(k=(N=s.hybrid)==null?void 0:N.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:_.key):c,f=s==null?void 0:s.name,h=s&&(s._id||s.gridId),g=s==null?void 0:s.provider,y=(W=s==null?void 0:s.mobileTokens)==null?void 0:W.androidToken,T=(V=s==null?void 0:s.mobileTokens)==null?void 0:V.iosToken,I=s==null?void 0:s.apiUrl;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:I}}async function ig(s,e,t,r,n){let i;try{i=await n()}catch(o){throw Ze.error("failed to get grid",{projectId:s,companyId:e,err:o}),new Error(gt.UNKNOWN)}if(Ze.info("get grid info",{...i,projectId:s,companyId:e}),!i||!["success","error"].includes(i.status))throw Ze.error("invalid response - get grid",{res:i}),new Error(gt.UNKNOWN);if(i.status==="success"){let o=bo(i.grid);return Kv(t,e,o.gridId,o.slotId,r),o}throw i.code==="not-found"?new Ke(gt.NOT_FOUND):i.code==="no-available-slot"?new zt(`Failed to run test on ${r} - concurrency limit reached`):(Ze.error("invalid code error response - get grid",{res:i}),new Ke(gt.UNKNOWN))}function Jv(s,e,t,r,n,i){return ig(t,e,s,n,()=>Ki(e,t,r,n,i))}function Yv(s,e,t,r,n,i,o){return ig(t,e,s,n,()=>{var c;let l=(c=o.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?Ki(e,t,l._id,n,i):wl(e,t,r,n,i)})}function og(s){return Sl(s)}async function ag(s,e,t){let n=(t||await og(s)).find(i=>i._id===e);if(!n)throw new x(`Failed to find grid id: ${e}`);return bo(n)}async function Xv(s,e,t){let n=(t||await og(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new x(`Failed to find grid name: ${e}`);return bo(n)}async function Tu(s,e){let t=In[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o}=t;if(delete In[s],!r){Ze.warn("failed to find grid slot id",{projectId:e});return}Ze.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await bl(o,e,r,n,i)}catch(a){Ze.error("failed to release slot",{projectId:e,err:a})}}async function Qv(s){let e=Object.values(In).filter(Boolean);if(e.length!==0){Ze.info("keep alive worker slots",{projectId:s,slots:e});try{await yl(s,e)}catch(t){Ze.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Zv(s){ng=global.setInterval(Qv,1e4,s)}async function eS(s){let e=Object.keys(In);if(e.length){Ze.warn("not all slots released before end runner flow",{projectId:s});try{await ae(e,t=>Tu(Number(t),s))}catch(t){Ze.error("failed to release all slots",{err:t,projectId:s})}}}async function tS(s){await eS(s),clearInterval(ng)}function rS(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function sS(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function cg(s){let t=(()=>yo.isEmpty(s.testobjectSauce)?yo.isEmpty(s.saucelabs)?yo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=rS(t,s),l=sS(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a}}async function lg(s,e){let t=s.company.companyId;return await ag(t,e.gridId,s.allGrids)}async function ug(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:l}=s;if(n||o||i)return{mode:"local"};if(r)return cg(s);let c=t==null?void 0:t.companyId;if(a)return ag(c,a,e);if(l)return Xv(c,l,e);if(zs(s)||s.tunnelOnlyMode){Ze.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new Ke("Missing host or grid configuration")}async function pg(s,e,t,r){let{host:n,project:i,grid:o,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return cg(t);if(a)return Jv(r,u,i,a,s,e);if(o)return Yv(r,u,i,o,s,e,t);throw new Ke("Missing host or grid configuration")}var yo,Ze,In,sg,ng,Kv,Rn,dg,as=w(()=>{"use strict";yo=S(require("lodash"));ge();$();F();ne();J();Ze=A("grid-service"),In={},sg=/(^(https?):\/{2})?(.*)/,ng=null;Kv=(s,e,t,r,n)=>{In[s]={gridId:t,companyId:e,slotId:r,browser:n}};Rn={start:Zv,end:tS};dg=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!o||!a||((a===O.TESTIM_LAMBDATEST||a===O.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==O.HYBRID||!i||!l||!d||!m))return e;let u=await Tl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Ze.info("handling hybrid grid",{response:u,companyId:i});let f=bo({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});async function wu(s,e,t){let r=cs[s];if(!r)return;let{slotId:n}=r;if(delete cs[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Bl(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function nS(s,e){let t=Object.values(cs).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await $l(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function iS(s,e){mg=global.setInterval(()=>nS(s,e),1e4)}async function oS(s,e){let t=Object.keys(cs);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await ae(t,r=>wu(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function aS(s,e){await oS(s,e),clearInterval(mg)}async function gg(s,e,t){let r;try{r=await Fl(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(gt.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(gt.UNKNOWN);if(r.status==="success")return fg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new Ke(gt.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new Ke(gt.UNKNOWN))}async function hg(s,e,t,r){let n=cs[r];if(!n)throw new Error("slot not found");Object.assign(n,t),fg(r,n),await jl(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,cs,mg,fg,xn,ls=w(()=>{"use strict";ge();$();F();ne();J();ct=A("slot-service"),cs={},mg=null,fg=(s,e)=>{cs[s]=e};xn={start:iS,end:aS}});function Pn(){return To||"master"}function yg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){To="master";return}if(s!=null&&s.isArchived)throw new x(`Branch ${s.branch} is archived, run aborted.`);if(s){To=s.branch||s;return}To=e?"master":void 0}var To,vu=w(()=>{"use strict";J()});var kn,Su,cS,Eu,lS,wo,vo,So,Eo,Io,Ro=w(()=>{"use strict";F();ne();kn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},Su=s=>{let{status:e}=s;return e===me.ABORTED},cS=s=>{let{status:e}=s;return e===me.PASSED},Eu=s=>s.runnerStatus===Cc.SKIPPED,lS=s=>s.testStatus===Xe.EVALUATING,wo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Eu(t)&&(Qe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,vo=s=>Object.values(s).filter(e=>kn(e)&&lS(e)).length,So=s=>Object.values(s).filter(kn),Eo=s=>Object.values(s).filter(cS),Io=s=>Object.values(s).filter(Su)});function pS(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Iu,Ao,uS,xo,Tg=w(()=>{"use strict";Iu=S(require("lodash"));$();Ro();Ao=A("debug-reporter"),uS=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],xo=class{constructor(e){this.options=e}onTestStarted(e,t){Ao.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;Ao.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Iu.default.omit(this.options,uS),company:Iu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=pS(process.argv);Ao.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,i){let o=Eo(e).length,a=Object.keys(e).length-o;Ao.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ru,Pt,_n=w(()=>{"use strict";ne();Ru=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===O.DEVICE_FARM}},Pt=new Ru});var xu={};H(xu,{Reporter:()=>dS});var rr,On,Ir,Co,wg,Au,dS,Cu=w(()=>{"use strict";rr=S(require("chalk")),On=S(require("lodash"));F();ne();_n();Ro();Ir={success:rr.default.green,warn:rr.default.yellow,error:rr.default.red},{CLI_MODE:Co}=Ut,wg="device",Au=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: ${rr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?me.PASSED:me.FAILED,n=`(${e.testId})`,i=Ir[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Ei(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Ir.error("Failed runs are:")),console.log(Ir.error(t.join(`
23
- \r`)))}onTestPlanFinished(e,t,r,n,i){let o=So(e),a=Eo(e),l=Io(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Pt.isTestStatusEnabled){let I=vo(e);u=` FAILED-EVALUATING: ${I}`,m-=I,f=` SKIPPED: ${wo(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=Ir[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Ei(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=On.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=On.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=On.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=On.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((f,h)=>{var T;let g=(T=f.testData)!=null&&T.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",h+1,":",`${f.name}${Qe(f,this.options)?"-quarantine":""}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Co.APPIUM?wg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${rr.default.underline(n)} slot from ${rr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Co.APPIUM?wg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${rr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===Co.APPIUM?"device":"browser";if(n)console.log(Ir.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(Ir.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Co.APPIUM?"Appium":"Selenium";console.log(Ir.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},dS=Au});var _u={};H(_u,{Reporter:()=>bS});function mS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function fS(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 gS(s){return`${s.visitedUrlsJson||""}`}async function hS(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:mS(u),classname:n,time:Mc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(kn(u)||Su(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=kn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Eu(u)&&Qe(u,i)&&Pt.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=fS(u),h["visited-urls-json"]=gS(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},I={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Pt.isTestStatusEnabled){I.skipped=wo(y,i);let b=vo(y);I.failures-=b,I["failure-evaluating"]=b}return{$:I,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return So(u).length+Io(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new ku.Builder().buildObject(m)}catch(u){return yS(u)}}function yS(s){let e=new ku.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 ku,vg,Pu,bS,Ou=w(()=>{"use strict";ku=S(require("xml2js"));F();vg=require("fs");_n();Ro();Pu=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 hS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await vg.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)}};bS=Pu});var Sg={};H(Sg,{Reporter:()=>TS});function us(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 Lu,Du,TS,Eg=w(()=>{"use strict";$();Lu=A("team-city-reporter");Du=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 us(n)}onTestStarted(e,t,r,n){if(r){Lu.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){Lu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${us(t)}' details='${us(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Lu.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='${us(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${us(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${us(t)}']`)}},TS=Du});var Ig={};H(Ig,{Reporter:()=>wS});var Mu,wS,Rg=w(()=>{"use strict";Mu=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}}))}},wS=Mu});var Ag={};H(Ag,{Reporter:()=>vS});var Nu,vS,xg=w(()=>{"use strict";F();Zl();Nu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return so(t)}},vS=Nu});var Uu,Z,kt=w(()=>{"use strict";Tg();Uu=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 xo(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Cu(),xu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Ou(),_u));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Eg(),Sg)),r.includes("console")&&Promise.resolve().then(()=>(Cu(),xu)),r.includes("junit")&&Promise.resolve().then(()=>(Ou(),_u)),r.includes("json")&&Promise.resolve().then(()=>(Rg(),Ig)),r.includes("chrome")&&Promise.resolve().then(()=>(xg(),Ag))])).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))}}},Z=new Uu});function Pg(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function kg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Pg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:Cg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function _g({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let I=Pg({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Cg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",I);return}yt("test-run-ci-fail",{...I,failureReason:n.failureReason})}catch(I){f.error("failed to update test end analytics",{err:I})}}function Og(s){yt("batch-run-ci",s)}var Cg,Fu=w(()=>{"use strict";ss();qi();Cg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:es&&e?"ci-with-user":es?"ci":e?"cli-with-user":s});var Dg,Po,Mg=w(()=>{"use strict";Dg=require("istanbul-lib-report"),Po=class extends Dg.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 Ng,Ug,Fg,Ln,bt,Bg,ko,Bu,jg,SS,$g,Wg,ES,IS,Vg,RS,AS,xS,CS,PS,Gg,Hg=w(()=>{"use strict";Ng=S(require("ora")),Ug=S(require("dayjs")),Fg=S(require("test-exclude")),Ln=S(require("fs")),bt=S(require("path")),Bg=S(require("istanbul-reports")),ko=S(require("istanbul-lib-report"));ge();J();F();$();vn();Mg();Bu=A("test-run-status"),jg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},SS=s=>!!jg(s).search,$g=s=>s?jg(s).pathname.substring(1):"",Wg=(s,e)=>{let t=$g(e);return!new Fg.default({relativePath:!1,include:s}).shouldInstrument(t)},ES=s=>s.substring(0,s.indexOf("?")),IS=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await at("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Vg=(s,e)=>`${bt.resolve(s,$g(e))}.js`,RS=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await ae(i.sources,async(o,a)=>{if(Wg(r,o))return;let l=Vg(e,o);await Ln.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await Ln.promises.writeFile(l,i.sourcesContent[a])})})},AS={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(SS(e)&&(e=ES(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},xS=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=ko.createContext({dir:t,coverageMap:e,watermarks:ko.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Vg(r,a);return Ln.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new Po({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:AS}),Bg.create(a,l).execute(o)}),i},CS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await at("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Wg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},PS=async(s,e)=>{let{mergeProcessCovs:r}=await at("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await Rl(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await pn(l,9e4);await ae(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await cl(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Gg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Bu.info("start js coverage process");let n=(0,Ng.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,Ug.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([at("istanbul-lib-coverage"),PS(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Bu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ae(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),I=await IS({sourceMapType:T,source:y,sourceMapDir:a});u[h]=I;let b=await CS(s,{source:y,sourceMap:I,functions:g});m.merge(b)}),await RS(s,o,u);let f=await xS(s,m,i,o);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof x?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Bu.error(c,{err:l})}}});var qg={};H(qg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Rr});var xe,kS,Rr,ps=w(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},kS=["ALL",...Object.values(xe)],Rr=class{constructor(){this.marks=Object.fromEntries(kS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();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`,Ai(r,50)],[`${t}_P95`,Ai(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Yg={};H(Yg,{initServer:()=>LS,mapFilesToLocalDrive:()=>$u});function $u(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,_o[t.id]?{screenshot:_o[t.id]}:{})),Object.keys(Oo).forEach(t=>{s.assets||={},s.assets[Jg[t]]=Oo[t]}),s.assets||={},s.assets.screenshots=Object.values(_o)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function LS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await at("multer"),n=typeof t=="string"?t:_S;await ju.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=Dn.join(n,m.testResultId);try{await ju.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=Dn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,Kg.default)();o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(_o[d.stepId]=l.file.path),d.testResultId&&OS.includes(d.subType)&&(Oo[d.subType]||=[],Oo[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new x(`Port ${s} is already in use`));default:return c(u)}}})}var ju,zg,Dn,Kg,_S,_o,Oo,Jg,OS,Wu=w(()=>{"use strict";ju=S(require("fs")),zg=S(require("os")),Dn=S(require("path")),Kg=S(require("express"));J();vn();_S=Dn.join(zg.tmpdir(),"testim/rca/"),_o={},Oo={},Jg={"test-log":"consoleLogs","har-file":"networkLogs"},OS=Object.keys(Jg)});var sr,Vu,Lo,Xg=w(()=>{"use strict";sr=S(require("lodash"));F();$();Vu=A("override-test-data-builder"),Lo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return sr.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)&&!sr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Vu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(sr.isObject(e.overrideAllTestsData)&&!sr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Vu.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}Vu.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 sr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=se();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 Do(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var Ar,et,DS,MS,NS,US,Mo,Qg=w(()=>{"use strict";Ar=S(require("lodash"));F();ne();as();ls();ge();J();$();kt();hn();Hg();ps();Wu();pe();le();Xg();_n();et=A("test-run-status"),DS=gr(),MS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,NS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,US=ze();Mo=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 Rr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=qs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:di||t.parallel||1,browser:i,gitBranch:DS,gitCommit:MS,gitRepoUrl:NS,runnerVersion:US,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:I}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ar.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:I},Pl({projectId:n,runId:i,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Z.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Yi(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){et.error("failed to upload test data artifact (runner)",{err:d})}let l=Ar.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,vr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Qe(e,this.options))return;let n=this.exportsGlobal;try{let i=await Do(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 et.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},et.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Xe.EVALUATING&&Pt.isTestStatusEnabled){Z.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(c){Z.onTestPassed(i);return}Z.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Z.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Nc();t.isOverThreshold&&et.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&&$u(o,et),o.resultUrl=qe(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Z.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await Do(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){et.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 vr(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 et.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),Gr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let l=e.browser?Js(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Hr(L,n)&&Ks(a.nativeApp)&&!e.appId,d=Jt(e)&&(Gr(a.nativeApp,n)||c),m=Qe(a,e)||d,u={testId:a.testId,status:m?me.SKIPPED:me.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,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await xn.end(r,t),e==="mongo"&&await Rn.end(t)}async executionStart(e,t,r,n,i){et.info("execution started",{executionId:e});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;rs(()=>Promise.all([this.endKeepAlive(d,t,c),zi("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...L.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await Do(o.beforeSuite,m),f=new Lo(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 I=async()=>{let b=Ar.cloneDeep(this.testRunStatus);await ae(Object.keys(b),async C=>{var _;let D=b[C],R=(_=D.config)==null?void 0:_.testData,N=D.testId,k=await Yi(t,N,C,R,l.defaults);k&&(delete D.config.testData,D.config.testDataUrl=k)});let v=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=dl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:v,intersections:o.intersections});return this.executionStartedPromise=E,E.catch(C=>et.error(C)),E};try{await I()}catch(b){et.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 d;let t=Fc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===me.PASSED&&n++,m===me.SKIPPED&&i++,m===me.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Do(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),et.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Gg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await zi("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await pl(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 BS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function ih(s){return th.readFileSync(s,{encoding:"base64"})}function oh(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&_e(s))&&s){let r=ih(s);ds.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${qu(r)} current extension count: ${e.length}`),e.push(r)}}function ah(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ds.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=No.basename(i));let l=No.join(process.cwd(),a),c=ih(l);ds.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${qu(c)} current extension count: ${e.length}`),e.push(c)}function jS(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...nh];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Gu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Gu.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};Hu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Hu(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Gu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Pc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),oh(r,c,o),a===q.EXTENSION&&ah(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return re.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function WS(s,e,t){let r={"pdfjs.disabled":!0};return L.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":eh.join(","),"browser.helperApps.neverAsk.openFile":eh.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 VS(s){return`${s.width}x${s.height}`}function GS(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let i={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let o=(0,sh.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(i["sauce:options"].screenResolution=VS(r.resolution||t.sl.screenResolution),delete o.screenResolution),lt.merge(o,i,n)}return lt.merge(i,n)}return{}}function HS(s,e,t){return lt.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function qS(s){return s.perfecto?s.perfecto:{}}function zS(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 KS(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=Xa(i,o)),a}function Uo(s){var I,b,v,E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let C=[],D=[...nh],R={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(N=>D.push(`--${N}`)),t.chromeBinaryLocation&&(R.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&ah(t,C,D,null,c),oh(o,C,c),{logLevel:Zg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:C,...R},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=KS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:Zg,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!lt.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Hu(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);lt.merge(h.desiredCapabilities,GS(t,r,n,e),HS(t,r,n),qS(t),zS(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((I=i.host)!=null&&I.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&L.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=$S(h,t,n,o,i,T,c,d);break;case"firefox":h=WS(h,t,c);break;case"safari":case"safari technology preview":h=BS(h,y);break;default:break}lt.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let C={"hub.lambdatest.com":"lambdatest",[L.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=_=>_[i.provider]||_[h.host]||_[C[h.host]],R=_=>{var W,V;return D(_)||_[(W=h.desiredCapabilities)==null?void 0:W.browserName]||_[(V=h.desiredCapabilities)==null?void 0:V.version]||_||{}},N=JSON.parse(L.flags.addCustomCapabilities.getValue()||"{}"),k=R(R(N));Object.keys(k).length&&(ds.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(h.desiredCapabilities,k))}catch(C){ds.error("Failed to load custom capabilities",{error:C,customCapabilities:L.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(FS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let C=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),R=(v=D==null?void 0:D.capabilities)==null?void 0:v.alwaysMatch,N=_=>_.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(_=>{var W,V;R!=null&&R[_]&&(R[_].extensions=(V=(W=C==null?void 0:C[_])==null?void 0:W.extensions)==null?void 0:V.map(N))}),R!=null&&R.loadExtension&&(R.loadExtension=(E=C==null?void 0:C.loadExtension)==null?void 0:E.map(N));let k=require("util");console.log(k.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var th,No,rh,lt,sh,ds,Zg,Gu,nh,qu,Hu,FS,$S,eh,zu=w(()=>{"use strict";th=S(require("fs")),No=S(require("path")),rh=S(require("crypto")),lt=S(require("lodash"));F();pe();$();le();ne();mo();sh=require("lodash"),ds=A("testim-desired-capabilities-builder"),Zg=pi?"debug":"silent",Gu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},nh=["--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"],qu=(...s)=>rh.createHash("sha256").update(s.join("")).digest("hex"),Hu=s=>s.type===O.DEVICE_FARM||s.type===O.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=L.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ds.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};$S=lt.memoize(jS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(lt.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return qu(o,a,l,r,c,i)}),eh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Be(s){var e,t,r,n,i,o,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function lh(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 Ku=w(()=>{"use strict"});function Ju(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Ju(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var uh=w(()=>{"use strict"});var ph,dh,Vt,JS,YS,Fo,mh=w(()=>{"use strict";ph=S(require("promise-queue")),dh=S(require("webdriverio"));pe();We();F();$();Fr();uh();Ku();ps();Vt=A("WebDriverApi"),JS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},YS={implicit:0,pageLoad:1,script:2},Fo=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().substr(0,2e3):"";throw Vt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),tc!==void 0&&(e=tc);let t=1/0;this.queue=new ph.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),U("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{Vt.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),U("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await dh.remote(e),this.logGridStatus(r)}),U("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,xe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Vt.info("grid status is not supported by the grid",{testResultId:e});return}Vt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Vt.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 Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},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){Vt.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(Be(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 Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Be(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Ju,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Be(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(lh(e,this.isSafari(),Vt))})}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[YS[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(Be(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(De(e)),await this.elementIdValue(De(e),t)}async getViewportSize(e){let t=await this.execute(JS);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async 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(De(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(()=>{var i;return(i=this.client)==null?void 0:i.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let 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(Be(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Vt.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Vt.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 fh={};H(fh,{doubleClick:()=>XS});var XS,gh=w(()=>{"use strict";XS=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(I,b,v){return v>I&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Mn={};H(Mn,{dispatchFocus:()=>QS});function QS(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 Nn=w(()=>{"use strict"});var wh={};H(wh,{WebDriver:()=>Cr});async function rE(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 eE(r):void 0}catch(r){je.info("Error getting cdpAddress",r);return}}var ms,bh,Th,je,nr,ZS,hh,eE,ir,tE,yh,xr,Cr,Un=w(()=>{"use strict";ms=S(require("lodash"));F();We();zu();bh=S(require("p-retry")),Th=S(require("ua-parser-js"));Fr();$();Ku();mh();J();le();ps();je=A("webdriver"),[nr,ZS]=[0,2],{extractElementId:hh,getCdpAddressForHost:eE}=K,ir=()=>(Te(),Ue(er)).getSessionPlayer().codeSnippets,tE=()=>(Te(),Ue(er)).getSessionPlayer().locatorBuilderUtils,yh=()=>(Te(),Ue(er)).getSessionPlayer().utils,xr=()=>(Te(),Ue(er)).getSessionPlayer().positionUtils;Cr=class extends Fo{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,v,E,C,D,R,N,k;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(v=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:v.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Uo({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,I=u?()=>null:()=>this.executeJS("window.focus()");try{U("before initClient in webdriver.js init");let _=await this.initClient(y,i,d);U("after initResult before getCdpAddress in init"),this.cdpUrl=await rE(_),U("after getCdpAddress in webdriver.js init"),je.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),L.flags.dontFocusOnInit.isEnabled()||await I(),U("after focus and delay in webdriver.js init")}catch(_){let W=JSON.stringify(ms.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));je.error("failed to init webdriver",{err:_,capabilitiesAsString:W});let V=((D=(C=n==null?void 0:n.company)==null?void 0:C.activePlan)==null?void 0:D.plan)==="free";throw(R=_.stack)!=null&&R.includes("at startWebDriverSession")&&((N=_.message)!=null&&N.startsWith("Failed to create session"))&&((k=_.message)!=null&&k.includes("Timeout awaiting 'request'"))&&V?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):_.message.match(/Invalid username or password/)?new $r(_.message):_.message.match(/capabilit(y|ies)/)?new gi(_.message):_.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):_.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${_.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ms.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"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=se();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,je.warn("close unexpected alert open"),await this.alertAccept().catch(l=>je.warn("failed to click on alert",{err:l}));return}if(je.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;je.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=hh(r.value);return await this.switchToFrame({ELEMENT:n,[Ht]: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 hi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||L.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
20
+ `))},au=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:cu,argv:uu,exit:iu,cwd:Ct}=global.process,Tv=["trace","debug","info","warn","error","silent"];Lc(uu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));lu.description("Testim.io CLI").option("-h --help","output usage information",Cf).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]","").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",hv).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(cu.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,ou.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,ou.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: ${au.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("--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(uu);p=lu.opts(),wv=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},vv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},If=s=>{var r;if(!L.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=oo.readFileSync(s);(r=Yl)!=null&&r.containsEncryptedCredentials(t.toString())&&Yl.injectProxyCredentialsStoreToGlobal()},Sv=async()=>{var y,T,I,b,v,E,C,D;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!uu.slice(2).length)throw Cf(),new jr;if(p.version){let R="Testim CLI Version: ";cu.npm_package_version&&(console.log(R,cu.npm_package_version),iu(0));let N=ze();N&&(console.log(R,N),iu(0)),console.log("Could not find version, please check the package.json manually"),iu(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&mm(),p.clearFileCache&&Yr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=Ne.resolve(n);pm(R)}if(p.usePrefechedData&&fm(),p.playerRequirePath){let R=Ne.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let N=Ne.join(R,"tsconfig.node.json"),_=require("ts-node").register({project:N,ignore:[/node_modules/,new RegExp(`^${$t.escapeRegExp(Ne.relative(Ct(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:_.config.options.paths,baseUrl:_.config.options.baseUrl}),(Te(),Ue(er)).options.playerPath=R;let V=require("module"),Y=V.prototype.require;V.prototype.require=function(de){return de==="rox-alias"?Y.call(this,"rox-node"):de==="canvas"?{}:Y.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=oo.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 x("missing --proxy option");if(df(p))return mf(p);try{let R={};p.configFile?(If(p.configFile),R=require(Ne.join(Ct(),p.configFile)).config):p.optionsFile&&(R=require(Ne.join(Ct(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(N=>{let k=gv(N);p[k]=yv(p[k],R[N])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let i=((y=p.testConfig)==null?void 0:y.length)||((T=p.testConfigId)==null?void 0:T.length),o=((I=p.testPlan)==null?void 0:I.length)||((b=p.testPlanId)==null?void 0:b.length),a=((v=p.suite)==null?void 0:v.length)||((E=p.suiteId)==null?void 0:E.length);if(p.seleniumCapsFile)try{r=require(Ne.join(Ct(),p.seleniumCapsFile))}catch(R){throw new x(`Failed to parse selenium caps file file error: ${R.message}`)}if((C=p.reporters)!=null&&C.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new x("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new x("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new x("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Ne.join(Ct(),p.chromeExtraPrefs))}catch(R){throw new x(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let N of R){let[k]=N.split("=");Ef.includes(k)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(N),k==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${k}), allowed values: ${JSON.stringify(Ef)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&If(p.paramsFile),s={...s,...require(Ne.join(Ct(),p.paramsFile))}}catch(R){throw new x(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new x(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new x("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(wv(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(Ne.join(Ct(),p.sauceOptions)),N=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let _=R.browserName.toLowerCase();switch(_){case"microsoftedge":p.browser="edge";break;default:p.browser=_}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let k=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!N&&p.browser==="chrome"&&k)throw new x("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new x(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new x("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(vv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(Ne.join(Ct(),p.browserstackOptions)),N=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!N&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new x("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new x(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(Ne.join(Ct(),p.perfectoOptions)),N={location:"US East",securityToken:p.perfectoToken};p.perfecto={...N,...R}}catch(R){throw new x(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(Ne.join(Ct(),p.testobjectOptions)),N={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...N,...R}}catch(R){throw new x(`Failed to parse test object options file error: ${R.message}`)}if(!p.project){let N=await(await Promise.resolve().then(()=>(io(),nu))).getProjectId();if(N)p.project=N;else throw new x("missing project-id info, either --login to provide new credentials or use --project <project-id>")}L.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=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let N=await(await Promise.resolve().then(()=>(io(),nu))).getToken();if(N)p.token=N;else throw new x("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=R=>R<=0||!Number.isInteger(R);if(d(p.retries))throw new x("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new x("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new x("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new x("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 x("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new x("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new x("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new x("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new x(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Er,...Tn].includes(p.browser))throw new x(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new x("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!Tv.includes(p.appiumLogLevel))throw new x(`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 x("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 x("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 x("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new x("please define exactly one of --grid or --grid-id or --host");if((D=p.host)!=null&&D.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Af.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(N=>N.trim()).filter(Boolean);let R=p.resultLabel.filter(N=>N.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&gr()&&p.resultLabel.unshift(gr()),R.length)throw new x("A result label cannot exceed 250 characters")}let u=eo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new x("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 x("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new x("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 x("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&&!$t.inRange($t.parseInt(p.setRetention),1,11))throw new x("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 f="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new x(`--mock-network-har ${f}`);if(p.mockNetworkPattern)throw new x(`--mock-network-pattern ${f}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new x("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new x("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new x("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new x("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&$t.difference(p.codeCoverageReporter,au).length){let R=$t.difference(p.codeCoverageReporter,au);throw new x(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let h={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"},g=Object.keys(h).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&g.length){let R=g.length>1?"are":"is";throw new x(`${g.map(N=>h[N]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=oo.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new x(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new x("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(bv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new x("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new x("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 x("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},N=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...N}}catch(R){throw new x(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
21
+ 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 x("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"?gr():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,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||u,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Df={};H(Df,{installAllLazyDependencies:()=>Rv,lazyRequire:()=>at});async function at(s,e={}){let t=Gc(s);if(t)return t;let r;e.silent||(r=(0,_f.default)(`Installing ${s} before first usage...`).start());try{let n=await Iv(s);return r&&r.succeed(),n}catch(n){Ev.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Lf(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${o}`;throw r&&r.fail(c),n}}async function Iv(s){return ns.has(s)||(ns.set(s,Of(s)),ns.get(s).catch(()=>{ns.delete(s)})),ns.get(s)}async function Of(s){let e=Gc(s);if(e)return e;let t=Lf(s),r=`${s}@${t}`;return await Ni(ft(),r),Xt(s)}async function Rv(){let s=Object.keys(ec);for(let e of s)await Of(e)}function Lf(s){let e=Object.entries(ec).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var _f,Ev,ns,wn=w(()=>{"use strict";_f=S(require("ora"));Qr();$();F();li();Qs();Ev=A("lazy-require"),ns=new Map});var Nf={};H(Nf,{preloadTests:()=>vn});async function vn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ht(async()=>{let t=await ae(s.testId,r=>pn({...e,testId:r}),{concurrency:2});return Mf.keyBy(t,"testData.id")},"loadTests",Av,[e,s.testId])()}var Mf,Av,ao=w(()=>{"use strict";Mf=S(require("lodash"));Bt();ge();F();Av=1e3*60*60*10});function pu(){return ze()}async function Bf(){if(!Oe)try{let s=await oe(Cv(),5e3,"The API call to NPM timed out"),e=pu();e&&Ff.lt(e,s)&&console.log(Uf.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){xv.warn("Failed to get NPM version",{err:s})}}var Uf,Ff,xv,Cv,du=w(()=>{"use strict";Uf=S(require("chalk")),Ff=S(require("semver"));F();pe();Qr();Bt();$();xv=A("npm-driver"),Cv=ht(()=>Tm("@testim/testim-cli"),"getNpmVersion")});var mu,kv,is,jf,$f,fu,Wf,Vf=w(()=>{"use strict";F();J();$();wn();mu=A("testimNgrok"),kv=".whitelisted-ngrok.testim.io",is="",$f=async(s,e={})=>{if(!e.ngrokToken)throw new x("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${se()}-${s.projectData.projectId}${kv}`);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 at("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(mu.info("replace https to http"),is=i.replace("https://","http://")):is=i,s.tunnelDiagnostics&&fu(),s.baseUrl=is},fu=async(s=!0)=>{try{let t=(await at("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===is);console.log("ngrok stats",n),mu.info("ngrok stats",{tunnel:n})}catch(e){mu.error("error collecting ngrok stats",{err:e})}s&&(jf=setTimeout(()=>fu(),1e4))},Wf=async s=>{if(!is)return;clearTimeout(jf),s.tunnelDiagnostics&&await fu(!1),await(await at("ngrok")).disconnect(is)}});var tr,hu,Gf,Ov,Lv,gu,co,uo,lo,Dv,Hf,qf,zf=w(()=>{"use strict";tr=S(require("os")),hu=S(require("fs")),Gf=S(require("child_process"));F();ge();Ov="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Lv={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"}},gu=tr.tmpdir(),co=`${gu}/cloudflared`,uo=null,lo=null,Dv=async()=>{if(await he(co))return;let e=Lv[tr.platform()+tr.arch()];if(!e)throw new Error(`tunnel on ${tr.platform()+tr.arch()} platform is not supported.`);let t=e.extract?gu+e.path:co;await Ye(`${Ov}/${e.path}`,t),e.extract&&await nt(t,gu),await hu.promises.chmod(co,"755")},Hf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([_l(s.company.companyId,t),Dv()]);uo=r._id,lo=Gf.spawn(co,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Ol(s.company.companyId,uo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await hu.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},qf=async s=>{let e=[];return uo&&e.push(Ll(s.company.companyId,uo)),lo&&e.push(new Promise((t,r)=>{lo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),lo.kill()})),await Promise.all(e)}});function Kf(s,e){if(e){if(!$v.includes(e)){Sn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Jf,Yf,Wt,Xf,Qf,Zf,po,eg,Sn,Nv,Uv,En,Fv,Bv,jv,re,$v,mo=w(()=>{"use strict";Jf=S(require("ms")),Yf=S(require("p-retry")),Wt=S(require("os")),Xf=S(require("portfinder")),Qf=S(require("child_process"));F();Ge();ge();Zf=S(require("fs")),po=S(require("fs/promises")),eg=require("path");J();$();hn();ne();le();F();Sn=A("lambdatestService"),Nv="https://downloads.lambdatest.com/tunnel/v3",Uv={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"},En=`${Wt.tmpdir()}/LT`,Fv=`${En}/LT`,Bv=(0,Jf.default)("15m"),jv="2560x1440",re=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.TESTIM_LAMBDATEST||e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){re.isLambdatestGrid(e)&&(re.lambdatestConfigPromise||=El(),re.lambdatestConfig=await re.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Bv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await he(Fv))return;let t=Uv[Wt.platform()+Wt.arch()];if(!t)throw new Error(`tunnel on ${Wt.platform()+Wt.arch()} platform is not supported.`);let r=`${En}.zip`;await Ye(`${Nv}/${t}`,r),await nt(r,En)}static async chmodLtTunnel(e){if(!(Wt.platform()==="win32"||!await he(e))){try{await po.access(e,Zf.constants.X_OK);return}catch{}try{await po.chmod(e,"777")}catch(r){throw Sn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){re.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Xf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;re.tunnelName=se();let c=["--tunnelName",re.tunnelName,"--infoAPIPort",String(t)];if(L.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(L.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Dc(u)])}if(L.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new x("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new x("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await re.delay(3e3),await re.chmodLtTunnel((0,eg.join)(En,"LT")),re.tunnel=Qf.spawn("./LT",c,{cwd:En});let d="",m="";re.tunnel.stdout.on("data",u=>{d+=u.toString()}),re.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Yf.default)(()=>be(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Sn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Sn.error("Failed to start LT tunnel",{err:u}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!re.tunnel))return new Promise((t,r)=>{re.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),re.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,l){var T,I;if(!this.isActive)return{};let c=re.lambdatestConfig.CAPABILITIES[t]||{},d={...re.tunnelName&&{tunnel:!0,tunnelName:re.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:Kf(n,a==null?void 0:a.os)||Kf(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||re.lambdatestConfig.PLATFORM,resolution:re.lambdatestConfig.RESOLUTION??jv,version:t==="safari"&&((I=o==null?void 0:o.lt)==null?void 0:I.safari_version)||c.version};if(l!==q.APPIUM&&l!==q.SELENIUM&&!f){let b=Jl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&_e(h)&&(m=[...m,h]),m.length||Sn.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return g&&_e(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:re.lambdatestConfig.SELENIUM_VERSION,timezone:re.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:L.flags.LTNetworkCapabilities.isEnabled(),ntlm:L.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:L.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},$v=["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"]});var yu={};H(yu,{connect:()=>go,disconnect:()=>ho,serveTunneling:()=>Vv});var fo,tg,rg,Wv,go,ho,Vv,bu=w(()=>{"use strict";Vf();gn();zf();ot();fo=S(require("ora"));$();ne();mo();tg=A("tunnel"),rg=s=>{var e;return[O.TESTIM_LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Wv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},go=async s=>{if(!s.tunnel)return;let e=wr(),t;try{rg(s)?(t=(0,fo.default)("Starting testim lambdatest tunnel...").start(),await re.connectTunnel(s)):Wv(s)?(t=(0,fo.default)("Starting testim cloudflare tunnel...").start(),await Hf(s)):(t=(0,fo.default)("Starting testim ngrok tunnel...").start(),await $f(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."),tg.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
22
+ ${r.stdoutResult}`:n)}},ho=async s=>{if(s.tunnel)try{rg(s)?await re.disconnectTunnel(s):"tunnelRoutes"in s?await qf(s):await Wf(s)}catch(e){let t="catch error - failed to close tunnel";throw tg.error(t,{err:e}),new Error(t)}},Vv=async(s,e=new Promise(()=>{}))=>(await go(s),rs(()=>ho(s)),await e)});function Gv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.TESTIM_LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=sg.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function Hv(s){let e=sg.exec(s);return e==null?void 0:e[3]}function bo(s){var b,v,E,C,D,R,N,k,_,W,V;let e=s&&Hv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&Gv(s),i=s==null?void 0:s.token,o=s==null?void 0:s.slotId,a=(b=s==null?void 0:s.hybrid)==null?void 0:b.tunnel,l=(v=s==null?void 0:s.external)==null?void 0:v.user,c=(E=s==null?void 0:s.external)==null?void 0:E.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((R=(D=(C=s.hybrid)==null?void 0:C.external)==null?void 0:D[s.hybrid.tunnel])==null?void 0:R.user):l,u=d===O.HYBRID?a&&((_=(k=(N=s.hybrid)==null?void 0:N.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:_.key):c,f=s==null?void 0:s.name,h=s&&(s._id||s.gridId),g=s==null?void 0:s.provider,y=(W=s==null?void 0:s.mobileTokens)==null?void 0:W.androidToken,T=(V=s==null?void 0:s.mobileTokens)==null?void 0:V.iosToken,I=s==null?void 0:s.apiUrl;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:I}}async function ig(s,e,t,r,n){let i;try{i=await n()}catch(o){throw Ze.error("failed to get grid",{projectId:s,companyId:e,err:o}),new Error(gt.UNKNOWN)}if(Ze.info("get grid info",{...i,projectId:s,companyId:e}),!i||!["success","error"].includes(i.status))throw Ze.error("invalid response - get grid",{res:i}),new Error(gt.UNKNOWN);if(i.status==="success"){let o=bo(i.grid);return qv(t,e,o.gridId,o.slotId,r),o}throw i.code==="not-found"?new Ke(gt.NOT_FOUND):i.code==="no-available-slot"?new zt(`Failed to run test on ${r} - concurrency limit reached`):(Ze.error("invalid code error response - get grid",{res:i}),new Ke(gt.UNKNOWN))}function zv(s,e,t,r,n,i){return ig(t,e,s,n,()=>Ki(e,t,r,n,i))}function Kv(s,e,t,r,n,i,o){return ig(t,e,s,n,()=>{var c;let l=(c=o.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?Ki(e,t,l._id,n,i):wl(e,t,r,n,i)})}function og(s){return Sl(s)}async function ag(s,e,t){let n=(t||await og(s)).find(i=>i._id===e);if(!n)throw new x(`Failed to find grid id: ${e}`);return bo(n)}async function Jv(s,e,t){let n=(t||await og(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new x(`Failed to find grid name: ${e}`);return bo(n)}async function Tu(s,e){let t=In[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o}=t;if(delete In[s],!r){Ze.warn("failed to find grid slot id",{projectId:e});return}Ze.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await bl(o,e,r,n,i)}catch(a){Ze.error("failed to release slot",{projectId:e,err:a})}}async function Yv(s){let e=Object.values(In).filter(Boolean);if(e.length!==0){Ze.info("keep alive worker slots",{projectId:s,slots:e});try{await yl(s,e)}catch(t){Ze.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Xv(s){ng=global.setInterval(Yv,1e4,s)}async function Qv(s){let e=Object.keys(In);if(e.length){Ze.warn("not all slots released before end runner flow",{projectId:s});try{await ae(e,t=>Tu(Number(t),s))}catch(t){Ze.error("failed to release all slots",{err:t,projectId:s})}}}async function Zv(s){await Qv(s),clearInterval(ng)}function eS(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function tS(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function cg(s){let t=(()=>yo.isEmpty(s.testobjectSauce)?yo.isEmpty(s.saucelabs)?yo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=eS(t,s),l=tS(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a}}async function lg(s,e){let t=s.company.companyId;return await ag(t,e.gridId,s.allGrids)}async function ug(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:l}=s;if(n||o||i)return{mode:"local"};if(r)return cg(s);let c=t==null?void 0:t.companyId;if(a)return ag(c,a,e);if(l)return Jv(c,l,e);if(qs(s)||s.tunnelOnlyMode){Ze.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new Ke("Missing host or grid configuration")}async function pg(s,e,t,r){let{host:n,project:i,grid:o,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return cg(t);if(a)return zv(r,u,i,a,s,e);if(o)return Kv(r,u,i,o,s,e,t);throw new Ke("Missing host or grid configuration")}var yo,Ze,In,sg,ng,qv,Rn,dg,os=w(()=>{"use strict";yo=S(require("lodash"));ge();$();F();ne();J();Ze=A("grid-service"),In={},sg=/(^(https?):\/{2})?(.*)/,ng=null;qv=(s,e,t,r,n)=>{In[s]={gridId:t,companyId:e,slotId:r,browser:n}};Rn={start:Xv,end:Zv};dg=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!o||!a||((a===O.TESTIM_LAMBDATEST||a===O.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==O.HYBRID||!i||!l||!d||!m))return e;let u=await Tl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Ze.info("handling hybrid grid",{response:u,companyId:i});let f=bo({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});async function wu(s,e,t){let r=as[s];if(!r)return;let{slotId:n}=r;if(delete as[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Bl(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function rS(s,e){let t=Object.values(as).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await $l(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function sS(s,e){mg=global.setInterval(()=>rS(s,e),1e4)}async function nS(s,e){let t=Object.keys(as);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await ae(t,r=>wu(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function iS(s,e){await nS(s,e),clearInterval(mg)}async function gg(s,e,t){let r;try{r=await Fl(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(gt.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(gt.UNKNOWN);if(r.status==="success")return fg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new Ke(gt.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new Ke(gt.UNKNOWN))}async function hg(s,e,t,r){let n=as[r];if(!n)throw new Error("slot not found");Object.assign(n,t),fg(r,n),await jl(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,as,mg,fg,xn,cs=w(()=>{"use strict";ge();$();F();ne();J();ct=A("slot-service"),as={},mg=null,fg=(s,e)=>{as[s]=e};xn={start:sS,end:iS}});function Pn(){return To||"master"}function yg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){To="master";return}if(s!=null&&s.isArchived)throw new x(`Branch ${s.branch} is archived, run aborted.`);if(s){To=s.branch||s;return}To=e?"master":void 0}var To,vu=w(()=>{"use strict";J()});var kn,Su,oS,Eu,aS,wo,vo,So,Eo,Io,Ro=w(()=>{"use strict";F();ne();kn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},Su=s=>{let{status:e}=s;return e===me.ABORTED},oS=s=>{let{status:e}=s;return e===me.PASSED},Eu=s=>s.runnerStatus===Cc.SKIPPED,aS=s=>s.testStatus===Xe.EVALUATING,wo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Eu(t)&&(Qe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,vo=s=>Object.values(s).filter(e=>kn(e)&&aS(e)).length,So=s=>Object.values(s).filter(kn),Eo=s=>Object.values(s).filter(oS),Io=s=>Object.values(s).filter(Su)});function lS(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Iu,Ao,cS,xo,Tg=w(()=>{"use strict";Iu=S(require("lodash"));$();Ro();Ao=A("debug-reporter"),cS=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],xo=class{constructor(e){this.options=e}onTestStarted(e,t){Ao.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;Ao.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Iu.default.omit(this.options,cS),company:Iu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=lS(process.argv);Ao.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,i){let o=Eo(e).length,a=Object.keys(e).length-o;Ao.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ru,Pt,_n=w(()=>{"use strict";ne();Ru=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===O.DEVICE_FARM}},Pt=new Ru});var xu={};H(xu,{Reporter:()=>uS});var rr,On,Ir,Co,wg,Au,uS,Cu=w(()=>{"use strict";rr=S(require("chalk")),On=S(require("lodash"));F();ne();_n();Ro();Ir={success:rr.default.green,warn:rr.default.yellow,error:rr.default.red},{CLI_MODE:Co}=Ut,wg="device",Au=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: ${rr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?me.PASSED:me.FAILED,n=`(${e.testId})`,i=Ir[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Ei(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Ir.error("Failed runs are:")),console.log(Ir.error(t.join(`
23
+ \r`)))}onTestPlanFinished(e,t,r,n,i){let o=So(e),a=Eo(e),l=Io(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Pt.isTestStatusEnabled){let I=vo(e);u=` FAILED-EVALUATING: ${I}`,m-=I,f=` SKIPPED: ${wo(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=Ir[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Ei(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=On.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=On.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=On.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=On.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((f,h)=>{var T;let g=(T=f.testData)!=null&&T.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",h+1,":",`${f.name}${Qe(f,this.options)?"-quarantine":""}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Co.APPIUM?wg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${rr.default.underline(n)} slot from ${rr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Co.APPIUM?wg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${rr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===Co.APPIUM?"device":"browser";if(n)console.log(Ir.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(Ir.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Co.APPIUM?"Appium":"Selenium";console.log(Ir.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},uS=Au});var _u={};H(_u,{Reporter:()=>hS});function pS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function dS(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 mS(s){return`${s.visitedUrlsJson||""}`}async function fS(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:pS(u),classname:n,time:Mc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(kn(u)||Su(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=kn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Eu(u)&&Qe(u,i)&&Pt.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=dS(u),h["visited-urls-json"]=mS(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},I={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Pt.isTestStatusEnabled){I.skipped=wo(y,i);let b=vo(y);I.failures-=b,I["failure-evaluating"]=b}return{$:I,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return So(u).length+Io(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new ku.Builder().buildObject(m)}catch(u){return gS(u)}}function gS(s){let e=new ku.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 ku,vg,Pu,hS,Ou=w(()=>{"use strict";ku=S(require("xml2js"));F();vg=require("fs");_n();Ro();Pu=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 fS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await vg.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)}};hS=Pu});var Sg={};H(Sg,{Reporter:()=>yS});function ls(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 Lu,Du,yS,Eg=w(()=>{"use strict";$();Lu=A("team-city-reporter");Du=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 ls(n)}onTestStarted(e,t,r,n){if(r){Lu.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){Lu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ls(t)}' details='${ls(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Lu.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='${ls(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ls(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ls(t)}']`)}},yS=Du});var Ig={};H(Ig,{Reporter:()=>bS});var Mu,bS,Rg=w(()=>{"use strict";Mu=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}}))}},bS=Mu});var Ag={};H(Ag,{Reporter:()=>TS});var Nu,TS,xg=w(()=>{"use strict";F();Zl();Nu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return so(t)}},TS=Nu});var Uu,Z,kt=w(()=>{"use strict";Tg();Uu=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 xo(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Cu(),xu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Ou(),_u));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Eg(),Sg)),r.includes("console")&&Promise.resolve().then(()=>(Cu(),xu)),r.includes("junit")&&Promise.resolve().then(()=>(Ou(),_u)),r.includes("json")&&Promise.resolve().then(()=>(Rg(),Ig)),r.includes("chrome")&&Promise.resolve().then(()=>(xg(),Ag))])).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))}}},Z=new Uu});function Pg(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function kg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Pg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:Cg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function _g({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let I=Pg({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Cg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",I);return}yt("test-run-ci-fail",{...I,failureReason:n.failureReason})}catch(I){f.error("failed to update test end analytics",{err:I})}}function Og(s){yt("batch-run-ci",s)}var Cg,Fu=w(()=>{"use strict";ss();qi();Cg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:es&&e?"ci-with-user":es?"ci":e?"cli-with-user":s});var Dg,Po,Mg=w(()=>{"use strict";Dg=require("istanbul-lib-report"),Po=class extends Dg.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 Ng,Ug,Fg,Ln,bt,Bg,ko,Bu,jg,wS,$g,Wg,vS,SS,Vg,ES,IS,RS,AS,xS,Gg,Hg=w(()=>{"use strict";Ng=S(require("ora")),Ug=S(require("dayjs")),Fg=S(require("test-exclude")),Ln=S(require("fs")),bt=S(require("path")),Bg=S(require("istanbul-reports")),ko=S(require("istanbul-lib-report"));ge();J();F();$();wn();Mg();Bu=A("test-run-status"),jg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},wS=s=>!!jg(s).search,$g=s=>s?jg(s).pathname.substring(1):"",Wg=(s,e)=>{let t=$g(e);return!new Fg.default({relativePath:!1,include:s}).shouldInstrument(t)},vS=s=>s.substring(0,s.indexOf("?")),SS=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await at("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Vg=(s,e)=>`${bt.resolve(s,$g(e))}.js`,ES=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await ae(i.sources,async(o,a)=>{if(Wg(r,o))return;let l=Vg(e,o);await Ln.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await Ln.promises.writeFile(l,i.sourcesContent[a])})})},IS={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(wS(e)&&(e=vS(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},RS=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=ko.createContext({dir:t,coverageMap:e,watermarks:ko.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Vg(r,a);return Ln.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new Po({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:IS}),Bg.create(a,l).execute(o)}),i},AS=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await at("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Wg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},xS=async(s,e)=>{let{mergeProcessCovs:r}=await at("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await Rl(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await un(l,9e4);await ae(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await cl(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Gg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Bu.info("start js coverage process");let n=(0,Ng.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,Ug.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([at("istanbul-lib-coverage"),xS(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Bu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ae(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),I=await SS({sourceMapType:T,source:y,sourceMapDir:a});u[h]=I;let b=await AS(s,{source:y,sourceMap:I,functions:g});m.merge(b)}),await ES(s,o,u);let f=await RS(s,m,i,o);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof x?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Bu.error(c,{err:l})}}});var qg={};H(qg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Rr});var xe,CS,Rr,us=w(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},CS=["ALL",...Object.values(xe)],Rr=class{constructor(){this.marks=Object.fromEntries(CS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();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`,Ai(r,50)],[`${t}_P95`,Ai(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Yg={};H(Yg,{initServer:()=>_S,mapFilesToLocalDrive:()=>$u});function $u(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,_o[t.id]?{screenshot:_o[t.id]}:{})),Object.keys(Oo).forEach(t=>{s.assets||={},s.assets[Jg[t]]=Oo[t]}),s.assets||={},s.assets.screenshots=Object.values(_o)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function _S({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await at("multer"),n=typeof t=="string"?t:PS;await ju.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=Dn.join(n,m.testResultId);try{await ju.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=Dn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,Kg.default)();o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(_o[d.stepId]=l.file.path),d.testResultId&&kS.includes(d.subType)&&(Oo[d.subType]||=[],Oo[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new x(`Port ${s} is already in use`));default:return c(u)}}})}var ju,zg,Dn,Kg,PS,_o,Oo,Jg,kS,Wu=w(()=>{"use strict";ju=S(require("fs")),zg=S(require("os")),Dn=S(require("path")),Kg=S(require("express"));J();wn();PS=Dn.join(zg.tmpdir(),"testim/rca/"),_o={},Oo={},Jg={"test-log":"consoleLogs","har-file":"networkLogs"},kS=Object.keys(Jg)});var sr,Vu,Lo,Xg=w(()=>{"use strict";sr=S(require("lodash"));F();$();Vu=A("override-test-data-builder"),Lo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return sr.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)&&!sr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Vu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(sr.isObject(e.overrideAllTestsData)&&!sr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Vu.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}Vu.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 sr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=se();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 Do(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var Ar,et,OS,LS,DS,MS,Mo,Qg=w(()=>{"use strict";Ar=S(require("lodash"));F();ne();os();cs();ge();J();$();kt();gn();Hg();us();Wu();pe();le();Xg();_n();et=A("test-run-status"),OS=gr(),LS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,DS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,MS=ze();Mo=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 Rr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=Hs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:di||t.parallel||1,browser:i,gitBranch:OS,gitCommit:LS,gitRepoUrl:DS,runnerVersion:MS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:I}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ar.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:I},Pl({projectId:n,runId:i,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Z.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Yi(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){et.error("failed to upload test data artifact (runner)",{err:d})}let l=Ar.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,vr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Qe(e,this.options))return;let n=this.exportsGlobal;try{let i=await Do(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 et.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},et.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Xe.EVALUATING&&Pt.isTestStatusEnabled){Z.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(c){Z.onTestPassed(i);return}Z.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Z.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Nc();t.isOverThreshold&&et.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&&$u(o,et),o.resultUrl=qe(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Z.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await Do(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){et.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 vr(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 et.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),Gr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let l=e.browser?Ks(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Hr(L,n)&&zs(a.nativeApp)&&!e.appId,d=Jt(e)&&(Gr(a.nativeApp,n)||c),m=Qe(a,e)||d,u={testId:a.testId,status:m?me.SKIPPED:me.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,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await xn.end(r,t),e==="mongo"&&await Rn.end(t)}async executionStart(e,t,r,n,i){et.info("execution started",{executionId:e});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;rs(()=>Promise.all([this.endKeepAlive(d,t,c),zi("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...L.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await Do(o.beforeSuite,m),f=new Lo(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 I=async()=>{let b=Ar.cloneDeep(this.testRunStatus);await ae(Object.keys(b),async C=>{var _;let D=b[C],R=(_=D.config)==null?void 0:_.testData,N=D.testId,k=await Yi(t,N,C,R,l.defaults);k&&(delete D.config.testData,D.config.testDataUrl=k)});let v=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=dl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:v,intersections:o.intersections});return this.executionStartedPromise=E,E.catch(C=>et.error(C)),E};try{await I()}catch(b){et.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 d;let t=Fc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===me.PASSED&&n++,m===me.SKIPPED&&i++,m===me.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Do(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),et.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Gg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await zi("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await pl(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 US(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function ih(s){return th.readFileSync(s,{encoding:"base64"})}function oh(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&_e(s))&&s){let r=ih(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${qu(r)} current extension count: ${e.length}`),e.push(r)}}function ah(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ps.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=No.basename(i));let l=No.join(process.cwd(),a),c=ih(l);ps.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${qu(c)} current extension count: ${e.length}`),e.push(c)}function FS(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...nh];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Gu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Gu.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};Hu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-2",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Hu(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Gu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Pc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),oh(r,c,o),a===q.EXTENSION&&ah(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return re.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function jS(s,e,t){let r={"pdfjs.disabled":!0};return L.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":eh.join(","),"browser.helperApps.neverAsk.openFile":eh.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 $S(s){return`${s.width}x${s.height}`}function WS(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,sh.cloneDeep)(t.sl);return t.sl.screenResolution&&(n["sauce:options"].screenResolution=$S(t.sl.screenResolution),delete i.screenResolution),lt.merge(i,n,r)}return lt.merge(n,r)}return{}}function VS(s,e,t){return lt.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function GS(s){return s.perfecto?s.perfecto:{}}function HS(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 qS(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=Xa(i,o)),a}function Uo(s){var I,b,v,E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let C=[],D=[...nh],R={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(N=>D.push(`--${N}`)),t.chromeBinaryLocation&&(R.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&ah(t,C,D,null,c),oh(o,C,c),{logLevel:Zg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:C,...R},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=qS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:Zg,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!lt.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Hu(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);lt.merge(h.desiredCapabilities,WS(t,r,n),VS(t,r,n),GS(t),HS(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((I=i.host)!=null&&I.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&L.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=BS(h,t,n,o,i,T,c,d);break;case"firefox":h=jS(h,t,c);break;case"safari":case"safari technology preview":h=US(h,y);break;default:break}lt.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let C={"hub.lambdatest.com":"lambdatest",[L.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=_=>_[i.provider]||_[h.host]||_[C[h.host]],R=_=>{var W,V;return D(_)||_[(W=h.desiredCapabilities)==null?void 0:W.browserName]||_[(V=h.desiredCapabilities)==null?void 0:V.version]||_||{}},N=JSON.parse(L.flags.addCustomCapabilities.getValue()||"{}"),k=R(R(N));Object.keys(k).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(h.desiredCapabilities,k))}catch(C){ps.error("Failed to load custom capabilities",{error:C,customCapabilities:L.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(NS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let C=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),R=(v=D==null?void 0:D.capabilities)==null?void 0:v.alwaysMatch,N=_=>_.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(_=>{var W,V;R!=null&&R[_]&&(R[_].extensions=(V=(W=C==null?void 0:C[_])==null?void 0:W.extensions)==null?void 0:V.map(N))}),R!=null&&R.loadExtension&&(R.loadExtension=(E=C==null?void 0:C.loadExtension)==null?void 0:E.map(N));let k=require("util");console.log(k.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var th,No,rh,lt,sh,ps,Zg,Gu,nh,qu,Hu,NS,BS,eh,zu=w(()=>{"use strict";th=S(require("fs")),No=S(require("path")),rh=S(require("crypto")),lt=S(require("lodash"));F();pe();$();le();ne();mo();sh=require("lodash"),ps=A("testim-desired-capabilities-builder"),Zg=pi?"debug":"silent",Gu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},nh=["--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"],qu=(...s)=>rh.createHash("sha256").update(s.join("")).digest("hex"),Hu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",NS=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=L.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};BS=lt.memoize(FS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(lt.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return qu(o,a,l,r,c,i)}),eh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Be(s){var e,t,r,n,i,o,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function lh(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 Ku=w(()=>{"use strict"});function Ju(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Ju(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var uh=w(()=>{"use strict"});var ph,dh,Vt,zS,KS,Fo,mh=w(()=>{"use strict";ph=S(require("promise-queue")),dh=S(require("webdriverio"));pe();We();F();$();Fr();uh();Ku();us();Vt=A("WebDriverApi"),zS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},KS={implicit:0,pageLoad:1,script:2},Fo=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().substr(0,2e3):"";throw Vt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),tc!==void 0&&(e=tc);let t=1/0;this.queue=new ph.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),U("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{Vt.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),U("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await dh.remote(e),this.logGridStatus(r)}),U("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,xe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Vt.info("grid status is not supported by the grid",{testResultId:e});return}Vt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Vt.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 Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},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){Vt.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(Be(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 Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Be(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Ju,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Be(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(lh(e,this.isSafari(),Vt))})}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[KS[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(Be(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(De(e)),await this.elementIdValue(De(e),t)}async getViewportSize(e){let t=await this.execute(zS);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async 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(De(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(()=>{var i;return(i=this.client)==null?void 0:i.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let 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(Be(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Vt.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Vt.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 fh={};H(fh,{doubleClick:()=>JS});var JS,gh=w(()=>{"use strict";JS=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(I,b,v){return v>I&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Mn={};H(Mn,{dispatchFocus:()=>YS});function YS(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 Nn=w(()=>{"use strict"});var wh={};H(wh,{WebDriver:()=>Cr});async function eE(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 QS(r):void 0}catch(r){je.info("Error getting cdpAddress",r);return}}var ds,bh,Th,je,nr,XS,hh,QS,ir,ZS,yh,xr,Cr,Un=w(()=>{"use strict";ds=S(require("lodash"));F();We();zu();bh=S(require("p-retry")),Th=S(require("ua-parser-js"));Fr();$();Ku();mh();J();le();us();je=A("webdriver"),[nr,XS]=[0,2],{extractElementId:hh,getCdpAddressForHost:QS}=K,ir=()=>(Te(),Ue(er)).getSessionPlayer().codeSnippets,ZS=()=>(Te(),Ue(er)).getSessionPlayer().locatorBuilderUtils,yh=()=>(Te(),Ue(er)).getSessionPlayer().utils,xr=()=>(Te(),Ue(er)).getSessionPlayer().positionUtils;Cr=class extends Fo{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,v,E,C,D,R,N,k;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(v=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:v.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Uo({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,I=u?()=>null:()=>this.executeJS("window.focus()");try{U("before initClient in webdriver.js init");let _=await this.initClient(y,i,d);U("after initResult before getCdpAddress in init"),this.cdpUrl=await eE(_),U("after getCdpAddress in webdriver.js init"),je.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),L.flags.dontFocusOnInit.isEnabled()||await I(),U("after focus and delay in webdriver.js init")}catch(_){let W=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));je.error("failed to init webdriver",{err:_,capabilitiesAsString:W});let V=((D=(C=n==null?void 0:n.company)==null?void 0:C.activePlan)==null?void 0:D.plan)==="free";throw(R=_.stack)!=null&&R.includes("at startWebDriverSession")&&((N=_.message)!=null&&N.startsWith("Failed to create session"))&&((k=_.message)!=null&&k.includes("Timeout awaiting 'request'"))&&V?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):_.message.match(/Invalid username or password/)?new $r(_.message):_.message.match(/capabilit(y|ies)/)?new gi(_.message):_.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):_.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${_.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ds.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=se();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,je.warn("close unexpected alert open"),await this.alertAccept().catch(l=>je.warn("failed to click on alert",{err:l}));return}if(je.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;je.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=hh(r.value);return await this.switchToFrame({ELEMENT:n,[Ht]: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 hi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||L.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
24
24
  var fn = ${ir().getLocatedElementCode};
25
25
  return fn.apply(null, arguments);
26
26
  `,t)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:i,attributeValue:o,locatedElement:a}){let l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(i,o)}await this.executeJS(`
27
27
  var getLocatedElement = ${ir().getLocatedElementCode};
28
28
  var setDynamicParentAttribute = ${n.toString()};
29
29
  return setDynamicParentAttribute.apply(null, arguments)
30
- `,{attributeName:tE().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(n){let i=getLocatedElement(n);if(!i)return null;let o=parseInt(window.getComputedStyle(i).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(i).paddingLeft.replace("px",""),10)||0,l=i.getBoundingClientRect();return{top:Math.round(l.top+o),left:Math.round(l.left+a)}}return this.executeJS(`
30
+ `,{attributeName:ZS().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(n){let i=getLocatedElement(n);if(!i)return null;let o=parseInt(window.getComputedStyle(i).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(i).paddingLeft.replace("px",""),10)||0,l=i.getBoundingClientRect();return{top:Math.round(l.top+o),left:Math.round(l.left+a)}}return this.executeJS(`
31
31
  const getLocatedElement = ${ir().getLocatedElementCode};
32
32
  const getLocation = ${r.toString()};
33
33
  return getLocation.apply(null, arguments)
@@ -46,8 +46,8 @@ ${r.stdoutResult}`:n)}},ho=async s=>{if(s.tunnel)try{rg(s)?await re.disconnectTu
46
46
  var eventData = arguments[0];
47
47
  var done = arguments[1];
48
48
  return doubleClick.call(null, eventData, done);
49
- `,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,nr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,ZS,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw je.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:i,y:o,width:a,height:l}=n.value;return{x:r.left+i+a/2,y:r.top+o+l/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:i}=r.clickOffset;try{return await this.moveTo(t,n,i)}catch(o){if(Be(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,n="viewport",i=0){return[{type:"pointerMove",duration:i,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){je.error("tried to use element origin but failed because of visibility, trying location",n);let i=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(i)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),n=r[0].pointerPosition,i=r.at(-1).pointerPosition;return{xDiff:i.screenX-n.screenX,yDiff:i.screenY-n.screenY}}async dragWithMoveTo(t,r,n,i,o){return await this.moveTo(t,i,o),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,i,o){let a=this.getMoveActions(i,o,t,1),l=this.getClickActions(["pointerDown"],nr),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],nr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,i,o){let{width:a,height:l}=r,c=n-a/2+1,d=i-l/2,m=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Be(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:i},c=10,d=Math.round(o(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:l,toX:c,toY:d}=n,m=xr().calculateElementMiddlePoint(i),u=xr().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+o,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(o),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],nr),I=ms.flatMap(g,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(f,h),v=this.getClickActions(["pointerUp"],nr),E=y.concat(T).concat(I).concat(b).concat(v);return this.actions([{type:"pointer",id:"mouse",actions:E}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(i){if(Be(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw i}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(i){if(Be(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw i}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(i){if(Be(i))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw i}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],nr);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],nr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(hh(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(i){je.error("error getting element location",{err:i})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){je.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||je.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){if(this.unsupportedActions.has("submit"))return await super.submitFormManually(t);try{return await super.submitForm(t)}catch(r){if(Be(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var Yu,Xu,Fn,Qu=w(()=>{"use strict";$();le();ge();Yu=A("lab-features-service"),Xu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Yu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await Il(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){Yu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=L.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:i}=this,o=n.find(l=>l.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(i&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw Yu.error(t,{featureFlagName:e.name}),new Error(t)}},Fn=new Xu});function sE(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function nE(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function iE(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function oE(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
50
- var res = requireOrImportMethod('${sE(n[h])}');
49
+ `,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,nr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,XS,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Be(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw je.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:i,y:o,width:a,height:l}=n.value;return{x:r.left+i+a/2,y:r.top+o+l/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:i}=r.clickOffset;try{return await this.moveTo(t,n,i)}catch(o){if(Be(o))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw o}}getMoveActions(t=1,r=1,n="viewport",i=0){return[{type:"pointerMove",duration:i,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){je.error("tried to use element origin but failed because of visibility, trying location",n);let i=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(i)}}getDragCoordinates(t){let r=t.filter(o=>o.event==="mousemove"||o.event==="pointermove"),n=r[0].pointerPosition,i=r.at(-1).pointerPosition;return{xDiff:i.screenX-n.screenX,yDiff:i.screenY-n.screenY}}async dragWithMoveTo(t,r,n,i,o){return await this.moveTo(t,i,o),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,i,o){let a=this.getMoveActions(i,o,t,1),l=this.getClickActions(["pointerDown"],nr),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],nr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,i,o){let{width:a,height:l}=r,c=n-a/2+1,d=i-l/2,m=this.getDragCoordinates(o),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Be(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,i){let o=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:i},c=10,d=Math.round(o(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,i){return this.getMoveRelativeSequence(t,r,n,i).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:i,fromX:o,fromY:a,toRect:l,toX:c,toY:d}=n,m=xr().calculateElementMiddlePoint(i),u=xr().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+o,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(o),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],nr),I=ds.flatMap(g,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(f,h),v=this.getClickActions(["pointerUp"],nr),E=y.concat(T).concat(I).concat(b).concat(v);return this.actions([{type:"pointer",id:"mouse",actions:E}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(i){if(Be(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw i}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(i){if(Be(i))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw i}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(i){if(Be(i))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw i}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:i,toRect:o,toX:a,toY:l}=t,c=xr().calculateElementMiddlePoint(r),d=xr().calculateElementMiddlePoint(o),m=Math.floor(c.x+n),u=Math.floor(c.y+i),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],nr);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],nr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(hh(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(i){je.error("error getting element location",{err:i})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){je.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||je.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){if(this.unsupportedActions.has("submit"))return await super.submitFormManually(t);try{return await super.submitForm(t)}catch(r){if(Be(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var Yu,Xu,Fn,Qu=w(()=>{"use strict";$();le();ge();Yu=A("lab-features-service"),Xu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Yu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await Il(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){Yu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=L.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:i}=this,o=n.find(l=>l.featureFlagName===e),a=o==null?void 0:o.enabled;return Boolean(i&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw Yu.error(t,{featureFlagName:e.name}),new Error(t)}},Fn=new Xu});function tE(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function rE(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(o=>{let a=JSON.parse(o);return import(r(s,a.main||`${t}index.js`))})}}}function sE(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function nE(s,e,t,r,n={},i=void 0,o=void 0){let a=Object.keys(n).map(h=>`
50
+ var res = requireOrImportMethod('${tE(n[h])}');
51
51
  if (res.sync) {
52
52
  var ${h} = res.lib;
53
53
  } else {
@@ -110,7 +110,7 @@ ${r.stdoutResult}`:n)}},ho=async s=>{if(s.tunnel)try{rg(s)?await re.disconnectTu
110
110
  });
111
111
  `,d=`
112
112
  function injectCode(params, args, incomingParams, context, code) {
113
- const constructWithArguments = ${iE.toString()}
113
+ const constructWithArguments = ${sE.toString()}
114
114
 
115
115
  const resolve = result => {
116
116
  parentPort.postMessage({
@@ -176,7 +176,7 @@ ${r.stdoutResult}`:n)}},ho=async s=>{if(s.tunnel)try{rg(s)?await re.disconnectTu
176
176
  // A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
177
177
  const __require = require;
178
178
  const { parentPort } = require('worker_threads');
179
- const requireOrImportMethod = ${nE.toString()}
179
+ const requireOrImportMethod = ${rE.toString()}
180
180
 
181
181
  // requireCode will set async to be true if needed.
182
182
  ${a}
@@ -214,17 +214,17 @@ ${r.stdoutResult}`:n)}},ho=async s=>{if(s.tunnel)try{rg(s)?await re.disconnectTu
214
214
  injectCode(params, args, incomingParams, context, code);
215
215
  });
216
216
  })();
217
- `,u=[],f=new Ih.Worker(m,{eval:!0});try{return await oe(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};ut.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"?ut.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):ut.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",()=>{ut.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 ie))throw h;return ut.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 aE(s){try{await vh.promises.rm(s,{recursive:!0,force:!0})}catch(e){ut.warn("failed to remove install npm packages folder",{err:e})}}function Rh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function gs(s,e,t,r,n,i){let o=Rh(n,e,s,t),{data:a}=await cE(o,r,i);return a}async function hs(s,e,t,r,n,i,o,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||L.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=Sm(y.testimPackageLocalLocation);return[y.paramName,fs.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Rh(o,n,e,i);if(c){let y=await pn(c);y&&(l=y)}Buffer.isBuffer(l)&&(ut.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(ut.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await oE(u,t,r,s,m,a,l),nodeVersion:process.version}}async function cE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Ah(),o=L.flags.reuseCliPkgInstallFolder.isEnabled()?n:fs.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Em(o,r,a,t),ut.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=wm(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:fs.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw ut.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await oe(l(),t)}catch(c){throw c instanceof ie&&ut.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Ah(){return fs.join(Sh.tmpdir(),"/testim_local_packages")}function lE(){let s=Ah();return aE(s)}var vh,Sh,fs,Eh,Ih,ut,ys=w(()=>{"use strict";vh=S(require("fs")),Sh=S(require("os")),fs=S(require("path"));F();Qr();Eh=S(require("data-uri-to-buffer")),Ih=require("worker_threads");J();$();ge();Qr();le();ut=A("cli-service");lE().catch(s=>ut.warn("failed to clean local package folder",{err:s}))});var or={};H(or,{run:()=>pE});function uE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=L.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var pE,xh=w(()=>{"use strict";ys();J();le();pE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await hs(r,n,i,o,a,l,c,d,m,u);return f&&uE({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ie?new Error("Timeout while running action"):f}}});var Zu={};H(Zu,{run:()=>dE});var dE,Ch=w(()=>{"use strict";ys();J();dE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await gs(t,r,n,o,i,a),success:!0}}catch(l){if(l instanceof Rt)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof ie)return{success:!1,code:"timeout"};throw l}}});async function kh(s,e,t,r){try{return await xl(s,e,t,r)}catch{Bo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function fE(s,e,t,r,n){return Bo.info("finished to run remote step",{stepId:t,sessionId:n}),await kh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Ph(s,e,t,r,n){return Bo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await kh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function _h(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),l=t.id;Bo.info("start play remote step",{stepType:o,stepId:l,sessionId:a});let c=mE[o];if(!c)return await Ph(n,r,l,`Failed to find step type ${o}`,a);try{let d=await c.run(e,t,i);return await fE(n,r,l,d,a)}catch(d){return await Ph(n,r,l,d.message,a)}}var Bo,mE,Oh=w(()=>{"use strict";xh();ge();Ch();$();Bo=A("step-playback"),mE={"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":or,"cli-download-code-step":or,"node-package":Zu}});var ep,Lh,Pr,hE,tp,Tt,jo=w(()=>{"use strict";F();ot();ep=S(require("ws")),Lh=require("events");$();pe();Pr=A("socket-service"),hE=5e3,tp=class extends Lh.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Pr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),hE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Pr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(pd);return xt().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new ep.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Pr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Pr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===ep.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Pr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Pr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Pr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(l){n(l)&&i(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=o.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=se(),l={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",c=>c.id===a,o),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},Tt=new tp});var Mh,rp,yE,bE,TE,Dh,$o,bs,sp=w(()=>{"use strict";Mh=S(require("p-retry")),rp=S(require("socket.io-client"));pe();F();$();yE=50,bE=10,TE=5e3,Dh=10*1e3,$o=A("base socket service"),bs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);$o.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{}$o.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===bE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=yE)throw new Error(`Can't connect to Testim Servers.
218
- Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{$o.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:Dh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=rp.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Dh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=rp.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Mh.default)(()=>oe(n(),TE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&$o.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Nh={};H(Nh,{remoteStepServiceSocketIO:()=>wE});var np,wE,Uh=w(()=>{"use strict";sp();np=class extends bs{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))}},wE=new np});var Fh={};H(Fh,{remoteStepService:()=>Ts});var ip,jn,op,Ts,Wo=w(()=>{"use strict";jo();ne();le();({REMOTE_STEP_SAVED:ip}=At),op=class{async init(e){L.flags.useNewWSCLI.isEnabled()||(jn=(await Promise.resolve().then(()=>(Uh(),Nh))).remoteStepServiceSocketIO,jn.init(e))}joinToRemoteStep(e){return L.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[ip]):jn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(L.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[ip],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}jn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return L.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[ip]),Promise.resolve()):jn.unlistenToRemoteStep(e)}},Ts=new op});var ap,kr,Bh=w(()=>{"use strict";sp();ap=class extends bs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},kr=new ap});var $h={};H($h,{testResultService:()=>_t});var jh,cp,_t,Vo=w(()=>{"use strict";jh=require("events");jo();ne();le();Bh();cp=class extends jh.EventEmitter{init(e){if(L.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}kr.init(e),kr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return L.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]):kr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(L.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]);return}await kr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(L.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}kr.listenToTestResult(e,t,r)}getSocket(){if(!L.flags.useNewWSCLI.isEnabled())return kr.getSocket()}},_t=new cp});var Vh,Gh,Hh,ve,vE,qh,Wh,Go,zh=w(()=>{"use strict";Vh=S(require("lodash"));F();pe();We();ss();ot();ge();Oh();Gh=S(require("p-retry")),Hh=require("node:url");$();ao();ps();ne();Wo();Vo();ge();ve=A("test-run-handler"),vE=3,qh=20*1e3,Wh=s=>JSON.stringify(s).length<qh,Go=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Rr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Js(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return Ks(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Gr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?vi.FROM_DEVICE:vi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){var t;let e=await dn({projectId:this._options.project,testId:this.testId,branch:this.branch});for(let r of e.scenarioData.steps){let n=(t=r==null?void 0:r.element)==null?void 0:t.mobileLocator;if((n==null?void 0:n.domMode)==="enhanced")return!0}return!1}async getRunRequestParams(){var r,n;let t={tokenV3:await xt(),refreshToken:Wi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:yd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Vi()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Wh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),ve.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):ve.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${qh} 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 Sn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return ve.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Wh(e))return;let r=async()=>{try{return await Cl(this._options.project,this._testId,this._testResultId,e)}catch(o){return ve.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Al(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){U("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{U("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};U("before Runtime.evaluate"),await(0,Gh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),U("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return U("after Runtime.evaluate"),c.value}catch(o){throw ve.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Hh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await Sr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){ve.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else _t.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Sr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return ve.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw ve.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Fe.TEST_START_TIMEOUT_MSG)}catch(i){throw ve.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Fe.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await _t.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||_t.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Vh.debounce(async()=>{try{await _t.joinToTestResult(this._testResultId,this.testId)}catch(o){ve.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Sr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(ve.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return ve.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)_t.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await hl(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){ve.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&_t.off("socket-connected",e)}}listenToRemoteStep(e){Ts.listenToRemoteStep(this.testResultId,t=>{_h(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:vE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Ho,Kh=w(()=>{"use strict";zh();Ho=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Go(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var SE,EE,IE,$n,lp=w(()=>{"use strict";as();ls();$();SE=A("worker-utils"),EE=async(s,e,t)=>{e&&await Tu(s,t)},IE=async(s,e,t)=>{await wu(s,e,t)},$n=async(s,e,t,r,n,i)=>{SE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await EE(s,e,t),n==="redis"&&await IE(s,r,t)}}});function CE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var zo,Xh,Ko,dp,Qh,wt,Jh,Yh,up,Wn,RE,pp,AE,ar,xE,qo,PE,Ot,Vn=w(()=>{"use strict";zo=S(require("ms")),Xh=S(require("lodash")),Ko=S(require("p-retry")),dp=S(require("dayjs")),Qh=S(require("dayjs/plugin/duration"));F();We();as();ls();ge();$();lp();kt();mo();le();Wo();Vo();ot();Ge();ne();J();dp.default.extend(Qh.default);wt=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Jh,TEST_START_TIMEOUT_MSG:Yh,TEST_COMPLETE_TIMEOUT_MSG:up}=Fe,{SETUP_TIMEOUT:Wn,NETWORK_ERROR:RE,GRID_ERROR:pp,BROWSER_CLOSED:AE,SELENIUM_ERROR:ar,UNKNOWN_ERROR:xE,MOBILE_SESSION_ERROR:qo}=Hs;PE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new re;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await pg(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Fs(!0)}async getBrowserOnce(e,t,r,n){throw new Fs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Qe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Hr(L,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=L.flags.increaseTDCRequestTimeout.isEnabled(),r=e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN,n=fr(L.flags.appiumConnectionRequestTimeout.getValue(),(0,zo.default)("2m")),i=fr(L.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===O.BROWSERSTACK||t&&r?o+(0,zo.default)("10m"):o+(0,zo.default)("1m")}getSessionTimeout(){if(Jt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,Ko.default)(async()=>{let n=Date.now();try{return await oe(this.getSlotOnce(e),this.options.getBrowserTimeout,Fe.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Ko.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await oe(gg(o,a,this.id),this.options.getBrowserTimeout,Fe.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof zt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ce(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{U("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);U("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Ko.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await dg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c,U("before getBrowserOnce");let f=await oe(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Fe.GET_BROWSER_TIMEOUT_MSG);return U("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof It)&&this.options.mode!==q.APPIUM&&await ce(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),U("after getBrowserOnce retries")}catch(o){throw await $n(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[It,$r].some(a=>o instanceof a)?o:o instanceof Ke?new dr(o,pp):new dr(o,ar)}return n}async runTest(e,t,r){var d;U("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Jt(this.options)&&this.handleMobileTest(e);if(o)return o;U("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await xt(),await this.runTestOnce(e,c)}finally{await $n(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var _,W;if(Qe(g,this.options)||Hr(L,(_=this.options.gridData)==null?void 0:_.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let I=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof dr,v=I(Yh),E=y&&(I(up)||v&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||v)&&e.retryOnInfraErrors,R=E&&e.hasMoreTimeoutRetries(),N=e.hasMoreRetries()&&!b&&!E,k=!g.success&&(N||R||D);try{let V=e.retryKey;g.testRetryKey=V;let Y=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,k,Y),await this.runTestCleanup(),k){if(R&&await e.startNewTimeoutRetry(),D){wt.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 te=(W=this.options.projectData)==null?void 0:W.projectId,de=e.testResultId,Lt=e.testId;await Ji(te,de,Lt,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return N&&!D&&!R&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(k)}t(this.id,...r);return}catch(V){if(V instanceof qt)return;wt.error("failed to process test result",{error:V}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
219
- Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:I,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:v}=Oc,E=g instanceof Error?g.message:g;return E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(Jh)||E.includes(b)?{errorType:Wn,reason:"timeout while getting device"}:E.includes(T)||E.includes(v)?{errorType:qo,reason:"app doesn't exist on device"}:E.includes(I)?{errorType:qo,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:qo,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:qo,reason:E}},a=(g,y)=>{let T=this.options.mode===q.APPIUM?"device":"browser";if(!y&&L.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:RE,reason:i()};let I=g instanceof Error?g.message:g;if(I.includes(Jh))return{errorType:Wn,reason:`Test couldn't get ${T}`};if(I.includes(Yh))return{errorType:Wn,reason:"Test couldn't be started"};if(I.includes(up)){if(!this.testRunTimeout)return{errorType:Wn,reason:"Test timeout reached: test is too long"};let b=dp.default.duration({milliseconds:this.testRunTimeout}),v=Math.floor(b.asMinutes()),E=b.asSeconds(),C=v>0?` ${v} min`:"",D=E>0?` ${E} sec`:"";return{errorType:Wn,reason:`Test timeout reached (timeout:${C}${D}): test is too long`}}if(g instanceof dr&&g.type){if(g.type===pp)return{errorType:pp,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===ar)return{errorType:ar,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===AE?{errorType:ar,reason:`Session terminated, this is often caused to connection
220
- problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:ar,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:ar,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:ar,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:ar,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:xE,reason:I}},l=async g=>{var v;let y=await Ic();!y&&L.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),wt.warn("error on run",{err:g});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:I,reason:b}=this.options.mode===q.APPIUM?o(g):a(g,y);Ji(T,this.testResultId,this.testId,{status:Gs.COMPLETED,success:!1,reason:b,errorType:I,testRetryKey:e.retryKey,setupStepResult:{status:Gs.COMPLETED,success:!1,reason:b,errorType:I}},e.remoteRunId),await n(CE(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var v;let y=this.testId,T=this.testResultId,I=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!I||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let E=await Sr(y,T,I,b);if(wt.warn("Test failed. Got results via API",{err:g,testResult:Xh.default.omit(E,PE),resultId:T}),E&&E.status===Gs.COMPLETED&&!g.message.includes(up))return await n(E);throw g}catch(E){return E!==g&&wt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:I,branch:b,err:E}),l(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===q.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&Ts.joinToRemoteStep(this.testResultId),!d&&_t.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),U("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||Ts.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var mp,Zh,ws,fp=w(()=>{"use strict";F();mp=S(require("p-retry"));F();$();J();Zh=A("window-utils"),ws=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 Zh.warn("selenium navigation failed. retrying to navigate",{err:i}),await ce(1500),r(n-1);throw!i.seleniumStack&&o&&Zh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ce(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ce(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ce(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new It("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,mp.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,mp.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var gp,vs,hp=w(()=>{"use strict";$();gp=A("cookies-utils"),vs=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw gp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw gp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw gp.error("failed to remove cookie",{err:t}),t}}}});var yp,Jo,ey=w(()=>{"use strict";yp=S(require("p-retry")),Jo=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,yp.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,yp.default)(i,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function ty(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 kE.warn("missing elementRect",sy.omit(s,"image")),{};let{elementRect:o}=s,a=await Ss.default.read(Buffer.from(n[1],"base64")),l=o.left*r+i.left*r,c=o.top*r+i.top*r,d=o.width*r,m=o.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new bp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(Ss.default.MIME_PNG)}}async function _E(s,e){let t=await Ss.default.read(s.width,s.height);for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Ss.default.read(Buffer.from(i[1],"base64"));await new Promise((a,l)=>{t.composite(o,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(Ss.default.MIME_PNG)}function OE(s,e){return _E(s,e)}async function LE(){}async function DE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await LE(s[i]);return{key:i,url:o}}let r=await ae(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function ry(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 sy,Ss,kE,bp,Yo,ny=w(()=>{"use strict";sy=S(require("lodash"));F();Ss=S(require("jimp"));$();kE=A("image-capture-utils"),bp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Yo=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 ty(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:ry(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 DE({screenImage:t.image,absoluteScreenHighlight:ry(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>ce(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await ty({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 l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,I=Array.from({length:Math.ceil(h/g)},(v,E)=>({scrollX:Math.min(E*g,h-g),cropX:E*g-Math.min(E*g,h-g),cropW:g-(E*g-Math.min(E*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(v,E)=>({scrollY:Math.min(E*T,y-T),cropY:E*T-Math.min(E*T,y-T),cropH:T-(E*T-Math.min(E*T,y-T))}));return I.flatMap(v=>b.map(E=>({scrollPos:{x:v.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:v.cropX,width:v.cropW,height:E.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),OE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var iy,oy,Xo,Qo,ay=w(()=>{"use strict";iy=S(require("p-retry")),oy=S(require("semver"));F();$();fp();ey();ny();Te();Xo=A("tab-service"),Qo=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),Xo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=se();function l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new ws(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Yo(t,a,new Jo(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=Q(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Q();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){Xo.error("failed to get url or title",{err:i})}}catch(n){Xo.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ce(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){Xo.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,iy.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=oy.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Q();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var Tp,Zo,wp=w(()=>{"use strict";Tp=class{select(){return console.log(`
217
+ `,u=[],f=new Ih.Worker(m,{eval:!0});try{return await oe(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};ut.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"?ut.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):ut.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",()=>{ut.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 ie))throw h;return ut.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 iE(s){try{await vh.promises.rm(s,{recursive:!0,force:!0})}catch(e){ut.warn("failed to remove install npm packages folder",{err:e})}}function Rh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function fs(s,e,t,r,n,i){let o=Rh(n,e,s,t),{data:a}=await oE(o,r,i);return a}async function gs(s,e,t,r,n,i,o,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||L.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=Sm(y.testimPackageLocalLocation);return[y.paramName,ms.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Rh(o,n,e,i);if(c){let y=await un(c);y&&(l=y)}Buffer.isBuffer(l)&&(ut.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(ut.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await nE(u,t,r,s,m,a,l),nodeVersion:process.version}}async function oE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Ah(),o=L.flags.reuseCliPkgInstallFolder.isEnabled()?n:ms.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Em(o,r,a,t),ut.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=wm(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ms.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw ut.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await oe(l(),t)}catch(c){throw c instanceof ie&&ut.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Ah(){return ms.join(Sh.tmpdir(),"/testim_local_packages")}function aE(){let s=Ah();return iE(s)}var vh,Sh,ms,Eh,Ih,ut,hs=w(()=>{"use strict";vh=S(require("fs")),Sh=S(require("os")),ms=S(require("path"));F();Qr();Eh=S(require("data-uri-to-buffer")),Ih=require("worker_threads");J();$();ge();Qr();le();ut=A("cli-service");aE().catch(s=>ut.warn("failed to clean local package folder",{err:s}))});var or={};H(or,{run:()=>lE});function cE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=L.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var lE,xh=w(()=>{"use strict";hs();J();le();lE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await gs(r,n,i,o,a,l,c,d,m,u);return f&&cE({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ie?new Error("Timeout while running action"):f}}});var Zu={};H(Zu,{run:()=>uE});var uE,Ch=w(()=>{"use strict";hs();J();uE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await fs(t,r,n,o,i,a),success:!0}}catch(l){if(l instanceof Rt)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof ie)return{success:!1,code:"timeout"};throw l}}});async function kh(s,e,t,r){try{return await xl(s,e,t,r)}catch{Bo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function dE(s,e,t,r,n){return Bo.info("finished to run remote step",{stepId:t,sessionId:n}),await kh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Ph(s,e,t,r,n){return Bo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await kh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function _h(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),l=t.id;Bo.info("start play remote step",{stepType:o,stepId:l,sessionId:a});let c=pE[o];if(!c)return await Ph(n,r,l,`Failed to find step type ${o}`,a);try{let d=await c.run(e,t,i);return await dE(n,r,l,d,a)}catch(d){return await Ph(n,r,l,d.message,a)}}var Bo,pE,Oh=w(()=>{"use strict";xh();ge();Ch();$();Bo=A("step-playback"),pE={"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":or,"cli-download-code-step":or,"node-package":Zu}});var ep,Lh,Pr,fE,tp,Tt,jo=w(()=>{"use strict";F();ot();ep=S(require("ws")),Lh=require("events");$();pe();Pr=A("socket-service"),fE=5e3,tp=class extends Lh.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Pr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),fE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Pr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(pd);return xt().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new ep.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Pr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Pr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===ep.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Pr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Pr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Pr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(l){n(l)&&i(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=o.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=se(),l={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",c=>c.id===a,o),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},Tt=new tp});var Mh,rp,gE,hE,yE,Dh,$o,ys,sp=w(()=>{"use strict";Mh=S(require("p-retry")),rp=S(require("socket.io-client"));pe();F();$();gE=50,hE=10,yE=5e3,Dh=10*1e3,$o=A("base socket service"),ys=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);$o.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{}$o.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===hE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=gE)throw new Error(`Can't connect to Testim Servers.
218
+ Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{$o.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:Dh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=rp.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Dh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=rp.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Mh.default)(()=>oe(n(),yE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&$o.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Nh={};H(Nh,{remoteStepServiceSocketIO:()=>bE});var np,bE,Uh=w(()=>{"use strict";sp();np=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},bE=new np});var Fh={};H(Fh,{remoteStepService:()=>bs});var ip,jn,op,bs,Wo=w(()=>{"use strict";jo();ne();le();({REMOTE_STEP_SAVED:ip}=At),op=class{async init(e){L.flags.useNewWSCLI.isEnabled()||(jn=(await Promise.resolve().then(()=>(Uh(),Nh))).remoteStepServiceSocketIO,jn.init(e))}joinToRemoteStep(e){return L.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[ip]):jn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(L.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[ip],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}jn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return L.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[ip]),Promise.resolve()):jn.unlistenToRemoteStep(e)}},bs=new op});var ap,kr,Bh=w(()=>{"use strict";sp();ap=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},kr=new ap});var $h={};H($h,{testResultService:()=>_t});var jh,cp,_t,Vo=w(()=>{"use strict";jh=require("events");jo();ne();le();Bh();cp=class extends jh.EventEmitter{init(e){if(L.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}kr.init(e),kr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return L.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]):kr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(L.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]);return}await kr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(L.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}kr.listenToTestResult(e,t,r)}getSocket(){if(!L.flags.useNewWSCLI.isEnabled())return kr.getSocket()}},_t=new cp});var Vh,Gh,Hh,ve,TE,qh,Wh,wE,Go,zh=w(()=>{"use strict";Vh=S(require("lodash"));F();pe();We();ss();ot();ge();Oh();Gh=S(require("p-retry")),Hh=require("node:url");$();ao();us();ne();Wo();Vo();ge();ve=A("test-run-handler"),TE=3,qh=20*1e3,Wh=s=>JSON.stringify(s).length<qh,wE="Test couldn't be started",Go=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Rr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Ks(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return zs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Gr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?vi.FROM_DEVICE:vi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){var t;let e=await pn({projectId:this._options.project,testId:this.testId,branch:this.branch});for(let r of e.scenarioData.steps){let n=(t=r==null?void 0:r.element)==null?void 0:t.mobileLocator;if((n==null?void 0:n.domMode)==="enhanced")return!0}return!1}async getRunRequestParams(){var r,n;let t={tokenV3:await xt(),refreshToken:Wi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:yd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Vi()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Wh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),ve.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):ve.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${qh} 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 vn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return ve.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Wh(e))return;let r=async()=>{try{return await Cl(this._options.project,this._testId,this._testResultId,e)}catch(o){return ve.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Al(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===wE||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){U("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{U("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};U("before Runtime.evaluate"),await(0,Gh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),U("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return U("after Runtime.evaluate"),c.value}catch(o){throw ve.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Hh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await Sr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){ve.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else _t.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Sr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return ve.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw ve.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Fe.TEST_START_TIMEOUT_MSG)}catch(i){throw ve.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Fe.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await _t.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||_t.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Vh.debounce(async()=>{try{await _t.joinToTestResult(this._testResultId,this.testId)}catch(o){ve.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Sr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(ve.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return ve.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)_t.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await hl(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){ve.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&_t.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{_h(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:TE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Ho,Kh=w(()=>{"use strict";zh();Ho=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Go(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var vE,SE,EE,$n,lp=w(()=>{"use strict";os();cs();$();vE=A("worker-utils"),SE=async(s,e,t)=>{e&&await Tu(s,t)},EE=async(s,e,t)=>{await wu(s,e,t)},$n=async(s,e,t,r,n,i)=>{vE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await SE(s,e,t),n==="redis"&&await EE(s,r,t)}}});function xE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var zo,Xh,Ko,dp,Qh,wt,Jh,Yh,up,Wn,IE,pp,RE,ar,AE,qo,CE,Ot,Vn=w(()=>{"use strict";zo=S(require("ms")),Xh=S(require("lodash")),Ko=S(require("p-retry")),dp=S(require("dayjs")),Qh=S(require("dayjs/plugin/duration"));F();We();os();cs();ge();$();lp();kt();mo();le();Wo();Vo();ot();Ge();ne();J();dp.default.extend(Qh.default);wt=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Jh,TEST_START_TIMEOUT_MSG:Yh,TEST_COMPLETE_TIMEOUT_MSG:up}=Fe,{SETUP_TIMEOUT:Wn,NETWORK_ERROR:IE,GRID_ERROR:pp,BROWSER_CLOSED:RE,SELENIUM_ERROR:ar,UNKNOWN_ERROR:AE,MOBILE_SESSION_ERROR:qo}=Gs;CE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new re;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await pg(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Us(!0)}async getBrowserOnce(e,t,r,n){throw new Us(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Qe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Hr(L,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=L.flags.increaseTDCRequestTimeout.isEnabled(),r=e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN,n=fr(L.flags.appiumConnectionRequestTimeout.getValue(),(0,zo.default)("2m")),i=fr(L.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===O.BROWSERSTACK||t&&r?o+(0,zo.default)("10m"):o+(0,zo.default)("1m")}getSessionTimeout(){if(Jt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,Ko.default)(async()=>{let n=Date.now();try{return await oe(this.getSlotOnce(e),this.options.getBrowserTimeout,Fe.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Ko.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await oe(gg(o,a,this.id),this.options.getBrowserTimeout,Fe.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof zt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ce(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{U("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);U("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Ko.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await dg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c,U("before getBrowserOnce");let f=await oe(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Fe.GET_BROWSER_TIMEOUT_MSG);return U("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof It)&&this.options.mode!==q.APPIUM&&await ce(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),U("after getBrowserOnce retries")}catch(o){throw await $n(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[It,$r].some(a=>o instanceof a)?o:o instanceof Ke?new dr(o,pp):new dr(o,ar)}return n}async runTest(e,t,r){var d;U("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Jt(this.options)&&this.handleMobileTest(e);if(o)return o;U("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await xt(),await this.runTestOnce(e,c)}finally{await $n(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var _,W;if(Qe(g,this.options)||Hr(L,(_=this.options.gridData)==null?void 0:_.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let I=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof dr,v=I(Yh),E=y&&(I(up)||v&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||v)&&e.retryOnInfraErrors,R=E&&e.hasMoreTimeoutRetries(),N=e.hasMoreRetries()&&!b&&!E,k=!g.success&&(N||R||D);try{let V=e.retryKey;g.testRetryKey=V;let Y=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,k,Y),await this.runTestCleanup(),k){if(R&&await e.startNewTimeoutRetry(),D){wt.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 te=(W=this.options.projectData)==null?void 0:W.projectId,de=e.testResultId,Lt=e.testId;await Ji(te,de,Lt,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return N&&!D&&!R&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(k)}t(this.id,...r);return}catch(V){if(V instanceof qt)return;wt.error("failed to process test result",{error:V}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
219
+ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:I,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:v}=Oc,E=g instanceof Error?g.message:g;return E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(Jh)||E.includes(b)?{errorType:Wn,reason:"timeout while getting device"}:E.includes(T)||E.includes(v)?{errorType:qo,reason:"app doesn't exist on device"}:E.includes(I)?{errorType:qo,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:qo,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:qo,reason:E}},a=(g,y)=>{let T=this.options.mode===q.APPIUM?"device":"browser";if(!y&&L.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:IE,reason:i()};let I=g instanceof Error?g.message:g;if(I.includes(Jh))return{errorType:Wn,reason:`Test couldn't get ${T}`};if(I.includes(Yh))return{errorType:Wn,reason:"Test couldn't be started"};if(I.includes(up)){if(!this.testRunTimeout)return{errorType:Wn,reason:"Test timeout reached: test is too long"};let b=dp.default.duration({milliseconds:this.testRunTimeout}),v=Math.floor(b.asMinutes()),E=b.asSeconds(),C=v>0?` ${v} min`:"",D=E>0?` ${E} sec`:"";return{errorType:Wn,reason:`Test timeout reached (timeout:${C}${D}): test is too long`}}if(g instanceof dr&&g.type){if(g.type===pp)return{errorType:pp,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===ar)return{errorType:ar,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===RE?{errorType:ar,reason:`Session terminated, this is often caused to connection
220
+ problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:ar,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:ar,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:ar,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:ar,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:AE,reason:I}},l=async g=>{var v;let y=await Ic();!y&&L.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),wt.warn("error on run",{err:g});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:I,reason:b}=this.options.mode===q.APPIUM?o(g):a(g,y);Ji(T,this.testResultId,this.testId,{status:Vs.COMPLETED,success:!1,reason:b,errorType:I,testRetryKey:e.retryKey,setupStepResult:{status:Vs.COMPLETED,success:!1,reason:b,errorType:I}},e.remoteRunId),await n(xE(this.testId,this.testName,this.testResultId,b),g)},c=async g=>{var v;let y=this.testId,T=this.testResultId,I=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!I||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:g}),l(g);try{let E=await Sr(y,T,I,b);if(wt.warn("Test failed. Got results via API",{err:g,testResult:Xh.default.omit(E,CE),resultId:T}),E&&E.status===Vs.COMPLETED&&!g.message.includes(up))return await n(E);throw g}catch(E){return E!==g&&wt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:I,branch:b,err:E}),l(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===q.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&bs.joinToRemoteStep(this.testResultId),!d&&_t.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),U("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||bs.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var mp,Zh,Ts,fp=w(()=>{"use strict";F();mp=S(require("p-retry"));F();$();J();Zh=A("window-utils"),Ts=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return Zh.warn("selenium navigation failed. retrying to navigate",{err:i}),await ce(1500),r(n-1);throw!i.seleniumStack&&o&&Zh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ce(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ce(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ce(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new It("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,mp.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,mp.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var gp,ws,hp=w(()=>{"use strict";$();gp=A("cookies-utils"),ws=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw gp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw gp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw gp.error("failed to remove cookie",{err:t}),t}}}});var yp,Jo,ey=w(()=>{"use strict";yp=S(require("p-retry")),Jo=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,yp.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,yp.default)(i,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function ty(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 PE.warn("missing elementRect",sy.omit(s,"image")),{};let{elementRect:o}=s,a=await vs.default.read(Buffer.from(n[1],"base64")),l=o.left*r+i.left*r,c=o.top*r+i.top*r,d=o.width*r,m=o.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new bp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(vs.default.MIME_PNG)}}async function kE(s,e){let t=await vs.default.read(s.width,s.height);for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await vs.default.read(Buffer.from(i[1],"base64"));await new Promise((a,l)=>{t.composite(o,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(vs.default.MIME_PNG)}function _E(s,e){return kE(s,e)}async function OE(){}async function LE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await OE(s[i]);return{key:i,url:o}}let r=await ae(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function ry(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 sy,vs,PE,bp,Yo,ny=w(()=>{"use strict";sy=S(require("lodash"));F();vs=S(require("jimp"));$();PE=A("image-capture-utils"),bp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Yo=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 ty(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:ry(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 LE({screenImage:t.image,absoluteScreenHighlight:ry(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>ce(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await ty({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 l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,I=Array.from({length:Math.ceil(h/g)},(v,E)=>({scrollX:Math.min(E*g,h-g),cropX:E*g-Math.min(E*g,h-g),cropW:g-(E*g-Math.min(E*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(v,E)=>({scrollY:Math.min(E*T,y-T),cropY:E*T-Math.min(E*T,y-T),cropH:T-(E*T-Math.min(E*T,y-T))}));return I.flatMap(v=>b.map(E=>({scrollPos:{x:v.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:v.cropX,width:v.cropW,height:E.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),_E(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var iy,oy,Xo,Qo,ay=w(()=>{"use strict";iy=S(require("p-retry")),oy=S(require("semver"));F();$();fp();ey();ny();Te();Xo=A("tab-service"),Qo=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),Xo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=se();function l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Ts(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Yo(t,a,new Jo(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=Q(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Q();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){Xo.error("failed to get url or title",{err:i})}}catch(n){Xo.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ce(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){Xo.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,iy.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=oy.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Q();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var Tp,Zo,wp=w(()=>{"use strict";Tp=class{select(){return console.log(`
221
221
  internal error - cant use port selector in selenium!!!!
222
- `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Zo=new Tp});var Gn,ea,ta=w(()=>{"use strict";hp();F();Te();Gn={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},ea=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Ys;this.getLinksFromUnescapeHTML=Xs;this.cookieUtils=new vs(this.driver)}get sessionPlayerInit(){return Q()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,i=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-i.x,y:e.y-i.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function ly(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=cy(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:l}=Q();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw ME.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=cy(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,i,o,a,l){let c=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,i,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=L.flags.enableFrameSwitchOptimization.isEnabled(),c=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),I=0;for(let b of T)I++,this.currentFrameHandler=await this.locate(b,I,this.currentFrameHandler,i,o,r);return this.currentFrameHandler}}let u=await o.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,i,o,r);return g}}return e}var ME,NE,cy,uy=w(()=>{"use strict";$();le();Te();Fr();ME=A("frame-locator"),NE="ELEMENT",cy=s=>s?s[NE]||s[Ht]:null});var ra,vp=w(()=>{"use strict";pe();ra=()=>{try{if(ud)return!1;if(require("inspector").url())return!0}catch{}return!1}});var G,ue=w(()=>{"use strict";Te();G=class{constructor(e,t,r,n={},i=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=i;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return Q()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function FE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:L.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?L.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function BE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new py.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,i,o,a){let{locatorBuilderUtils:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=Q();if(FE(n,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(E){throw _r.error("failed to execute getVisibilityCode",{err:E}),E}let{value:T}=y||{},I=T.elementVisibilityInfo||UE,[b,v]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(I,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Q();await s.execute(r(t))}}}var py,_r,UE,Hn,dy=w(()=>{"use strict";ue();$();le();Te();py=require("linkedom"),_r=A("locate-step-action"),UE={opacity:1,clientRects:{}};Hn=class extends G{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return BE(e)}static getFrameIdByTestimFrameId(){throw _r.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw _r.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw _r.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw _r.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw _r.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw _r.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var my={};H(my,{scroll:()=>jE});var jE,fy=w(()=>{"use strict";jE=function(s,e,t,r,n,i,o,a){function l(I,b){if(!b)return{success:!1};elementScrollTo(b,I.x,I.y);let v=b.scrollLeft,E=b.scrollTop;return{success:Math.abs(E-I.y)<1&&Math.abs(v-I.x)<1,actualX:v,actualY:E}}function c(I,b){if(!t)return{x:n,y:i};let v=getLocatedElement(b);if(r&&!v)return{x:I.scrollWidth,y:I.scrollHeight};if(!v)throw new Error("could not find target element");let E=v.getBoundingClientRect(),C=0,D=0,R=Math.max(window.innerHeight-(E.height+10),0),N=Math.max(window.innerWidth-(E.width+10),0);return C=a?I.scrollTop+E.top-Math.min(i,R):I.scrollTop,D=o?I.scrollLeft+E.left-Math.min(n,N):I.scrollLeft,{x:Math.round(D),y:Math.round(C)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let I=T.getBoundingClientRect();g=I.left,y=I.top}return{success:h.success,actualX:g,actualY:y}}});var sa,gy=w(()=>{"use strict";ue();sa=class extends G{getFailureString(e,t,r,n,i){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${i}, x: ${n})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${i}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${n}`),o}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:i}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(fy(),my)),d=`
222
+ `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Zo=new Tp});var Gn,ea,ta=w(()=>{"use strict";hp();F();Te();Gn={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},ea=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Js;this.getLinksFromUnescapeHTML=Ys;this.cookieUtils=new ws(this.driver)}get sessionPlayerInit(){return Q()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,i=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-i.x,y:e.y-i.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function ly(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=cy(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,i){let{frameOffset:o,locatedElement:a}=r,{locatorBuilderUtils:l}=Q();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw DE.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=cy(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:o,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,i,o,a,l){let c=new this.LocateElementPlayer(o);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,i,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=o.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,i,o){let a=L.flags.enableFrameSwitchOptimization.isEnabled(),c=i.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),I=0;for(let b of T)I++,this.currentFrameHandler=await this.locate(b,I,this.currentFrameHandler,i,o,r);return this.currentFrameHandler}}let u=await o.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,i,o,r);return g}}return e}var DE,ME,cy,uy=w(()=>{"use strict";$();le();Te();Fr();DE=A("frame-locator"),ME="ELEMENT",cy=s=>s?s[ME]||s[Ht]:null});var ra,vp=w(()=>{"use strict";pe();ra=()=>{try{if(ud)return!1;if(require("inspector").url())return!0}catch{}return!1}});var G,ue=w(()=>{"use strict";Te();G=class{constructor(e,t,r,n={},i=void 0,o=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=i;this.locateElementPlayer=o;this.exportsTest=a;this.frameId=0}get driver(){var e;return(e=this.context.project.defaults)!=null&&e.ignoreVisibilityForExisting&&!this.stepActionUtils.driver.getIgnoreVisibility()&&this.stepActionUtils.driver.setIgnoreVisibility(!0),this.stepActionUtils.driver}get sessionPlayerInit(){return Q()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function UE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:L.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?L.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function FE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new py.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,i,o,a){let{locatorBuilderUtils:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=Q();if(UE(n,d,m,s))return s.isVisible(e.seleniumElement);if(s.getIgnoreVisibility())return{visible:!0,invisibleReason:"visibility is ignored"};if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(E){throw _r.error("failed to execute getVisibilityCode",{err:E}),E}let{value:T}=y||{},I=T.elementVisibilityInfo||NE,[b,v]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(I,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Q();await s.execute(r(t))}}}var py,_r,NE,Hn,dy=w(()=>{"use strict";ue();$();le();Te();py=require("linkedom"),_r=A("locate-step-action"),NE={opacity:1,clientRects:{}};Hn=class extends G{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return FE(e)}static getFrameIdByTestimFrameId(){throw _r.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw _r.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw _r.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw _r.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw _r.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw _r.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var my={};H(my,{scroll:()=>BE});var BE,fy=w(()=>{"use strict";BE=function(s,e,t,r,n,i,o,a){function l(I,b){if(!b)return{success:!1};elementScrollTo(b,I.x,I.y);let v=b.scrollLeft,E=b.scrollTop;return{success:Math.abs(E-I.y)<1&&Math.abs(v-I.x)<1,actualX:v,actualY:E}}function c(I,b){if(!t)return{x:n,y:i};let v=getLocatedElement(b);if(r&&!v)return{x:I.scrollWidth,y:I.scrollHeight};if(!v)throw new Error("could not find target element");let E=v.getBoundingClientRect(),C=0,D=0,R=Math.max(window.innerHeight-(E.height+10),0),N=Math.max(window.innerWidth-(E.width+10),0);return C=a?I.scrollTop+E.top-Math.min(i,R):I.scrollTop,D=o?I.scrollLeft+E.left-Math.min(n,N):I.scrollLeft,{x:Math.round(D),y:Math.round(C)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let I=T.getBoundingClientRect();g=I.left,y=I.top}return{success:h.success,actualX:g,actualY:y}}});var sa,gy=w(()=>{"use strict";ue();sa=class extends G{getFailureString(e,t,r,n,i){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${i}, x: ${n})`;let o="Scrolling limit reached";return e.shouldScrollTop&&(o+=`. Expected top margin: ${r}, actual: ${i}`),e.shouldScrollLeft&&(o+=`. Expected left margin: ${t}, actual: ${n}`),o}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:i}}=this.sessionPlayerInit,o=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(fy(),my)),d=`
223
223
  const getLocatedElement = ${n.getLocatedElementCode};
224
224
  const elementScrollTo = ${l.toString()};
225
225
  const scroll = ${c.toString()};
226
226
  return scroll.apply(null, arguments)
227
- `;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var hy,yy=w(()=>{"use strict";hy=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,l){e[t(a)]=l},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),i=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var by,Ty=w(()=>{"use strict";by=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(k){e({status:"done",result:k,success:!0})}function a(k){k||={},e({status:"failed",result:k,success:!1,keep:!0})}function l(k){return k!=null&&k.toLowerCase?(k=k.toLowerCase(),k==="text"?"text/plain":k==="url"?"text/uri-list":k):k}function c(){try{return new DataTransfer}catch{return{data:{},setData(_,W){i[l(_)]=W},getData(_){return i[l(_)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(k){let _=k;for(;_&&_!==document.documentElement;){if(_.draggable)return _;_=_.parentElement}return null}function h(k,_,W){let V=_.element,{dispatchDragEventsOnClosestDraggable:Y}=W;if(d.includes(k.type)&&Y){if(!V&&_.lastDraggedElement)return _.lastDraggedElement;let te=f(V);if(te)return _.lastDraggedElement=te,te}return V}function g(k,_,W){function V(St,Ur,P){return P>St&&P<Ur}let Y=k.pointerPosition||{};if(_)return{x:Y.originX||0,y:Y.originY||0};let te=W.getBoundingClientRect(),de=Y.originX&&V(te.left,te.left+te.width,Y.originX)?Y.originX:te.left+te.width/2,Lt=Y.originY&&V(te.top,te.top+te.height,Y.originY)?Y.originY:te.top+te.height/2;return{x:de,y:Lt}}function y(k,_,W){let V=(_==null?void 0:_.modifiers)||{},Y=g(k,W.isDrag,W.element),te=(_==null?void 0:_.button)||0,de=k.event;return m.includes(de)?I(de,V,Y.x,Y.y,te):u.includes(de)?v(de,V,Y.x,Y.y):b(de,V,Y.x,Y.y,te)}function T(k,_,W){return{screenX:0,screenY:0,clientX:_,clientY:W,ctrlKey:Boolean(k.ctrl),altKey:Boolean(k.alt),shiftKey:Boolean(k.shift),metaKey:Boolean(k.meta),bubbles:!0,cancelable:!0,composed:!0}}function I(k,_,W,V,Y){if(n){let de=T(_,W,V);return de.pointerType="mouse",de.isPrimary=!0,new window.PointerEvent(k,de)}let te=document.createEvent("PointerEvent");return te.initPointerEvent(k,!0,!0,document.defaultView,1,0,0,W,V,Boolean(_.ctrl),Boolean(_.alt),Boolean(_.shift),Boolean(_.meta),Y,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),te}function b(k,_,W,V,Y){let te=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return te.initMouseEvent(k,!0,!0,document.defaultView,1,0,0,W,V,Boolean(_.ctrl),Boolean(_.alt),Boolean(_.shift),Boolean(_.meta),Y,document.body?document.body.parentNode:document.documentElement),te}function v(k,_,W,V){if(k==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let de=document.createEvent("CustomEvent");return de.initCustomEvent(k,!0,!0,null),Object.assign(de,{dataTransfer:window.TSTA.dataTransfer}),de}let Y=T(_,W,V),te=new window.DragEvent(k,Y);return Object.defineProperties(te,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),te}function E(k,_,W){let V=h(k,_,W);V==null||V.dispatchEvent(k)}function C(k,_){function W(){return k.event==="click"&&_.isDrag&&!_.allEventsOnSameElement}return W()}function D(k,_,W){if(W){let V=Math.min(W.timeStamp-_.timeStamp,40);setTimeout(()=>{R(k)},V)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function R(k){let _,W=k.events[k.eventIndex],V=k.events[++k.eventIndex];try{k.element=getLocatedElement(W.locatedElement),_=y(W,s,k)}catch(Y){return a(`exception in get event in drag step:${Y.message}`)}if(C(W,k))return D(k,W,V);if(_)try{E(_,k,W)}catch(Y){return a(`exception in executeEvent in drag step:${Y.message}`)}else return a(`cannot execute event ${W.event}`);D(k,W,V)}let N={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{R(N)}catch(k){a(k)}},0)}});var wy={};H(wy,{doClick:()=>$E});var $E,vy=w(()=>{"use strict";$E=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var D;function E(R){function N(){return i(R).find(W=>[...W.classList||[]].includes("Select-control"))}function k(){let W=N();return W?W.querySelector("input"):null}let _=k();_==null||_.focus()}let C=(D=b.quirks)==null?void 0:D.isReactSelect;v.type==="mousedown"&&C&&E(b.element)}function n(b,v){var C;let E=(C=b.quirks)==null?void 0:C.isCKEditorFrame;v.type==="click"&&E&&document.body.focus()}function i(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function o(b){let v={status:"done",result:b,success:!0,...I.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},E=b.getBoundingClientRect(),C=E.left+E.width/2,D=E.top+E.height/2,k=f("mousemove",v,C,D,0);b.dispatchEvent(k)}function d(b,v){function E(k,_,W){return W>k&&W<_}let C=b.pointerPosition||{},D=v.getBoundingClientRect(),R=C.originX&&E(D.left,D.left+D.width,C.originX)?C.originX:D.left+D.width/2,N=C.originY&&E(D.top,D.top+D.height,C.originY)?C.originY:D.top+D.height/2;return{x:R,y:N}}function m(b,v,E){return{screenX:0,screenY:0,clientX:v,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,v,E,C){if(!window.PointerEvent)return;let D=m(v,E,C);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,v,E,C,D){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement),R}function h(b,v){let E=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},D=d(b,v.element),R=v.button||0,N=b.event;return E.includes(N)?u(N,C,D.x,D.y):f(N,C,D.x,D.y,R)}function g(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return h(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let I={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!I.element){a("element not found");return}l(I.element),c(I.element);try{y(I);let b=g(),v=I.quirks,E=v==null?void 0:v.isReactSelect,C=v==null?void 0:v.isCKEditorFrame;!E&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var Sy={};H(Sy,{doDragPath:()=>WE});var WE,Ey=w(()=>{"use strict";WE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},E=b.getBoundingClientRect(),C=E.left+E.width/2,D=E.top+E.height/2,k=u("mousemove",v,C,D,0);b.dispatchEvent(k)}function c(b,v){function E(k,_,W){return W>k&&W<_}let C=b.pointerPosition||{};if(I.isDrag)return{x:C.originX||0,y:C.originY||0};let D=v.getBoundingClientRect(),R=C.originX&&E(D.left,D.left+D.width,C.originX)?C.originX:D.left+D.width/2,N=C.originY&&E(D.top,D.top+D.height,C.originY)?C.originY:D.top+D.height/2;return{x:R,y:N}}function d(b,v,E){return{screenX:0,screenY:0,clientX:v,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,v,E,C,D){if(r){let N=d(v,E,C);return N.pointerType="mouse",N.isPrimary=!0,new window.PointerEvent(b,N)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,E,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function u(b,v,E,C,D){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement),R}function f(b,v){let E=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},D=c(b,v.element),R=v.button||0,N=b.event;return E.includes(N)?m(N,C,D.x,D.y,R):u(N,C,D.x,D.y,R)}function h(b,v){function E(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return E()}function g(b,v,E){try{let C=f(v.events[b],v);h(C,v)||v.element.dispatchEvent(C)}catch{}if(b+1===v.events.length)E();else{let C=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{g(b+1,v,E)},C)}}function y(b,v){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let I={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!I.element){o("element not found");return}a(I.element),l(I.element),y(I,()=>{i()})}});var qn,na,Iy=w(()=>{"use strict";qn=S(require("lodash"));ue();yy();le();Ty();na=class extends G{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(vy(),wy)),Promise.resolve().then(()=>(Nn(),Mn))]),c=`
227
+ `;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,o,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:i.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:i.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,o,f,h)}}}catch{return{errorType:i.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var hy,yy=w(()=>{"use strict";hy=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,l){e[t(a)]=l},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),i=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!i)throw new Error("to element not found");let o=function(a,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};o(n,"dragstart"),o(i,"drop"),o(n,"dragend")}});var by,Ty=w(()=>{"use strict";by=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",i={};window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(k){e({status:"done",result:k,success:!0})}function a(k){k||={},e({status:"failed",result:k,success:!1,keep:!0})}function l(k){return k!=null&&k.toLowerCase?(k=k.toLowerCase(),k==="text"?"text/plain":k==="url"?"text/uri-list":k):k}function c(){try{return new DataTransfer}catch{return{data:{},setData(_,W){i[l(_)]=W},getData(_){return i[l(_)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(k){let _=k;for(;_&&_!==document.documentElement;){if(_.draggable)return _;_=_.parentElement}return null}function h(k,_,W){let V=_.element,{dispatchDragEventsOnClosestDraggable:Y}=W;if(d.includes(k.type)&&Y){if(!V&&_.lastDraggedElement)return _.lastDraggedElement;let te=f(V);if(te)return _.lastDraggedElement=te,te}return V}function g(k,_,W){function V(St,Ur,P){return P>St&&P<Ur}let Y=k.pointerPosition||{};if(_)return{x:Y.originX||0,y:Y.originY||0};let te=W.getBoundingClientRect(),de=Y.originX&&V(te.left,te.left+te.width,Y.originX)?Y.originX:te.left+te.width/2,Lt=Y.originY&&V(te.top,te.top+te.height,Y.originY)?Y.originY:te.top+te.height/2;return{x:de,y:Lt}}function y(k,_,W){let V=(_==null?void 0:_.modifiers)||{},Y=g(k,W.isDrag,W.element),te=(_==null?void 0:_.button)||0,de=k.event;return m.includes(de)?I(de,V,Y.x,Y.y,te):u.includes(de)?v(de,V,Y.x,Y.y):b(de,V,Y.x,Y.y,te)}function T(k,_,W){return{screenX:0,screenY:0,clientX:_,clientY:W,ctrlKey:Boolean(k.ctrl),altKey:Boolean(k.alt),shiftKey:Boolean(k.shift),metaKey:Boolean(k.meta),bubbles:!0,cancelable:!0,composed:!0}}function I(k,_,W,V,Y){if(n){let de=T(_,W,V);return de.pointerType="mouse",de.isPrimary=!0,new window.PointerEvent(k,de)}let te=document.createEvent("PointerEvent");return te.initPointerEvent(k,!0,!0,document.defaultView,1,0,0,W,V,Boolean(_.ctrl),Boolean(_.alt),Boolean(_.shift),Boolean(_.meta),Y,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),te}function b(k,_,W,V,Y){let te=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return te.initMouseEvent(k,!0,!0,document.defaultView,1,0,0,W,V,Boolean(_.ctrl),Boolean(_.alt),Boolean(_.shift),Boolean(_.meta),Y,document.body?document.body.parentNode:document.documentElement),te}function v(k,_,W,V){if(k==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let de=document.createEvent("CustomEvent");return de.initCustomEvent(k,!0,!0,null),Object.assign(de,{dataTransfer:window.TSTA.dataTransfer}),de}let Y=T(_,W,V),te=new window.DragEvent(k,Y);return Object.defineProperties(te,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),te}function E(k,_,W){let V=h(k,_,W);V==null||V.dispatchEvent(k)}function C(k,_){function W(){return k.event==="click"&&_.isDrag&&!_.allEventsOnSameElement}return W()}function D(k,_,W){if(W){let V=Math.min(W.timeStamp-_.timeStamp,40);setTimeout(()=>{R(k)},V)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),o()}function R(k){let _,W=k.events[k.eventIndex],V=k.events[++k.eventIndex];try{k.element=getLocatedElement(W.locatedElement),_=y(W,s,k)}catch(Y){return a(`exception in get event in drag step:${Y.message}`)}if(C(W,k))return D(k,W,V);if(_)try{E(_,k,W)}catch(Y){return a(`exception in executeEvent in drag step:${Y.message}`)}else return a(`cannot execute event ${W.event}`);D(k,W,V)}let N={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{R(N)}catch(k){a(k)}},0)}});var wy={};H(wy,{doClick:()=>jE});var jE,vy=w(()=>{"use strict";jE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var D;function E(R){function N(){return i(R).find(W=>[...W.classList||[]].includes("Select-control"))}function k(){let W=N();return W?W.querySelector("input"):null}let _=k();_==null||_.focus()}let C=(D=b.quirks)==null?void 0:D.isReactSelect;v.type==="mousedown"&&C&&E(b.element)}function n(b,v){var C;let E=(C=b.quirks)==null?void 0:C.isCKEditorFrame;v.type==="click"&&E&&document.body.focus()}function i(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function o(b){let v={status:"done",result:b,success:!0,...I.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},E=b.getBoundingClientRect(),C=E.left+E.width/2,D=E.top+E.height/2,k=f("mousemove",v,C,D,0);b.dispatchEvent(k)}function d(b,v){function E(k,_,W){return W>k&&W<_}let C=b.pointerPosition||{},D=v.getBoundingClientRect(),R=C.originX&&E(D.left,D.left+D.width,C.originX)?C.originX:D.left+D.width/2,N=C.originY&&E(D.top,D.top+D.height,C.originY)?C.originY:D.top+D.height/2;return{x:R,y:N}}function m(b,v,E){return{screenX:0,screenY:0,clientX:v,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,v,E,C){if(!window.PointerEvent)return;let D=m(v,E,C);return D.pointerType="mouse",D.isPrimary=!0,new window.PointerEvent(b,D)}function f(b,v,E,C,D){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement),R}function h(b,v){let E=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},D=d(b,v.element),R=v.button||0,N=b.event;return E.includes(N)?u(N,C,D.x,D.y):f(N,C,D.x,D.y,R)}function g(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return h(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let I={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!I.element){a("element not found");return}l(I.element),c(I.element);try{y(I);let b=g(),v=I.quirks,E=v==null?void 0:v.isReactSelect,C=v==null?void 0:v.isCKEditorFrame;!E&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),o()}catch(b){a(b.toString())}}});var Sy={};H(Sy,{doDragPath:()=>$E});var $E,Ey=w(()=>{"use strict";$E=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(b){e({status:"done",result:b,success:!0})}function o(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},E=b.getBoundingClientRect(),C=E.left+E.width/2,D=E.top+E.height/2,k=u("mousemove",v,C,D,0);b.dispatchEvent(k)}function c(b,v){function E(k,_,W){return W>k&&W<_}let C=b.pointerPosition||{};if(I.isDrag)return{x:C.originX||0,y:C.originY||0};let D=v.getBoundingClientRect(),R=C.originX&&E(D.left,D.left+D.width,C.originX)?C.originX:D.left+D.width/2,N=C.originY&&E(D.top,D.top+D.height,C.originY)?C.originY:D.top+D.height/2;return{x:R,y:N}}function d(b,v,E){return{screenX:0,screenY:0,clientX:v,clientY:E,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(b,v,E,C,D){if(r){let N=d(v,E,C);return N.pointerType="mouse",N.isPrimary=!0,new window.PointerEvent(b,N)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,E,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function u(b,v,E,C,D){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,E,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),D,document.body?document.body.parentNode:document.documentElement),R}function f(b,v){let E=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},D=c(b,v.element),R=v.button||0,N=b.event;return E.includes(N)?m(N,C,D.x,D.y,R):u(N,C,D.x,D.y,R)}function h(b,v){function E(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return E()}function g(b,v,E){try{let C=f(v.events[b],v);h(C,v)||v.element.dispatchEvent(C)}catch{}if(b+1===v.events.length)E();else{let C=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{g(b+1,v,E)},C)}}function y(b,v){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let I={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!I.element){o("element not found");return}a(I.element),l(I.element),y(I,()=>{i()})}});var qn,na,Iy=w(()=>{"use strict";qn=S(require("lodash"));ue();yy();le();Ty();na=class extends G{getDnDRectsAndOffsets(e,t,r,n){let i=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),o=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:i.x,fromY:i.y,toRect:t.rectWithoutFrameOffset,toX:o.x,toY:o.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,i=e.events;if(!(i!=null&&i.length))return{success:!1,reason:"Malformed step: missing recorded events"};let o={isRoot:r.isRoot,locatedElement:r.locatedElement,events:i,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:l}]=await Promise.all([Promise.resolve().then(()=>(vy(),wy)),Promise.resolve().then(()=>(Nn(),Mn))]),c=`
228
228
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
229
229
  var dispatchFocus = ${l.toString()};
230
230
  var doClick = ${a.toString()};
@@ -247,14 +247,14 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
247
247
  var dnd = ${hy.toString()};
248
248
  var eventData = arguments[0];
249
249
  return dnd.call(null, eventData);
250
- `,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var zn,Ry=w(()=>{"use strict";ue();zn=class extends G{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:i}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Ay,VE,ia,xy=w(()=>{"use strict";Ay=S(require("lodash"));ue();$();VE=A("evaluate-expression-step-action"),ia=class extends G{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{VE.info("runner running incoming params evaluation");let i=t.incomingParams||{};Ay.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],c=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,o.concat([c]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var Cy={};H(Cy,{setText:()=>GE});var GE,Py=w(()=>{"use strict";GE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){Lt()},window.addEventListener("unload",window.__unloadNavigator);let i=new Set(["keydown","keyup","keypress"]),o=15;function a(P){try{if(!t)return;let M=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return P.eventData&&(M.data=P.eventData.data),M}catch{}}function l(P){try{let M=document.createEvent("TextEvent");M.data=P.eventData.data;let j=1,z=P.eventData.locale||"en-US";return M.initTextEvent("textInput",!0,!0,window,P.eventData.data,j,z),M}catch{}}function c(P){return a(P)||l(P)}function d(P,M,j){try{return new KeyboardEvent(P,{bubbles:!0,cancelable:!0,location:M.location||0,key:M.key||"",ctrlKey:Boolean(j.ctrl),shiftKey:Boolean(j.shift),altKey:Boolean(j.alt),metaKey:Boolean(j.meta)})}catch{}}function m(P,M,j){try{let z=document.createEvent("KeyboardEvent");return z.initKeyEvent(P,!0,!0,null,Boolean(j.ctrl),Boolean(j.alt),Boolean(j.shift),Boolean(j.meta),M.key||"",0),z}catch{}}function u(P,M,j){try{let z=document.createEvent("Events");return z.initEvent(P,!0,!0),Object.assign(z,{altKey:Boolean(j.alt),ctrlKey:Boolean(j.ctrl),metaKey:Boolean(j.meta),shiftKey:Boolean(j.shift),keyCode:M.key||""}),z}catch{}}function f(P,M,j){return d(P,M,j)||m(P,M,j)||u(P,M,j)}function h(P){if(!i.has(P.event))return null;let M=P.eventData,j=M.modifiers||{},z=f(P.event,M,j);return Object.defineProperties(z,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(z,{_keyCode_:M.keyCode,_charCode_:M.charCode||0}),z}function g(P){return P.event==="textInput"?c(P):h(P)}function y(P,M){return(()=>{var z;return P.event==="textInput"&&!((z=M.quirks)!=null&&z.isAuth0Form)})()}function T(P,M){return P.event==="keyup"&&M.event==="keydown"?o:0}function I(P,M){let j=T(P,M);return Math.min(M.timeStamp-P.timeStamp,j)}function b(P){let M=Object.getOwnPropertyDescriptor(P,"value");if(!M)return;let j=P.value;P.value=`${j}#`,M.configurable&&delete P.value,P.value=j;let z=document.createEvent("HTMLEvents");z.initEvent("input",!0,!1),P.dispatchEvent(z),Object.defineProperty(P,"value",M)}function v(P){if(V(P.element))try{if(b(P.element),t)P.element.dispatchEvent(new Event("change"));else{let M=document.createEvent("HTMLEvents");M.initEvent("change",!1,!0),P.element.dispatchEvent(M)}}catch{}}function E(P,M,j){j?setTimeout(()=>{W(P)},I(M,j)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(P),Lt())}function C(P,M){return(P==="change"||P==="blur")&&M.element.tagName==="OPTION"}function D(P,M,j){return C(P.type,M)?M.element.parentElement:j.locatedElement?getLocatedElement(j.locatedElement):M.element}function R(P,M){let j=P.firstChild,z;for(;j;){if(j.nodeType===3){if(M.offset--<=0)return j}else if(j.nodeType===1&&(z=R(j,M),z))return z;j=j.nextSibling}return null}function N(P,M){if(!(!P||!M)){if(!isNaN(M.start))Object.assign(P,{selectionStart:M.start,selectionEnd:M.end});else if(!isNaN(M.nodeOffset)){let j;if(P.firstChild?j=R(P,{offset:M.nodeOffset}):j=P,j){let z=window.getSelection(),Pe=document.createRange();try{z.removeAllRanges(),Pe.setStart(j,M.textOffset),Pe.setEnd(j,M.textOffset),z.addRange(Pe)}catch{}}}}}function k(P,M){return P==="submit"&&Boolean(M.action)}function _(P,M,j){if(M.isFocusable&&M.isSelectable(P)&&P.type!=="submit")try{N(M.element,j.eventData.selection)}catch{}let z=D(P,M,j);if(!z)throw new Error("could not find element");k(P.type,z)?z.submit():z.dispatchEvent(P)}function W(P){let M,j=P.events[P.eventIndex],z=P.events[++P.eventIndex];try{M=g(j)}catch(Pe){return St(`exception in get event in text step:${Pe.message}`)}if(y(j,P))return E(P,j,z);if(M)try{_(M,P,j)}catch(Pe){return St(`exception in executeEvent in text step:${Pe.message}`)}else if(P.noEventExecuter)P.noEventExecuter(P,j);else return St(`cannot execute event ${j.event}`);E(P,j,z)}function V(P){let M=P.tagName;return M==="INPUT"||M==="TEXTAREA"}function Y(P){return P.getAttribute?Boolean(P.getAttribute("contenteditable")==="true"):!1}function te(P,M){if(V(P.element)){P.element.value=M.eventData.text;let j=document.createEvent("Event");j.initEvent("input",!0,!1),P.element.dispatchEvent(j)}else P.isContentEditable&&(P.element.innerHTML=M.eventData.text)}function de(){var M;let P=document.activeElement;for(;(M=P.shadowRoot)!=null&&M.activeElement;)P=P.shadowRoot.activeElement;return P}function Lt(P){let M={status:"done",result:P,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(M)}function St(P){P||="";let M={status:"failed",result:P,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(M)}try{let P=V(n.element);n.isContentEditable=Y(n.element),!P&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=P||n.isContentEditable,n.isSelectable=M=>M.type!=="keyup",n.noEventExecuter=te}catch(P){St(`exception in set text step:${P.message}`);return}let Ur=de();dispatchFocus(s.elementToFocusLocatedElement,Ur),W(n)}});var oa,ky=w(()=>{"use strict";ue();F();oa=class extends G{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(De(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:i}=this,o=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:l}=i.codeSnippets;if(o.isDraftEditor&&l)return this.driver.executeJS(l(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let c={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(Py(),Cy)),Promise.resolve().then(()=>(Nn(),Mn))]),u=`
250
+ `,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?this.clickJs():this.step.button===2?this.driver.rightClick(r,o):this.driver.leftClick(r,o)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=i=>i.fireOnTarget||["drop","dragenter"].includes(i.event);return e.forEach(i=>Object.assign(i,{locatedElement:n(i)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var zn,Ry=w(()=>{"use strict";ue();zn=class extends G{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:i}}=this,o=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(o),{evaluatedText:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:i.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Ay,WE,ia,xy=w(()=>{"use strict";Ay=S(require("lodash"));ue();$();WE=A("evaluate-expression-step-action"),ia=class extends G{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{WE.info("runner running incoming params evaluation");let i=t.incomingParams||{};Ay.isEmpty(i)&&(i=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let o=["context",...i.as.functionParameters],a=[t,...i.as.functionArguments],c=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,o.concat([c]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(i){let{stepResult:o}=this.sessionPlayerInit.commonConstants;throw{errorType:o.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:i.toString()},success:!1}}}}});var Cy={};H(Cy,{setText:()=>VE});var VE,Py=w(()=>{"use strict";VE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){Lt()},window.addEventListener("unload",window.__unloadNavigator);let i=new Set(["keydown","keyup","keypress"]),o=15;function a(P){try{if(!t)return;let M=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return P.eventData&&(M.data=P.eventData.data),M}catch{}}function l(P){try{let M=document.createEvent("TextEvent");M.data=P.eventData.data;let j=1,z=P.eventData.locale||"en-US";return M.initTextEvent("textInput",!0,!0,window,P.eventData.data,j,z),M}catch{}}function c(P){return a(P)||l(P)}function d(P,M,j){try{return new KeyboardEvent(P,{bubbles:!0,cancelable:!0,location:M.location||0,key:M.key||"",ctrlKey:Boolean(j.ctrl),shiftKey:Boolean(j.shift),altKey:Boolean(j.alt),metaKey:Boolean(j.meta)})}catch{}}function m(P,M,j){try{let z=document.createEvent("KeyboardEvent");return z.initKeyEvent(P,!0,!0,null,Boolean(j.ctrl),Boolean(j.alt),Boolean(j.shift),Boolean(j.meta),M.key||"",0),z}catch{}}function u(P,M,j){try{let z=document.createEvent("Events");return z.initEvent(P,!0,!0),Object.assign(z,{altKey:Boolean(j.alt),ctrlKey:Boolean(j.ctrl),metaKey:Boolean(j.meta),shiftKey:Boolean(j.shift),keyCode:M.key||""}),z}catch{}}function f(P,M,j){return d(P,M,j)||m(P,M,j)||u(P,M,j)}function h(P){if(!i.has(P.event))return null;let M=P.eventData,j=M.modifiers||{},z=f(P.event,M,j);return Object.defineProperties(z,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(z,{_keyCode_:M.keyCode,_charCode_:M.charCode||0}),z}function g(P){return P.event==="textInput"?c(P):h(P)}function y(P,M){return(()=>{var z;return P.event==="textInput"&&!((z=M.quirks)!=null&&z.isAuth0Form)})()}function T(P,M){return P.event==="keyup"&&M.event==="keydown"?o:0}function I(P,M){let j=T(P,M);return Math.min(M.timeStamp-P.timeStamp,j)}function b(P){let M=Object.getOwnPropertyDescriptor(P,"value");if(!M)return;let j=P.value;P.value=`${j}#`,M.configurable&&delete P.value,P.value=j;let z=document.createEvent("HTMLEvents");z.initEvent("input",!0,!1),P.dispatchEvent(z),Object.defineProperty(P,"value",M)}function v(P){if(V(P.element))try{if(b(P.element),t)P.element.dispatchEvent(new Event("change"));else{let M=document.createEvent("HTMLEvents");M.initEvent("change",!1,!0),P.element.dispatchEvent(M)}}catch{}}function E(P,M,j){j?setTimeout(()=>{W(P)},I(M,j)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(P),Lt())}function C(P,M){return(P==="change"||P==="blur")&&M.element.tagName==="OPTION"}function D(P,M,j){return C(P.type,M)?M.element.parentElement:j.locatedElement?getLocatedElement(j.locatedElement):M.element}function R(P,M){let j=P.firstChild,z;for(;j;){if(j.nodeType===3){if(M.offset--<=0)return j}else if(j.nodeType===1&&(z=R(j,M),z))return z;j=j.nextSibling}return null}function N(P,M){if(!(!P||!M)){if(!isNaN(M.start))Object.assign(P,{selectionStart:M.start,selectionEnd:M.end});else if(!isNaN(M.nodeOffset)){let j;if(P.firstChild?j=R(P,{offset:M.nodeOffset}):j=P,j){let z=window.getSelection(),Pe=document.createRange();try{z.removeAllRanges(),Pe.setStart(j,M.textOffset),Pe.setEnd(j,M.textOffset),z.addRange(Pe)}catch{}}}}}function k(P,M){return P==="submit"&&Boolean(M.action)}function _(P,M,j){if(M.isFocusable&&M.isSelectable(P)&&P.type!=="submit")try{N(M.element,j.eventData.selection)}catch{}let z=D(P,M,j);if(!z)throw new Error("could not find element");k(P.type,z)?z.submit():z.dispatchEvent(P)}function W(P){let M,j=P.events[P.eventIndex],z=P.events[++P.eventIndex];try{M=g(j)}catch(Pe){return St(`exception in get event in text step:${Pe.message}`)}if(y(j,P))return E(P,j,z);if(M)try{_(M,P,j)}catch(Pe){return St(`exception in executeEvent in text step:${Pe.message}`)}else if(P.noEventExecuter)P.noEventExecuter(P,j);else return St(`cannot execute event ${j.event}`);E(P,j,z)}function V(P){let M=P.tagName;return M==="INPUT"||M==="TEXTAREA"}function Y(P){return P.getAttribute?Boolean(P.getAttribute("contenteditable")==="true"):!1}function te(P,M){if(V(P.element)){P.element.value=M.eventData.text;let j=document.createEvent("Event");j.initEvent("input",!0,!1),P.element.dispatchEvent(j)}else P.isContentEditable&&(P.element.innerHTML=M.eventData.text)}function de(){var M;let P=document.activeElement;for(;(M=P.shadowRoot)!=null&&M.activeElement;)P=P.shadowRoot.activeElement;return P}function Lt(P){let M={status:"done",result:P,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(M)}function St(P){P||="";let M={status:"failed",result:P,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(M)}try{let P=V(n.element);n.isContentEditable=Y(n.element),!P&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=P||n.isContentEditable,n.isSelectable=M=>M.type!=="keyup",n.noEventExecuter=te}catch(P){St(`exception in set text step:${P.message}`);return}let Ur=de();dispatchFocus(s.elementToFocusLocatedElement,Ur),W(n)}});var oa,ky=w(()=>{"use strict";ue();F();oa=class extends G{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(De(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:i}=this,o=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:l}=i.codeSnippets;if(o.isDraftEditor&&l)return this.driver.executeJS(l(o.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let c={eventType:t,events:e,quirks:r,locatedElement:o.locatedElement,isRoot:o.isRoot,elementToFocusLocatedElement:o.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(Py(),Cy)),Promise.resolve().then(()=>(Nn(),Mn))]),u=`
251
251
  var getLocatedElement = ${i.codeSnippets.getLocatedElementCode};
252
252
  var dispatchFocus = ${m};
253
253
  var setText = ${d.toString()};
254
254
  var eventData = arguments[0];
255
255
  var done = arguments[1];
256
256
  return setText.call(null, eventData, done);
257
- `,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(De(t.seleniumElement),e[r]),r<e.length-1&&await ce(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(De(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var _y={};H(_y,{runCode:()=>HE});var HE,Oy=w(()=>{"use strict";HE=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(y){let T=y.message.toLowerCase().includes("quota"),I=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||I){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let E={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(E)),T||I)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let i={},o={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(i,o,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var aa,Kn,cr,ca=w(()=>{"use strict";aa=S(require("lodash"));F();ue();$();le();Kn=A("base-js-step-action"),cr=class extends G{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,o=L.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return i?a:(a&&Kn.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(i){if(i.message.includes("sessionStorage")||i.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(n):"{}"}throw i}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],i=[t.context,...r.as.functionArguments];return n.push(t.code),i.forEach(o=>{aa.isObject(o)&&Ii(o,"seleniumElement",aa.isEqual)}),{function:{params:n,args:i},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:i=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,l=async()=>{let c;try{c=await this.executeGetStatus(t)}catch(u){Kn.warn("failed to get js status",{err:u}),c={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((c==null?void 0:c.value)||"{}")}catch{Kn.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===i);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-o<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=o,await ce(o),l()):{success:!0})};return l()}async executeInAut(t){let r=L.flags.experimentalPreCodeCompilation.isEnabled(),n=L.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=i.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
257
+ `,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(De(t.seleniumElement),e[r]),r<e.length-1&&await ce(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(De(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var _y={};H(_y,{runCode:()=>GE});var GE,Oy=w(()=>{"use strict";GE=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(y){let T=y.message.toLowerCase().includes("quota"),I=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||I){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let E={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(E)),T||I)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let i={},o={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(i,o,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:i,exportsTest:o,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:i,exportsTest:o,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:i,exportsTest:o,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:i,exportsTest:o,exportsGlobal:a}})}}});var aa,Kn,cr,ca=w(()=>{"use strict";aa=S(require("lodash"));F();ue();$();le();Kn=A("base-js-step-action"),cr=class extends G{isExceedingMaxResultSize(t,r){var n;try{let i=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,o=L.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>o;return i?a:(a&&Kn.warn(`js result size exceeded ${o}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(i){if(i.message.includes("sessionStorage")||i.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(n):"{}"}throw i}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],i=[t.context,...r.as.functionArguments];return n.push(t.code),i.forEach(o=>{aa.isObject(o)&&Ii(o,"seleniumElement",aa.isEqual)}),{function:{params:n,args:i},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:i=""}}=this,o=r.config.retryTimeout,a=r.data.timeToPlayStep-o,l=async()=>{let c;try{c=await this.executeGetStatus(t)}catch(u){Kn.warn("failed to get js status",{err:u}),c={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((c==null?void 0:c.value)||"{}")}catch{Kn.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===i);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-o<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=o,await ce(o),l()):{success:!0})};return l()}async executeInAut(t){let r=L.flags.experimentalPreCodeCompilation.isEnabled(),n=L.flags.experimentalAsyncCustomCode.isEnabled(),i=this.constructJSFunParams(t),o=i.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=i.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
258
258
  ${t.code}
259
259
  };`:`function(${m.join(",")}) {
260
260
  ${t.code}
@@ -264,18 +264,18 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
264
264
  var eventData = arguments[0];
265
265
  var funcToRun = ${a};
266
266
  return runCode.call(null, eventData, funcToRun);
267
- `;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(Kn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),L.flags.useStepResultIdForStepTransactions.isEnabled()&&("stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:Kn.warn("useStepResultIdForStepTransactions is enabled but stepResultId is not present in context",{step:t,context:r})),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var Gt,Ly=w(()=>{"use strict";ca();Gt=class extends cr{isFailedResult(e){return e===!1}}});var Es,Dy=w(()=>{"use strict";ca();Es=class extends cr{isFailedResult(e){return!e}}});var la,My=w(()=>{"use strict";ue();F();ta();la=class extends G{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(De(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(Gn[t]),this.setWithValueApi(e)}}});var ua,Ny=w(()=>{"use strict";ue();ta();ua=class extends G{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Gn[n])t.push(Gn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var Uy={};H(Uy,{selectOption:()=>qE});function qE(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var Fy=w(()=>{"use strict"});var pa,By=w(()=>{"use strict";ue();F();le();pa=class extends G{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(De(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(Fy(),Uy)),c=L.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
267
+ `;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(Kn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),L.flags.useStepResultIdForStepTransactions.isEnabled()&&("stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:Kn.warn("useStepResultIdForStepTransactions is enabled but stepResultId is not present in context",{step:t,context:r})),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var Gt,Ly=w(()=>{"use strict";ca();Gt=class extends cr{isFailedResult(e){return e===!1}}});var Ss,Dy=w(()=>{"use strict";ca();Ss=class extends cr{isFailedResult(e){return!e}}});var la,My=w(()=>{"use strict";ue();F();ta();la=class extends G{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(De(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(Gn[t]),this.setWithValueApi(e)}}});var ua,Ny=w(()=>{"use strict";ue();ta();ua=class extends G{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Gn[n])t.push(Gn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var Uy={};H(Uy,{selectOption:()=>HE});function HE(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var Fy=w(()=>{"use strict"});var pa,By=w(()=>{"use strict";ue();F();le();pa=class extends G{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(De(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(Fy(),Uy)),c=L.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
268
268
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
269
269
  const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
270
270
  const selectOption = ${l.toString()};
271
271
  return selectOption.apply(null, arguments);
272
- `;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var da,jy=w(()=>{"use strict";ue();da=class extends G{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var zE,ma,$y=w(()=>{"use strict";ue();zE=(s,e,t,r)=>({x:t,y:r,width:e,height:s,get top(){return this.y},get left(){return this.x},get right(){return this.x+this.width},get bottom(){return this.y+this.height},toJSON(){}}),ma=class extends G{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:i,height:o}=n,a=i/2,l=o/2,c=this.step.element.clickOffset;if(c&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=c;this.sessionPlayerInit.utils.isWithinTargetRect(zE(o,i,0,0),m,u)&&(a=m,l=u)}let d={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(l)}};return await this.driver.hover(t,d),{success:!0}}}});var Wy={};H(Wy,{wheel:()=>KE});var KE,Vy=w(()=>{"use strict";KE=function(s,e){function r(a,l){function c(h,g,y){return y>h&&y<g}let d=a.pointerPosition||{},m=l.getBoundingClientRect(),u=d.originX&&c(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&c(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:u,y:f}}function n(a,l,c){let d=r(a,c),m=(l==null?void 0:l.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(m.ctrl),alt:Boolean(m.alt),shift:Boolean(m.shift),meta:Boolean(m.meta)};return new WheelEvent("wheel",u)}function i(a,l){if(a.length===0){e({state:"success"});return}if(!l)throw new Error("element not found");let c=a.shift(),d=n(c,s.eventData,l),m=a[0]?Math.min(a[0].timeStamp-c.timeStamp,200):200;l.dispatchEvent(d),setTimeout(()=>{i(a,l)},m)}let o=getLocatedElement(s.locatedElement);i(s.events,o)}});var fa,Gy=w(()=>{"use strict";ue();fa=class extends G{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:n,button:i}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:n,button:i},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:l}=await Promise.resolve().then(()=>(Vy(),Wy)),c=`
272
+ `;return(f=(await this.driver.executeJS(d,r,c)).value)!=null&&f.success?{success:!0}:{success:!1}}}});var da,jy=w(()=>{"use strict";ue();da=class extends G{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var qE,ma,$y=w(()=>{"use strict";ue();qE=(s,e,t,r)=>({x:t,y:r,width:e,height:s,get top(){return this.y},get left(){return this.x},get right(){return this.x+this.width},get bottom(){return this.y+this.height},toJSON(){}}),ma=class extends G{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:i,height:o}=n,a=i/2,l=o/2,c=this.step.element.clickOffset;if(c&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:u}=c;this.sessionPlayerInit.utils.isWithinTargetRect(qE(o,i,0,0),m,u)&&(a=m,l=u)}let d={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(l)}};return await this.driver.hover(t,d),{success:!0}}}});var Wy={};H(Wy,{wheel:()=>zE});var zE,Vy=w(()=>{"use strict";zE=function(s,e){function r(a,l){function c(h,g,y){return y>h&&y<g}let d=a.pointerPosition||{},m=l.getBoundingClientRect(),u=d.originX&&c(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,f=d.originY&&c(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:u,y:f}}function n(a,l,c){let d=r(a,c),m=(l==null?void 0:l.modifiers)||{},u={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(m.ctrl),alt:Boolean(m.alt),shift:Boolean(m.shift),meta:Boolean(m.meta)};return new WheelEvent("wheel",u)}function i(a,l){if(a.length===0){e({state:"success"});return}if(!l)throw new Error("element not found");let c=a.shift(),d=n(c,s.eventData,l),m=a[0]?Math.min(a[0].timeStamp-c.timeStamp,200):200;l.dispatchEvent(d),setTimeout(()=>{i(a,l)},m)}let o=getLocatedElement(s.locatedElement);i(s.events,o)}});var fa,Gy=w(()=>{"use strict";ue();fa=class extends G{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:n,button:i}=e;if(!(r!=null&&r.length))return;let o={events:r,eventData:{modifiers:n,button:i},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:l}=await Promise.resolve().then(()=>(Vy(),Wy)),c=`
273
273
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
274
274
  var wheel = ${l.toString()};
275
275
  var eventData = arguments[0];
276
276
  var done = arguments[1];
277
277
  return wheel.call(null, eventData, done);
278
- `;return{success:((m=(await this.driver.executeCodeAsync(c,a,o)).value)==null?void 0:m.state)==="success"}}}});var Hy={};H(Hy,{downloadFileAndFireDropEvent:()=>JE});var JE,qy=w(()=>{"use strict";JE=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let o=-1,a=0,l=[],c={endWithCallback:void 0,waitOn(){let d=++o;return function(m){d in l||(l[d]=m,a++,e.length===a&&c.endWithCallback(l))}},endWith(d){c.endWithCallback=d}};return c}function n(o,a,l){let c=new XMLHttpRequest;c.open("GET",o),c.responseType="blob",c.onload=function(){if(this.status>=200&&this.status<300)l({blob:c.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},c.onerror=function(){throw new Error("Failed to load blob")},c.send()}let i=r();e.forEach(o=>{n(o.url,o.name,i.waitOn())}),i.endWith(o=>{let a=createDropEvent(o);t.dispatchEvent(a)})}});var YE,ga,zy=w(()=>{"use strict";ue();$();le();YE=A("drop-file-step-action"),ga=class extends G{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,i=this.getTarget(),o=L.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,o,YE),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(qy(),Hy)),c=`
278
+ `;return{success:((m=(await this.driver.executeCodeAsync(c,a,o)).value)==null?void 0:m.state)==="success"}}}});var Hy={};H(Hy,{downloadFileAndFireDropEvent:()=>KE});var KE,qy=w(()=>{"use strict";KE=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let o=-1,a=0,l=[],c={endWithCallback:void 0,waitOn(){let d=++o;return function(m){d in l||(l[d]=m,a++,e.length===a&&c.endWithCallback(l))}},endWith(d){c.endWithCallback=d}};return c}function n(o,a,l){let c=new XMLHttpRequest;c.open("GET",o),c.responseType="blob",c.onload=function(){if(this.status>=200&&this.status<300)l({blob:c.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},c.onerror=function(){throw new Error("Failed to load blob")},c.send()}let i=r();e.forEach(o=>{n(o.url,o.name,i.waitOn())}),i.endWith(o=>{let a=createDropEvent(o);t.dispatchEvent(a)})}});var JE,ga,zy=w(()=>{"use strict";ue();$();le();JE=A("drop-file-step-action"),ga=class extends G{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,i=this.getTarget(),o=L.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,o,JE),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(qy(),Hy)),c=`
279
279
  const getLocatedElement = ${e.getLocatedElementCode};
280
280
  const createDropEvent = ${e.createDropEvent.toString()};
281
281
  const downloadFileAndFireDropEvent = ${l.toString()};
@@ -322,7 +322,7 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
322
322
  input.removeAttribute("disabled");
323
323
  input.focus();
324
324
  }
325
- }`}async function QE(s,e){let t=null;try{t=(await Ec(s)).body}catch(n){if(XE.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${Ky.tmpdir()}/${e}`;return await Jy.promises.writeFile(r,t),r}function ZE(s){return ae(s,e=>QE(e.url,e.name))}function eI(s,e){return e(s)}async function Xy(s,e){let t=await ZE(s),r=await ae(t,n=>eI(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var Ky,Jy,XE,Qy=w(()=>{"use strict";Ky=S(require("os"));Ge();Jy=require("fs");F();$();XE=A("input-file-utils")});function rI(){return`async function downloadAndUpload(locatedElement, fileUrls) {
325
+ }`}async function XE(s,e){let t=null;try{t=(await Ec(s)).body}catch(n){if(YE.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${Ky.tmpdir()}/${e}`;return await Jy.promises.writeFile(r,t),r}function QE(s){return ae(s,e=>XE(e.url,e.name))}function ZE(s,e){return e(s)}async function Xy(s,e){let t=await QE(s),r=await ae(t,n=>ZE(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var Ky,Jy,YE,Qy=w(()=>{"use strict";Ky=S(require("os"));Ge();Jy=require("fs");F();$();YE=A("input-file-utils")});function tI(){return`async function downloadAndUpload(locatedElement, fileUrls) {
326
326
  const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
327
327
  const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
328
328
  const attachTo = document.body || document.documentElement;
@@ -405,18 +405,18 @@ Please make sure the CLI has stable access to the internet. ${Rc()?"(Internal: n
405
405
  return getVisibleElement.apply(null, arguments);
406
406
  `;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw ha.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let i="The element is not editable",o="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ha.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(De(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=L.flags.overrideAzureStorageUrl.isEnabled(),n=L.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:l,driver:c}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,l.testimServicesApi,r,ha);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Nt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
407
407
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
408
- const downloadAndUploadFile = ${rI()};
409
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Xy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ba,Ta,eb=w(()=>{"use strict";ba=require("url");ue();Ta=class extends G{async updateBaseUrl(e){let t=new ba.URL(e),r=new ba.URL(this.context.recordedBaseUrl),n=new ba.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 wa,tb=w(()=>{"use strict";ue();F();wa=class extends G{async performAction(){await ce(this.step.durationMS||0)}}});var va,rb=w(()=>{"use strict";ue();va=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Jn,sb=w(()=>{"use strict";ue();Jn=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Sa,nb=w(()=>{"use strict";ue();Sa=class extends G{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var ib,Sp,Ep,ob=w(()=>{"use strict";ib=S(require("@applitools/spec-driver-webdriverio"));li();Te();Sp=class{constructor(){let{EyeSdkBuilder:e}=Q(),t=od["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:ib.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Q(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Ep=new Sp});var cb,ab,Yn,lb=w(()=>{"use strict";cb=S(require("lodash"));ue();$();ob();ab=A("pixel-validation-step-action"),Yn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Ep.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};cb.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),ab.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){ab.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ep.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Is,Ip=w(()=>{"use strict";ys();J();ca();Is=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:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await hs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ie?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var lr,ub=w(()=>{"use strict";Ip();lr=class extends Is{isFailedResult(e){return e===!1}}});var Ea,pb=w(()=>{"use strict";Ip();Ea=class extends Is{isFailedResult(e){return!e}}});var Ia,db=w(()=>{"use strict";ys();ue();J();Ia=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await gs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ie?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Or,mb=w(()=>{"use strict";ue();Or=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,fb=w(()=>{"use strict";ue();ye=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ra,gb=w(()=>{"use strict";ue();Ra=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Aa,hb=w(()=>{"use strict";ue();Aa=class extends G{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function sI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function xa(s,e){sI(nI,e),e.registerLocateStepActionUtils(Hn.getUtils(s))}var nI,Rp=w(()=>{"use strict";dy();gy();Iy();Ry();xy();ky();Ly();Dy();My();Ny();By();jy();$y();Gy();zy();Zy();eb();tb();rb();sb();nb();lb();ub();pb();db();mb();fb();gb();hb();nI={locate:Hn,scroll:sa,mouse:na,submit:da,text:oa,"special-key":la,"user-code":Gt,"validation-code-step":Gt,"wait-for-code-step":Gt,"action-code-step":Gt,"condition-step":Es,"skip-code-step":Es,"element-code-step":Es,"evaluate-expression":ia,"text-validation":zn,"wait-for-text-validation":zn,"select-option":pa,"drop-file":ga,"input-file":ya,hover:ma,navigation:Ta,wheel:fa,sleep:wa,refresh:va,"keyboard-shortcut-step":ua,"api-validation":Jn,"api-action":Jn,"api-code-step":Gt,"extract-text":Sa,"simple-ui-verification":Yn,"wait-for-simple-ui-verification":Yn,"cli-validation-download-file":Or,"cli-wait-for-download-file":Or,"network-validation-step":Or,"cli-validation-code-step":lr,"cli-wait-for-code-step":lr,"cli-action-code-step":lr,"cli-api-code-step":lr,"cli-condition-step":Ea,"node-package":Ia,"email-code-step":Gt,"cli-email-code-step":lr,"sfdc-internal-test-step":Aa,"sfdc-recorded-step":Ra,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":Or,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var yb,iI,Rs,Ap=w(()=>{"use strict";yb=["simple-ui-verification","wait-for-simple-ui-verification"],iI=[...yb,"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"],Rs=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=iI.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 yb.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 Tb={};H(Tb,{SeleniumTestPlayer:()=>Xn});var bb,oI,Xn,xp=w(()=>{"use strict";F();bb=require("@applitools/eyes-sdk-core");Un();J();$();hp();ay();wp();ta();uy();vp();Te();Rp();Ap();oI=A("SeleniumTestPlayer"),Xn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Rs(ra());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Q();this.driver=n??new Cr;let d=new ea(this.driver);this.stepActionFactory=new c(d),xa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Qo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=ly(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new vs(this.driver),FrameLocator:m,portSelector:Zo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:bb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Q(),t=1e3*60*2;try{await oe((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ie&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){oI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Pp={};H(Pp,{WorkerSelenium:()=>Cp});function cI(s){let{playback:e}=Q().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var Ca,aI,Cp,kp=w(()=>{"use strict";F();We();Vn();$();kt();ao();ne();fp();J();xp();Te();ot();Ca=A("worker-selenium"),aI=1e9,Cp=class extends Ot{initPlayer(t){return new Xn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new ws(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),U("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,aI),await this.windowUtils.validatePageIsAvailable(),U("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(Ca.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Gi(),initializedFromCache:Hi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Q(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Z.onWaitToTestComplete(this.id),cI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await Sn(this.options))[this.testId]);let d=async()=>oe(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ie&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Ca.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&&(Ca.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),U("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),U("right after super.runTestOnce in workerSelenium");let u=await d();return U("right after runSeleniumTest"),u}catch(u){throw Ca.error("failed to run test once",{err:u}),u}}}});var wb,vb,He,lI,uI,_p,vt,Pa=w(()=>{"use strict";wb=S(require("ora")),vb=S(require("jimp"));pe();Ge();ge();$();ne();Te();le();He=A("mobile-grid-service"),lI="https://tdc.tricentis-cloud.com",uI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.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===O.TESTIM_HEADSPIN?`${r||rc}/${nc}/devices`:t===O.TESTIM_TDC?`${r||sc}/${nc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Vs(`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===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Ml({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:I}=Q();y=I(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await vr(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=Q(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await vb.default.read(d),u=m.getWidth(),f=m.getHeight();return{scaleFactor:u/c.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,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ns}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?uI:lI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${Sd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,i,o,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(L.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ul({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await mn({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(vd*60))+1)*60*1e3,Math.max(wd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,wb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Nl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(g){let T=t.projectData.type,I=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});I&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!I&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!I&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===O.BROWSERSTACK){let u=`${Ns}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===O.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let u=`${c}/${ic}/apps`;return c||(u=`${l===O.TESTIM_HEADSPIN?rc:sc}/${ic}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===O.TESTIM_TVC){let u=`${Ed}/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(l===O.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await vc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,i)}},vt=new _p});function Sb({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"&&!pI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function dI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.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 mI(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 fI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&L.flags.enableBatchHeadSpin.isEnabled(),d=o&&(L.flags.enableBatchTDC.isEnabled()||L.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=L.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,...L.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:mI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function ka(s){return"id"in s?s.id:s.packageName}function gI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function hI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=gI(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":ka(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":ka(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Dr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i=""}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:ka(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:ka(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Eb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o}){let a=fI(o.type,i,n);return hI({projectType:s,sessionCaps:a,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Oa({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function La({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?oc:i.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":oc:".*")}function yI(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 bI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",..._a(s,As)}}function Ib(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function TI(s){return Ib(s,e=>e.startsWith("browserstack."),"browserstack.")}function wI(s){return Ib(s,e=>!e.startsWith("browserstack."))}function Rb(s){return!s||!Ab(s)?"2.0.0":s}function Ab(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function xb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=Ab(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function _a(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}function vI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=yI(i,s),h=Oa({osVersion:c,mobileConfig:m}),g=La({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),y=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch);if(u!==O.TESTIM_TVC&&l)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");let T={device:g,os_version:h,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":y,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Dr({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function SI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=L.flags.enableAppium2pCloudy.isEnabled(),g=Oa({osVersion:l,mobileConfig:d}),y=La({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),I={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...I,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Id),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=bI(b)),t="",Dr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:As}})}function EI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Oa({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Lr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],xb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},I={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Rb(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,..._a(h,As),"sauce:options":{...T,...I,...(0,Lr.omit)(g,"appiumVersion")}};return Dr({projectType:s,sessionCaps:b,appiumPrefix:As,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 Dr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Oa({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=TI(n.browserstack),g=(0,Lr.omit)(wI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:I}=n.browserstack||{},b=L.flags.enableAppium2BrowserStack.isEnabled();if(b||xb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":Rb(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},C={"appium:platformVersion":u,"appium:deviceName":f,..._a(g,As),"bstack:options":{...E,...(0,Lr.omit)(h,"appiumVersion")}};return Dr({projectType:s,sessionCaps:C,appiumPrefix:As,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:I||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,..._a(h,"browserstack.")};return Dr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function RI(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return Eb(s);if(O.TESTIM_TVC===s.gridInfo.type)return vI(s);if(O.P_CLOUDY===s.gridInfo.type)return SI(s);if(O.SAUCELABS===s.gridInfo.type)return EI(s);if(O.BROWSERSTACK===s.gridInfo.type)return II(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function AI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Cb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);Sb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=RI(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let y=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",T=AI(r,i==null?void 0:i.mobile);if(!(0,Lr.isEmpty)(T)){let I=Object.entries(T).map(([b,v])=>v.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=I}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l,d=L.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Op.default)("2m"),f=(0,Op.default)("12m"),h=fr(L.flags.appiumConnectionRetryCount.getValue(),m),g=fr(L.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function Pb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Sb({nativeAppMetadata:r,appPath:i,gridInfo:t}),dI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Eb({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function kb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Dr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function _b(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Op,Lr,As,pI,Lp=w(()=>{"use strict";Op=S(require("ms"));le();ne();Pa();Lr=require("lodash");F();pe();As="appium:",pI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var Da,Lb=w(()=>{"use strict";Da=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 Ma,Db=w(()=>{"use strict";F();Ma=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Ys;this.getLinksFromUnescapeHTML=Xs}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Dp,Na,Mb=w(()=>{"use strict";$();Dp=A("mobile-frame-locator-mock"),Na=class{foundFrameCallback(){return Dp.info("foundFrameCallback-mock invoked"),{}}locate(){return Dp.info("locate-mock invoked"),{}}async findFrame(){return Dp.info("findFrame-mock invoked"),{}}}});var xI,Ub,Nb,xs,Mp=w(()=>{"use strict";xI=S(require("webdriverio")),Ub=require("@applitools/eyes-sdk-core");Lb();wp();$();Db();vp();Te();Rp();Mb();Ap();Nb=A("appium-test-player"),xs=class{constructor(e,t,r,n=xI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Q(),m=new Ma(this.driver);this.stepActionFactory=new c(m),xa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Rs(ra()),this.sessionPlayer=new a(e,{tabService:new Da,cookieUtils:void 0,FrameLocator:Na,portSelector:Zo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Ub.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Nb.info("appium session deleted",{...i}))}catch(o){Nb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Q();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function CI(s){return await be(`${s}/api/status`)}async function Fb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function Bb(s){if((await CI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var jb=w(()=>{"use strict";Ge()});var $b={};H($b,{WorkerLocalTma:()=>Bp});var Mr,Np,Up,Fp,Bp,Wb=w(()=>{"use strict";Ge();Lp();Vn();F();$();kt();Mp();Te();jb();Pa();Mr=A("worker-appium"),Np=class extends Error{},Up=class extends Error{},Fp=class extends Error{},Bp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new xs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Q(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Z.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await Bb(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:C}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=C}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:I,version:b},v]=await Promise.all([this.getAppStateFromDevice(o,a,T),Fb(o,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(Mr.info("device status and app state",{deviceStatus:v,appInstalled:I,version:b,executionId:this.executionId,testResultId:this.testResultId}),!I&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!I&&y&&(await this.installApp(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let C={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=kb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),R={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:R,executionId:this.executionId,testResultId:this.testResultId});let N=await this.requestNewAppiumSessionFromTma(o,R,g);this.sessionData=N;let k=await m.attach({sessionId:N.sessionId,capabilities:D});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:k.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:k.capabilities})}catch(C){throw Mr.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Fp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await be(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Nt(n);await Ws(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Up(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Np(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Q(),{sessionPlayer:o}=r,a=n||"runner";Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var Gb={};H(Gb,{WorkerAppium:()=>jp});var Vb,Nr,jp,Hb=w(()=>{"use strict";F();Lp();Vb=require("linkedom");Vn();$();kt();Mp();Te();Pa();ne();ls();Nr=A("worker-appium"),jp=class extends Ot{initPlayer(t){return new xs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n,a=this.options.projectData.type,l=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m=(a==="android"||a==="ios")&&await t.isTestRecordedWithEnhancedMode(),u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:m},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),h=await Pb(f)):h=Cb(f),Nr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:d,capabilities:_b(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await o.remote(h),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,m);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Nr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Nr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Q(),n=async()=>{try{await t.getOrientation()}catch(i){Nr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&hg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Nr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===O.TESTIM_HEADSPIN||i===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:i,directConnectPath:o}=t;if(r&&n&&i&&o)return`${r}://${n}:${i}${o}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Q(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Z.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:I,port:b,path:v}=await vt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${I}:${b}${v}`}else d=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Vb.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((I,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:I,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 Nr.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 oe(u(),c)}catch(y){throw Nr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return`Testim/production:${ze()}`}}});var Ua,qb=w(()=>{"use strict";F();Un();J();Ua=class{constructor(e){this.id=e;this.driver=new Cr}async onDone(){try{await oe(this.driver.end(),12e4)}catch(t){t instanceof ie&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var zb,Fa,Kb=w(()=>{"use strict";zb=S(require("ws"));F();Fa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new zb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var ja,$p,Ba,Jb=w(()=>{"use strict";F();ja=S(require("chrome-launcher"));zu();Kb();hn();$p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Fa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Uo({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...ja.Launcher.defaultFlags().filter(I=>I!=="--disable-extensions")];this.chrome=await ja.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 hr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),rs(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},Ba=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new $p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Wp={};H(Wp,{WorkerExtension:()=>Qn});function PI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Yb(s){return PI(s)?s:new Error(s)}var pt,Qn,$a=w(()=>{"use strict";We();J();Vn();F();$();kt();ne();qb();Jb();ot();pt=A("worker-ext"),Qn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Ba(this.id):new Ua(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw pt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Gi(),initializedFromCache:Hi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Z.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;U("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await oe(e.runTestUsingCDP(d.cdpTestRunner),m,Fe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ie))throw u;return pt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw pt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(U("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw pt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Z.onWaitToTestStart(this.id);try{await oe(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ie))throw T;pt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),pt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=Hs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=oe(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),I=await yc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(E){pt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(pt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(pt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(T){throw pt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),Yb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw pt.warn("failed to start url",{err:h}),Yb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await c()}catch(d){throw pt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Gp={};H(Gp,{WorkerExtensionSingleBrowser:()=>Vp});var kI,_I,Vp,Hp=w(()=>{"use strict";We();F();$();lp();kt();$a();kI=A("base-worker"),_I=500,Vp=class extends Qn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await $n(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Z.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(kI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;U("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ce(_I)}}});var qp,Wa,Xb=w(()=>{"use strict";Un();pe();We();Fu();ot();Qu();J();$();ne();Kh();to();qp=A("worker-manager"),Wa=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Wb(),$b))).WorkerLocalTma:(await Promise.resolve().then(()=>(Hb(),Gb))).WorkerAppium;default:return Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>($a(),Wp))).WorkerExtension}else switch(r){case(Er.find(n=>n===r)&&Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser;case Er.find(n=>n===r):return(await Promise.resolve().then(()=>($a(),Wp))).WorkerExtension;case wn.find(n=>n===r):return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;default:throw new x(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return U("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{U("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var de,Lt,St,Ur,P,M,j,z;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Ho(r,n,e,i,o,t),this.combinedTestResults={};let T=((de=i.company)==null?void 0:de.ucid)||"",I=(Lt=i.company)==null?void 0:Lt.companyId,b=(St=i.company)==null?void 0:St.name,v=i.source||"cli",E=i.user,C=(Ur=i.company)==null?void 0:Ur.planType,D=(P=i.company)==null?void 0:P.isStartUp,R=(M=i.projectData)==null?void 0:M.name,N=(j=i.projectData)==null?void 0:j.type,k=i.lightweightMode,_=(z=i.gridData)==null?void 0:z.type,W=(Pe,Et,we,Ka,ei,Ja)=>(d++,kg({executionId:r,projectId:g,testId:Et,resultId:we,ucid:T,companyId:I,companyName:b,projectName:R,companyPlan:C,source:v,user:E,lightweightMode:k,isStartUp:D,projectType:N,appSource:Ja,gridType:_}),t.testStartAndReport(Pe,r,we,Ka,ei)),V=async(Pe,Et,we,Ka,ei,Ja)=>{var ed,td,rd;d--;let tt={...(k==null?void 0:k.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...i.host&&{gridHost:i.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),i.grid||i.gridId?(tt.gridName=i.grid||((ed=i.gridData)==null?void 0:ed.name),tt.gridType=(td=i.gridData)==null?void 0:td.type,tt.gridProvider=(rd=i.gridData)==null?void 0:rd.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(Pe,we,r,Ka,ei,tt).catch(AT=>qp.error("testEndAndReport threw an error",{err:AT})),ei)return;this.combinedTestResults[we.resultId]=we,_g({executionId:r,projectId:g,testId:Et,resultId:we.resultId,result:we,ucid:T,companyId:I,companyName:b,projectName:R,companyPlan:C,source:v,user:E,lightweightMode:k,logger:qp,isStartUp:D,projectType:N,appSource:Ja}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},Y=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},te=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:Wi(),authData:wr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:fe},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,W,V,te,Y)});try{let u=await xt(),f=await Vi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw qp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Zn,Va,zp,Ga,Qb=w(()=>{"use strict";Zn=S(require("lodash"));F();$();pe();ne();We();as();vu();Fu();ge();kt();Qg();J();Xb();to();({CLI_MODE:Va}=Ut),zp=A("test-plan-runner"),Ga=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Wa(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=di||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);U("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Og({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await f(),c}catch(g){if(zp.error("error running test plan",{err:g}),g instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,I,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Va.SELENIUM){let[{getSessionPlayer:v},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(Te(),er)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=v();await C.closeBatch(o,E);return}let g;try{if(!((b=(I=(T=i.company)==null?void 0:T.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(g=await kl(i.project),Zn.default.isEmpty(g)||!o))return;let{runKey:v,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,v,E;let c=se(),d=n.project;dc(c),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Mo(m,n,o,a),f=Zn.default.chain(m).map(C=>{var D;return((D=C.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);U("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Z.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),U("before runTestAllPhases");let I=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(c),U("after executionEnd"),{results:I,executionId:c,testPlanName:i,configName:h}}async runTestPlans(e,t){zp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Zn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a=await ml(o,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new x(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new x(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Va.APPIUM&&await Ql(e,r(c)),await ae(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await lg(e,d);let f=u.overrideExecutionName||d.name;return await ae(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Z.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Xl(n[m][E])})),I=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,C)=>Object.assign(E,C),{}),b=Xl(I);Object.assign(i,I);let v=b?T[0].executionId:T.find(E=>!E.status).executionId;return await ul(o,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;zp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await bf(e,t);if(U("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new x("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new x("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new x("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;U("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Va.APPIUM&&(a=await mn({appId:e.appId,projectId:e.project})),await ae(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Va.APPIUM&&await Ql(e,c),U("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return U("right after runTestPlan"),await Z.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Pn(),r=[];zs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Zn.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}}});var rT={};H(rT,{init:()=>eR,run:()=>JI});async function OI(s){let e=s.project,t=await gl(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),bn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Us}function LI(s,e){var i,o,a,l,c,d,m,u;let t=Ri(e.activePlan),r=s.parallel;if(t==="free"&&r>eT)throw new x(`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 f=(o=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:o.tunnel;if(s.tunnel&&!f)throw new x("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let h=(l=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!h&&(console.warn(`
410
- Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((c=s.gridData)==null?void 0:c.type)===O.TESTIM_TVC){let f=e.tvcLicense.expireAt||1;if(Date.now()>f&&!e.churnedByL2C)throw new x("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let h=Number(e.tvcLicense.maxParallel);if(r>h)throw new x(`Your license allows only ${h} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TDC){let f=e.tdcLicense.expireAt||1;if(Date.now()>f)throw new x("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 f=(u=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:u.resultRetention;if(n>f)throw new x(`Retention days (${n}) cannot be greater than the company's retention days (${f}). Run aborted`)}if(Jt(s)){if(L.flags.removeMobileTrialRestrictions.isEnabled())return;let f=e.tvcLicense,h=e.tdcLicense;if(f!=null&&f.isPaid||h!=null&&h.isPaid)return;let g=e==null?void 0:e.createdAt;if(new Date(g)<new Date(L.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let T=s.retries;T&&T>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function DI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await OI(s)}catch(t){if([x,Us].some(r=>t instanceof r))throw t;Kp.error("could not validate cli account",{err:t})}}function MI(s){let e=wr();return pf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function NI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(L.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Wo(),Fh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Vo(),$h));r.init(s)}}function UI(s,e){let{branch:t,autoDetect:r}=s;if(yg(e,r),!e&&!r)throw new x(`branch ${t} does not exist, run aborted.`)}async function FI(s,e){let{id:t,type:r}=e,i=tT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&L.flags.sfdcHybridCompany.isEnabled(),o=Pn();i&&(s.sfdcCredential=await ll({projectId:t,branch:o}))}function BI(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Ri(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<Zb?Zb:s.newBrowserWaitTimeout),L.setCompanyId(t),L.setIsPOC(i),L.setIsStartUp(o),L.setPlanType(a),Pt.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function jI(s,e){s.editorUrl=Ds||e.editorUrl}function $I(s,e){s.allGrids=e}function WI(s,e){s.authData=e}function VI(s,e){let{id:t,name:r,type:n,defaults:i}=e;L.setProjectId(t),L.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function GI(s){var e;s.gridData=await ug(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function HI(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}function qI(s,e){s.getBrowserRetries=["android","ios"].includes(e.type||"")?1:s.getBrowserRetries}async function zI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(yt("user-override-file",t),s.mockNetworkRules=await Qm(s.overrideMappingFile))}async function KI(s,e){U("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await Bf(),U("in runner.js after checkNpmVersion"),await DI(s),U("in runRunner before tunnel.connect"),await go(s),U("in runRunner after tunnel.connect");let a=await new Ga(e).run(s);return U("before tunnel.disconnect"),await ho(s),await QI(s.slotService,t,s.company.companyId),U("after tunnel.disconnect and gridService.keepAlive.end"),a}function YI(s){var e;Pt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
408
+ const downloadAndUploadFile = ${tI()};
409
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Xy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ba,Ta,eb=w(()=>{"use strict";ba=require("url");ue();Ta=class extends G{async updateBaseUrl(e){let t=new ba.URL(e),r=new ba.URL(this.context.recordedBaseUrl),n=new ba.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 wa,tb=w(()=>{"use strict";ue();F();wa=class extends G{async performAction(){await ce(this.step.durationMS||0)}}});var va,rb=w(()=>{"use strict";ue();va=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Jn,sb=w(()=>{"use strict";ue();Jn=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Sa,nb=w(()=>{"use strict";ue();Sa=class extends G{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var ib,Sp,Ep,ob=w(()=>{"use strict";ib=S(require("@applitools/spec-driver-webdriverio"));li();Te();Sp=class{constructor(){let{EyeSdkBuilder:e}=Q(),t=od["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:ib.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Q(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Ep=new Sp});var cb,ab,Yn,lb=w(()=>{"use strict";cb=S(require("lodash"));ue();$();ob();ab=A("pixel-validation-step-action"),Yn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Ep.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};cb.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),ab.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){ab.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ep.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Es,Ip=w(()=>{"use strict";hs();J();ca();Es=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:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ie?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var lr,ub=w(()=>{"use strict";Ip();lr=class extends Es{isFailedResult(e){return e===!1}}});var Ea,pb=w(()=>{"use strict";Ip();Ea=class extends Es{isFailedResult(e){return!e}}});var Ia,db=w(()=>{"use strict";hs();ue();J();Ia=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ie?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Or,mb=w(()=>{"use strict";ue();Or=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,fb=w(()=>{"use strict";ue();ye=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ra,gb=w(()=>{"use strict";ue();Ra=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Aa,hb=w(()=>{"use strict";ue();Aa=class extends G{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function rI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function xa(s,e){rI(sI,e),e.registerLocateStepActionUtils(Hn.getUtils(s))}var sI,Rp=w(()=>{"use strict";dy();gy();Iy();Ry();xy();ky();Ly();Dy();My();Ny();By();jy();$y();Gy();zy();Zy();eb();tb();rb();sb();nb();lb();ub();pb();db();mb();fb();gb();hb();sI={locate:Hn,scroll:sa,mouse:na,submit:da,text:oa,"special-key":la,"user-code":Gt,"validation-code-step":Gt,"wait-for-code-step":Gt,"action-code-step":Gt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":ia,"text-validation":zn,"wait-for-text-validation":zn,"select-option":pa,"drop-file":ga,"input-file":ya,hover:ma,navigation:Ta,wheel:fa,sleep:wa,refresh:va,"keyboard-shortcut-step":ua,"api-validation":Jn,"api-action":Jn,"api-code-step":Gt,"extract-text":Sa,"simple-ui-verification":Yn,"wait-for-simple-ui-verification":Yn,"cli-validation-download-file":Or,"cli-wait-for-download-file":Or,"network-validation-step":Or,"cli-validation-code-step":lr,"cli-wait-for-code-step":lr,"cli-action-code-step":lr,"cli-api-code-step":lr,"cli-condition-step":Ea,"node-package":Ia,"email-code-step":Gt,"cli-email-code-step":lr,"sfdc-internal-test-step":Aa,"sfdc-recorded-step":Ra,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":Or,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var yb,nI,Is,Ap=w(()=>{"use strict";yb=["simple-ui-verification","wait-for-simple-ui-verification"],nI=[...yb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Is=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=nI.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 yb.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 Tb={};H(Tb,{SeleniumTestPlayer:()=>Xn});var bb,iI,Xn,xp=w(()=>{"use strict";F();bb=require("@applitools/eyes-sdk-core");Un();J();$();hp();ay();wp();ta();uy();vp();Te();Rp();Ap();iI=A("SeleniumTestPlayer"),Xn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Is(ra());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Q();this.driver=n??new Cr;let d=new ea(this.driver);this.stepActionFactory=new c(d),xa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Qo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=ly(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:Zo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:bb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Q(),t=1e3*60*2;try{await oe((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ie&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){iI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Pp={};H(Pp,{WorkerSelenium:()=>Cp});function aI(s){let{playback:e}=Q().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var Ca,oI,Cp,kp=w(()=>{"use strict";F();We();Vn();$();kt();ao();ne();fp();J();xp();Te();ot();Ca=A("worker-selenium"),oI=1e9,Cp=class extends Ot{initPlayer(t){return new Xn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),U("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,oI),await this.windowUtils.validatePageIsAvailable(),U("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(Ca.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Gi(),initializedFromCache:Hi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Q(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Z.onWaitToTestComplete(this.id),aI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await vn(this.options))[this.testId]);let d=async()=>oe(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ie&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Ca.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&&(Ca.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),U("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),U("right after super.runTestOnce in workerSelenium");let u=await d();return U("right after runSeleniumTest"),u}catch(u){throw Ca.error("failed to run test once",{err:u}),u}}}});var wb,vb,He,cI,lI,_p,vt,Pa=w(()=>{"use strict";wb=S(require("ora")),vb=S(require("jimp"));pe();Ge();ge();$();ne();Te();le();He=A("mobile-grid-service"),cI="https://tdc.tricentis-cloud.com",lI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.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===O.TESTIM_HEADSPIN?`${r||rc}/${nc}/devices`:t===O.TESTIM_TDC?`${r||sc}/${nc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Ws(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Ml({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:I}=Q();y=I(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await vr(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=Q(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await vb.default.read(d),u=m.getWidth(),f=m.getHeight();return{scaleFactor:u/c.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,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ms}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?lI:cI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${Sd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,i,o,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(L.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ul({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await dn({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(vd*60))+1)*60*1e3,Math.max(wd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,wb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Nl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(g){let T=t.projectData.type,I=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});I&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!I&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!I&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===O.BROWSERSTACK){let u=`${Ms}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===O.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let u=`${c}/${ic}/apps`;return c||(u=`${l===O.TESTIM_HEADSPIN?rc:sc}/${ic}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===O.TESTIM_TVC){let u=`${Ed}/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(l===O.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await vc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,i)}},vt=new _p});function Sb({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"&&!uI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function pI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.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 dI(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 mI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&L.flags.enableBatchHeadSpin.isEnabled(),d=o&&(L.flags.enableBatchTDC.isEnabled()||L.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=L.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,...L.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:dI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function ka(s){return"id"in s?s.id:s.packageName}function fI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function gI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=fI(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":ka(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":ka(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Dr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i=""}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:ka(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:ka(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Eb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o}){let a=mI(o.type,i,n);return gI({projectType:s,sessionCaps:a,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Oa({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function La({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?oc:i.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":oc:".*")}function hI(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 yI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",..._a(s,Rs)}}function Ib(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 bI(s){return Ib(s,e=>e.startsWith("browserstack."),"browserstack.")}function TI(s){return Ib(s,e=>!e.startsWith("browserstack."))}function Rb(s){return!s||!Ab(s)?"2.0.0":s}function Ab(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function xb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=Ab(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function _a(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}function wI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=hI(i,s),h=Oa({osVersion:c,mobileConfig:m}),g=La({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),y=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch);if(u!==O.TESTIM_TVC&&l)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");let T={device:g,os_version:h,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":y,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Dr({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function vI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=L.flags.enableAppium2pCloudy.isEnabled(),g=Oa({osVersion:l,mobileConfig:d}),y=La({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),I={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...I,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Id),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=yI(b)),t="",Dr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Rs}})}function SI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Oa({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Lr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],xb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},I={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Rb(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,..._a(h,Rs),"sauce:options":{...T,...I,...(0,Lr.omit)(g,"appiumVersion")}};return Dr({projectType:s,sessionCaps:b,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Dr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function EI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Oa({osVersion:l,mobileConfig:d}),f=La({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=bI(n.browserstack),g=(0,Lr.omit)(TI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:I}=n.browserstack||{},b=L.flags.enableAppium2BrowserStack.isEnabled();if(b||xb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":Rb(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},C={"appium:platformVersion":u,"appium:deviceName":f,..._a(g,Rs),"bstack:options":{...E,...(0,Lr.omit)(h,"appiumVersion")}};return Dr({projectType:s,sessionCaps:C,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:I||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,..._a(h,"browserstack.")};return Dr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function II(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return Eb(s);if(O.TESTIM_TVC===s.gridInfo.type)return wI(s);if(O.P_CLOUDY===s.gridInfo.type)return vI(s);if(O.SAUCELABS===s.gridInfo.type)return SI(s);if(O.BROWSERSTACK===s.gridInfo.type)return EI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function RI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Cb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);Sb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=II(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let y=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",T=RI(r,i==null?void 0:i.mobile);if(!(0,Lr.isEmpty)(T)){let I=Object.entries(T).map(([b,v])=>v.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=I}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l,d=L.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Op.default)("2m"),f=(0,Op.default)("12m"),h=fr(L.flags.appiumConnectionRetryCount.getValue(),m),g=fr(L.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function Pb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Sb({nativeAppMetadata:r,appPath:i,gridInfo:t}),pI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Eb({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function kb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Dr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function _b(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Op,Lr,Rs,uI,Lp=w(()=>{"use strict";Op=S(require("ms"));le();ne();Pa();Lr=require("lodash");F();pe();Rs="appium:",uI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var Da,Lb=w(()=>{"use strict";Da=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 Ma,Db=w(()=>{"use strict";F();Ma=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Js;this.getLinksFromUnescapeHTML=Ys}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Dp,Na,Mb=w(()=>{"use strict";$();Dp=A("mobile-frame-locator-mock"),Na=class{foundFrameCallback(){return Dp.info("foundFrameCallback-mock invoked"),{}}locate(){return Dp.info("locate-mock invoked"),{}}async findFrame(){return Dp.info("findFrame-mock invoked"),{}}}});var AI,Ub,Nb,As,Mp=w(()=>{"use strict";AI=S(require("webdriverio")),Ub=require("@applitools/eyes-sdk-core");Lb();wp();$();Db();vp();Te();Rp();Mb();Ap();Nb=A("appium-test-player"),As=class{constructor(e,t,r,n=AI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Q(),m=new Ma(this.driver);this.stepActionFactory=new c(m),xa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Is(ra()),this.sessionPlayer=new a(e,{tabService:new Da,cookieUtils:void 0,FrameLocator:Na,portSelector:Zo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Ub.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Nb.info("appium session deleted",{...i}))}catch(o){Nb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Q();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function xI(s){return await be(`${s}/api/status`)}async function Fb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function Bb(s){if((await xI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var jb=w(()=>{"use strict";Ge()});var $b={};H($b,{WorkerLocalTma:()=>Bp});var Mr,Np,Up,Fp,Bp,Wb=w(()=>{"use strict";Ge();Lp();Vn();F();$();kt();Mp();Te();jb();Pa();Mr=A("worker-appium"),Np=class extends Error{},Up=class extends Error{},Fp=class extends Error{},Bp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new As(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Q(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Z.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await Bb(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:C}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=C}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:I,version:b},v]=await Promise.all([this.getAppStateFromDevice(o,a,T),Fb(o,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(Mr.info("device status and app state",{deviceStatus:v,appInstalled:I,version:b,executionId:this.executionId,testResultId:this.testResultId}),!I&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!I&&y&&(await this.installApp(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let C={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=kb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),R={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:R,executionId:this.executionId,testResultId:this.testResultId});let N=await this.requestNewAppiumSessionFromTma(o,R,g);this.sessionData=N;let k=await m.attach({sessionId:N.sessionId,capabilities:D});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:k.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:k.capabilities})}catch(C){throw Mr.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Fp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await be(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Nt(n);await $s(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Up(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Np(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Q(),{sessionPlayer:o}=r,a=n||"runner";Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var Gb={};H(Gb,{WorkerAppium:()=>jp});var Vb,Nr,jp,Hb=w(()=>{"use strict";F();Lp();Vb=require("linkedom");Vn();$();kt();Mp();Te();Pa();ne();cs();Nr=A("worker-appium"),jp=class extends Ot{initPlayer(t){return new As(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n,a=this.options.projectData.type,l=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m=(a==="android"||a==="ios")&&await t.isTestRecordedWithEnhancedMode(),u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:m},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),h=await Pb(f)):h=Cb(f),Nr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:d,capabilities:_b(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await o.remote(h),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,m);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Nr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Nr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Q(),n=async()=>{try{await t.getOrientation()}catch(i){Nr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&hg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Nr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===O.TESTIM_HEADSPIN||i===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:i,directConnectPath:o}=t;if(r&&n&&i&&o)return`${r}://${n}:${i}${o}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Q(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Z.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:I,port:b,path:v}=await vt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${I}:${b}${v}`}else d=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Vb.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((I,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:I,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 Nr.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 oe(u(),c)}catch(y){throw Nr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return`Testim/production:${ze()}`}}});var Ua,qb=w(()=>{"use strict";F();Un();J();Ua=class{constructor(e){this.id=e;this.driver=new Cr}async onDone(){try{await oe(this.driver.end(),12e4)}catch(t){t instanceof ie&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var zb,Fa,Kb=w(()=>{"use strict";zb=S(require("ws"));F();Fa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new zb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var ja,$p,Ba,Jb=w(()=>{"use strict";F();ja=S(require("chrome-launcher"));zu();Kb();gn();$p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Fa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Uo({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...ja.Launcher.defaultFlags().filter(I=>I!=="--disable-extensions")];this.chrome=await ja.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 hr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),rs(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},Ba=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new $p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Wp={};H(Wp,{WorkerExtension:()=>Qn});function CI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Yb(s){return CI(s)?s:new Error(s)}var pt,Qn,$a=w(()=>{"use strict";We();J();Vn();F();$();kt();ne();qb();Jb();ot();pt=A("worker-ext"),Qn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Ba(this.id):new Ua(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw pt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Gi(),initializedFromCache:Hi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Z.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;U("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await oe(e.runTestUsingCDP(d.cdpTestRunner),m,Fe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ie))throw u;return pt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw pt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(U("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw pt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Z.onWaitToTestStart(this.id);try{await oe(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ie))throw T;pt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),pt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=Gs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=oe(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),I=await yc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(E){pt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(pt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(pt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(T){throw pt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),Yb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw pt.warn("failed to start url",{err:h}),Yb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await c()}catch(d){throw pt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Gp={};H(Gp,{WorkerExtensionSingleBrowser:()=>Vp});var PI,kI,Vp,Hp=w(()=>{"use strict";We();F();$();lp();kt();$a();PI=A("base-worker"),kI=500,Vp=class extends Qn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await $n(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Z.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(PI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;U("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ce(kI)}}});var qp,Wa,Xb=w(()=>{"use strict";Un();pe();We();Fu();ot();Qu();J();$();ne();Kh();to();qp=A("worker-manager"),Wa=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Wb(),$b))).WorkerLocalTma:(await Promise.resolve().then(()=>(Hb(),Gb))).WorkerAppium;default:return Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>($a(),Wp))).WorkerExtension}else switch(r){case(Er.find(n=>n===r)&&Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser;case Er.find(n=>n===r):return(await Promise.resolve().then(()=>($a(),Wp))).WorkerExtension;case Tn.find(n=>n===r):return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;default:throw new x(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return U("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{U("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var de,Lt,St,Ur,P,M,j,z;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Ho(r,n,e,i,o,t),this.combinedTestResults={};let T=((de=i.company)==null?void 0:de.ucid)||"",I=(Lt=i.company)==null?void 0:Lt.companyId,b=(St=i.company)==null?void 0:St.name,v=i.source||"cli",E=i.user,C=(Ur=i.company)==null?void 0:Ur.planType,D=(P=i.company)==null?void 0:P.isStartUp,R=(M=i.projectData)==null?void 0:M.name,N=(j=i.projectData)==null?void 0:j.type,k=i.lightweightMode,_=(z=i.gridData)==null?void 0:z.type,W=(Pe,Et,we,Ka,ei,Ja)=>(d++,kg({executionId:r,projectId:g,testId:Et,resultId:we,ucid:T,companyId:I,companyName:b,projectName:R,companyPlan:C,source:v,user:E,lightweightMode:k,isStartUp:D,projectType:N,appSource:Ja,gridType:_}),t.testStartAndReport(Pe,r,we,Ka,ei)),V=async(Pe,Et,we,Ka,ei,Ja)=>{var ed,td,rd;d--;let tt={...(k==null?void 0:k.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...i.host&&{gridHost:i.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),i.grid||i.gridId?(tt.gridName=i.grid||((ed=i.gridData)==null?void 0:ed.name),tt.gridType=(td=i.gridData)==null?void 0:td.type,tt.gridProvider=(rd=i.gridData)==null?void 0:rd.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(Pe,we,r,Ka,ei,tt).catch(AT=>qp.error("testEndAndReport threw an error",{err:AT})),ei)return;this.combinedTestResults[we.resultId]=we,_g({executionId:r,projectId:g,testId:Et,resultId:we.resultId,result:we,ucid:T,companyId:I,companyName:b,projectName:R,companyPlan:C,source:v,user:E,lightweightMode:k,logger:qp,isStartUp:D,projectType:N,appSource:Ja}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},Y=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},te=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:Wi(),authData:wr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:fe},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,W,V,te,Y)});try{let u=await xt(),f=await Vi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw qp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Zn,Va,zp,Ga,Qb=w(()=>{"use strict";Zn=S(require("lodash"));F();$();pe();ne();We();os();vu();Fu();ge();kt();Qg();J();Xb();to();({CLI_MODE:Va}=Ut),zp=A("test-plan-runner"),Ga=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Wa(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=di||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);U("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Og({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await f(),c}catch(g){if(zp.error("error running test plan",{err:g}),g instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,I,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Va.SELENIUM){let[{getSessionPlayer:v},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(Te(),er)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=v();await C.closeBatch(o,E);return}let g;try{if(!((b=(I=(T=i.company)==null?void 0:T.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(g=await kl(i.project),Zn.default.isEmpty(g)||!o))return;let{runKey:v,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,v,E;let c=se(),d=n.project;dc(c),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Mo(m,n,o,a),f=Zn.default.chain(m).map(C=>{var D;return((D=C.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);U("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Z.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),U("before runTestAllPhases");let I=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(c),U("after executionEnd"),{results:I,executionId:c,testPlanName:i,configName:h}}async runTestPlans(e,t){zp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Zn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a=await ml(o,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new x(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new x(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Va.APPIUM&&await Ql(e,r(c)),await ae(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await lg(e,d);let f=u.overrideExecutionName||d.name;return await ae(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Z.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Xl(n[m][E])})),I=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,C)=>Object.assign(E,C),{}),b=Xl(I);Object.assign(i,I);let v=b?T[0].executionId:T.find(E=>!E.status).executionId;return await ul(o,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;zp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await bf(e,t);if(U("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new x("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new x("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new x("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;U("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Va.APPIUM&&(a=await dn({appId:e.appId,projectId:e.project})),await ae(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Va.APPIUM&&await Ql(e,c),U("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return U("right after runTestPlan"),await Z.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Pn(),r=[];qs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Zn.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}}});var rT={};H(rT,{init:()=>ZI,run:()=>KI});async function _I(s){let e=s.project,t=await gl(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),yn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ns}function OI(s,e){var i,o,a,l,c,d,m,u;let t=Ri(e.activePlan),r=s.parallel;if(t==="free"&&r>eT)throw new x(`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 f=(o=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:o.tunnel;if(s.tunnel&&!f)throw new x("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let h=(l=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!h&&(console.warn(`
410
+ Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((c=s.gridData)==null?void 0:c.type)===O.TESTIM_TVC){let f=e.tvcLicense.expireAt||1;if(Date.now()>f&&!e.churnedByL2C)throw new x("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let h=Number(e.tvcLicense.maxParallel);if(r>h)throw new x(`Your license allows only ${h} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TDC){let f=e.tdcLicense.expireAt||1;if(Date.now()>f)throw new x("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 f=(u=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:u.resultRetention;if(n>f)throw new x(`Retention days (${n}) cannot be greater than the company's retention days (${f}). Run aborted`)}if(Jt(s)){if(L.flags.removeMobileTrialRestrictions.isEnabled())return;let f=e.tvcLicense,h=e.tdcLicense;if(f!=null&&f.isPaid||h!=null&&h.isPaid)return;let g=e==null?void 0:e.createdAt;if(new Date(g)<new Date(L.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let T=s.retries;T&&T>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function LI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await _I(s)}catch(t){if([x,Ns].some(r=>t instanceof r))throw t;Kp.error("could not validate cli account",{err:t})}}function DI(s){let e=wr();return pf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function MI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(L.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Wo(),Fh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Vo(),$h));r.init(s)}}function NI(s,e){let{branch:t,autoDetect:r}=s;if(yg(e,r),!e&&!r)throw new x(`branch ${t} does not exist, run aborted.`)}async function UI(s,e){let{id:t,type:r}=e,i=tT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&L.flags.sfdcHybridCompany.isEnabled(),o=Pn();i&&(s.sfdcCredential=await ll({projectId:t,branch:o}))}function FI(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Ri(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<Zb?Zb:s.newBrowserWaitTimeout),L.setCompanyId(t),L.setIsPOC(i),L.setIsStartUp(o),L.setPlanType(a),Pt.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function BI(s,e){s.editorUrl=Ls||e.editorUrl}function jI(s,e){s.allGrids=e}function $I(s,e){s.authData=e}function WI(s,e){let{id:t,name:r,type:n,defaults:i}=e;L.setProjectId(t),L.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function VI(s){var e;s.gridData=await ug(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function GI(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}function HI(s,e){s.getBrowserRetries=["android","ios"].includes(e.type||"")?1:s.getBrowserRetries}async function qI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(yt("user-override-file",t),s.mockNetworkRules=await Qm(s.overrideMappingFile))}async function zI(s,e){U("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await Bf(),U("in runner.js after checkNpmVersion"),await LI(s),U("in runRunner before tunnel.connect"),await go(s),U("in runRunner after tunnel.connect");let a=await new Ga(e).run(s);return U("before tunnel.disconnect"),await ho(s),await XI(s.slotService,t,s.company.companyId),U("after tunnel.disconnect and gridService.keepAlive.end"),a}function JI(s){var e;Pt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
411
411
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
412
412
  If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
413
- `)}function XI(s,e,t){s==="redis"&&xn.start(t,e),s==="mongo"&&Rn.start(e)}async function QI(s,e,t){s==="redis"&&await xn.end(t,e),s==="mongo"&&await Rn.end(e)}function ZI(s,e){var i,o,a,l,c,d;let t=L.flags.redisSlotManager.isEnabled(),r=((i=s.projectData)==null?void 0:i.type)==="ios"||((o=s.projectData)==null?void 0:o.type)==="android",n=t&&r;if(e.followL2CPlan){let m=(l=(a=e.l2cLicense)==null?void 0:a.shadowCatalogId)==null?void 0:l.includes("testim_mobile"),u=!!((c=e.tvcLicense)!=null&&c.maxParallel);n&&u&&m&&(s.slotService="redis")}!e.followL2CPlan&&n&&((d=e.mobile)!=null&&d.maxParallel)&&(s.slotService="redis")}async function eR(s){var h,g,y,T;U("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=NI(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===q.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await fn(s);if(c.disabled)throw new x("The company is disabled.");if(d.disabled)throw new x("The project is disabled.");if(s.printGrids){let I=u.sort((b,v)=>b.type.localeCompare(v.type));console.table(I.reduce((b,v)=>{class E{constructor(R,N){this.Type=R,this.Browsers=N}}let C=Object.entries(v.browsers||{"N/A":""}).map(D=>D.join(":")).join(", ");return b[v.name]=new E(v.type,C),b},{})),process.exit(0)}if(await o,U("after featureFlagsReady and socketConnected"),jI(s,l),BI(s,c),VI(s,d),HI(s,d),qI(s,d),UI(s,m),$I(s,u),WI(s,a),await FI(s,d),await GI(s),LI(s,c),ZI(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[of(s)]),L.flags.clearRunnerFileCache.isEnabled())try{await Yr(),Kp.info("runner file cache cleared")}catch(I){Kp.error("failed to clear runner file cache",{err:I})}(g=s.lightweightMode)!=null&&g.disableLabs||await Fn.loadLabFeatures(d.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(L.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.type)==="turboMode"&&console.log(`
414
- 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`),XI(s.slotService,e,c.id),MI(e),await zI(s),YI(s);let f=Pn();await Z.setOptions(s,f)}var tT,Zb,eT,Kp,JI,sT=w(()=>{"use strict";tT=S(require("lodash"));F();du();bu();We();as();ls();ss();vu();ge();ot();Bt();$();kt();pe();ne();J();Qb();jo();Qu();le();_n();Hl();yn();Zb=30*60*1e3,eT=1,Kp=A("runner");JI=KI});function nT(s){s.get("/",(e,t)=>{let r=Jp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:pu()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());su({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var iT=w(()=>{"use strict";io();Yp();du()});var Xp,oT,Cs,Ha,aT=w(()=>{"use strict";Xp=S(require("chalk"));ys();oT=require("express");$();J();Cs=A("cli-router"),Ha=(0,oT.Router)();Ha.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await hs(t,r,n,i,o,a,l,c,d);u.success||(console.log(Xp.default.red(u.result.resultValue)),Cs.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Cs.error("failed to run cli code",{err:u,...m}),console.log(Xp.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Ha.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 l={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let c=await gs(t,r,n,i,o,a);Cs.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof Rt){Cs.error("failed to install node packages",{err:c,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof ie){Cs.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}Cs.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var cT=w(()=>{"use strict";aT()});var dT={};H(dT,{orchestrateRoutes:()=>tR});function tR(s){let e=(0,uT.default)();s(e),e.use(Qp.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,pT.default)()),e.use(Qp.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Oe||ld?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,lT.default)(r)),nT(e),e.use("/cliJs",Ha),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var lT,uT,Qp,pT,mT=w(()=>{"use strict";lT=S(require("cors")),uT=S(require("express")),Qp=S(require("body-parser")),pT=S(require("compression"));iT();cT();pe()});var gT={};H(gT,{init:()=>rR});async function rR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(mT(),dT));return new Promise((i,o)=>{let a=()=>{};t&&(jm(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let l=n(a),c=fT.createServer(l);c.listen(s,e),c.on("error",d),c.on("listening",m);function d(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new x(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function m(){let{port:u}=c.address();console.log(`Running on port: ${u}`),sR()}})}async function sR(){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,hT=w(()=>{"use strict";fT=S(require("http"));ot();J()});var ET={};H(ET,{getStartedWithStart:()=>Jp,runAgentMode:()=>aR});async function aR(s){var r;let e;if(await br(s.playerLocation,s.canary),s.startTestimBrowser){await uR();try{e=await lR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new x('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(hT(),gT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(xp(),Ue(Tb)))},6e3),t.init(s)}function Jp(){return vT}function yT(s){try{return process.kill(s,0)}catch{return!1}}async function cR(s,e,t){let r=ur.join(Ft,`chrome-${nn}-process`),n=3e3,i=()=>{Ce.rmSync(r,{recursive:!0}),console.log(`
413
+ `)}function YI(s,e,t){s==="redis"&&xn.start(t,e),s==="mongo"&&Rn.start(e)}async function XI(s,e,t){s==="redis"&&await xn.end(t,e),s==="mongo"&&await Rn.end(e)}function QI(s,e){var i,o,a,l,c,d;let t=L.flags.redisSlotManager.isEnabled(),r=((i=s.projectData)==null?void 0:i.type)==="ios"||((o=s.projectData)==null?void 0:o.type)==="android",n=t&&r;if(e.followL2CPlan){let m=(l=(a=e.l2cLicense)==null?void 0:a.shadowCatalogId)==null?void 0:l.includes("testim_mobile"),u=!!((c=e.tvcLicense)!=null&&c.maxParallel);n&&u&&m&&(s.slotService="redis")}!e.followL2CPlan&&n&&((d=e.mobile)!=null&&d.maxParallel)&&(s.slotService="redis")}async function ZI(s){var h,g,y,T;U("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=MI(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===q.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await mn(s);if(c.disabled)throw new x("The company is disabled.");if(d.disabled)throw new x("The project is disabled.");if(s.printGrids){let I=u.sort((b,v)=>b.type.localeCompare(v.type));console.table(I.reduce((b,v)=>{class E{constructor(R,N){this.Type=R,this.Browsers=N}}let C=Object.entries(v.browsers||{"N/A":""}).map(D=>D.join(":")).join(", ");return b[v.name]=new E(v.type,C),b},{})),process.exit(0)}if(await o,U("after featureFlagsReady and socketConnected"),BI(s,l),FI(s,c),WI(s,d),GI(s,d),HI(s,d),NI(s,m),jI(s,u),$I(s,a),await UI(s,d),await VI(s),OI(s,c),QI(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[of(s)]),L.flags.clearRunnerFileCache.isEnabled())try{await Yr(),Kp.info("runner file cache cleared")}catch(I){Kp.error("failed to clear runner file cache",{err:I})}(g=s.lightweightMode)!=null&&g.disableLabs||await Fn.loadLabFeatures(d.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(L.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.type)==="turboMode"&&console.log(`
414
+ 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`),YI(s.slotService,e,c.id),DI(e),await qI(s),JI(s);let f=Pn();await Z.setOptions(s,f)}var tT,Zb,eT,Kp,KI,sT=w(()=>{"use strict";tT=S(require("lodash"));F();du();bu();We();os();cs();ss();vu();ge();ot();Bt();$();kt();pe();ne();J();Qb();jo();Qu();le();_n();Hl();hn();Zb=30*60*1e3,eT=1,Kp=A("runner");KI=zI});function nT(s){s.get("/",(e,t)=>{let r=Jp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:pu()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());su({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var iT=w(()=>{"use strict";io();Yp();du()});var Xp,oT,xs,Ha,aT=w(()=>{"use strict";Xp=S(require("chalk"));hs();oT=require("express");$();J();xs=A("cli-router"),Ha=(0,oT.Router)();Ha.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:o,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await gs(t,r,n,i,o,a,l,c,d);u.success||(console.log(Xp.default.red(u.result.resultValue)),xs.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){xs.error("failed to run cli code",{err:u,...m}),console.log(Xp.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Ha.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 l={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let c=await fs(t,r,n,i,o,a);xs.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof Rt){xs.error("failed to install node packages",{err:c,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof ie){xs.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}xs.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var cT=w(()=>{"use strict";aT()});var dT={};H(dT,{orchestrateRoutes:()=>eR});function eR(s){let e=(0,uT.default)();s(e),e.use(Qp.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,pT.default)()),e.use(Qp.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Oe||ld?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,lT.default)(r)),nT(e),e.use("/cliJs",Ha),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var lT,uT,Qp,pT,mT=w(()=>{"use strict";lT=S(require("cors")),uT=S(require("express")),Qp=S(require("body-parser")),pT=S(require("compression"));iT();cT();pe()});var gT={};H(gT,{init:()=>tR});async function tR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(mT(),dT));return new Promise((i,o)=>{let a=()=>{};t&&(jm(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let l=n(a),c=fT.createServer(l);c.listen(s,e),c.on("error",d),c.on("listening",m);function d(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new x(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function m(){let{port:u}=c.address();console.log(`Running on port: ${u}`),rR()}})}async function rR(){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,hT=w(()=>{"use strict";fT=S(require("http"));ot();J()});var ET={};H(ET,{getStartedWithStart:()=>Jp,runAgentMode:()=>oR});async function oR(s){var r;let e;if(await br(s.playerLocation,s.canary),s.startTestimBrowser){await lR();try{e=await cR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new x('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(hT(),gT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(xp(),Ue(Tb)))},6e3),t.init(s)}function Jp(){return vT}function yT(s){try{return process.kill(s,0)}catch{return!1}}async function aR(s,e,t){let r=ur.join(Ft,`chrome-${sn}-process`),n=3e3,i=()=>{Ce.rmSync(r,{recursive:!0}),console.log(`
415
415
 
416
- Browser session ended`),process.exit(0)};if(await he(r)){let f=JSON.parse(Ce.readFileSync(r));if(yT(f.pid)){let h=()=>yT(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await $i();await he(Ps)||await Ce.promises.mkdir(Ps,{recursive:!0});let l=[...ST(Ps,e,t,o).desiredCapabilities.chromeOptions.args,...za.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await za.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Ps,chromePath:o,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await hr(`localhost:${m.port}`)};return Ce.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",i),m.process.once("close",i),{webdriverApi:u}}async function lR(s){let e=`${bd}/extension/testim-full-master.zip`,t=ur.basename(e),r=ur.join(Ft,t),n=ur.join(Ft,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await he(r)){let f=await Ce.promises.stat(r);i=Date.now()-iR>f.mtimeMs}if(await Ce.promises.mkdir(Ft,{recursive:!0}),i){let f=(0,TT.default)("Downloading Testim Editor").start();await Ye(e,r);try{await nt(r,n)}catch{await Ce.promises.rm(r,{recursive:!0,force:!0}),await Ye(e,r);try{await nt(r,n)}catch{throw await Ce.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 Ce.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Ce.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await cR(s,o,n);await en({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=ST(Ps,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Un(),Ue(wh)),{SeleniumPerfStats:c}=(ps(),Ue(qg)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);vT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await hr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function ST(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&i.push(`--load-extension=${t}`),{logLevel:nR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function uR(){if(await he(qa))try{let{webSocketDebuggerUrl:s}=await pR();await dR(s),await Ce.promises.unlink(qa)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Ce.promises.unlink(qa)}}async function pR(){let s=await Ce.promises.readFile(qa,{encoding:"utf8"}),[e,t]=s.split(`
417
- `).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 hr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function dR(s,e=100){let t=await mR(s,e);return Kt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function mR(s,e=100){let t=new wT.default(s,{timeout:e}),r=Kt(i=>{t.once("open",i)}).then(()=>{t.removeAllListeners()}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var bT,TT,wT,Ce,ur,za,nR,iR,Ps,oR,qa,vT,Yp=w(()=>{"use strict";bT=S(require("ms")),TT=S(require("ora")),wT=S(require("ws")),Ce=S(require("fs")),ur=S(require("path")),za=S(require("chrome-launcher"));pe();rn();J();el();F();nR=pi?"verbose":"silent",iR=(0,bT.default)("1h"),Ps=ur.join(Ft,"profile"),oR="DevToolsActivePort",qa=ur.join(Ps,oR);vT=!1});var zD=require("source-map-support/register");var ci=S(require("os")),_s=S(require("url")),Os=S(require("http")),Ya=S(require("https")),ri=S(require("form-data")),si=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)}},ni=class extends si{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 ri.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()}},ks=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}},ii=class extends Error{},oi=class extends Error{},ai=class extends Error{},pr=class extends Error{},Ee=class extends si{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Os.globalAgent;this.nodejsHttpsAgent=Ya.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 (${ci.type()} ${ci.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ee.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new ni(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){Ee.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 ii("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new ai(`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(Ee.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!==Ee.OPENED)throw new pr("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!==Ee.OPENED)throw new pr("XHR readyState must be OPENED");if(this._request)throw new pr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new oi(`Unsupported protocol ${this._url.protocol}`)}}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
418
- `):""}overrideMimeType(t){if([Ee.LOADING,Ee.DONE].includes(this.readyState))throw new pr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new ks("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new oi("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:"?Os:Ya).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 ri.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 ri.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=Os.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(Ee.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ee.LOADING&&this._setReadyState(Ee.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ee.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(Ee.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ee.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ee.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new ks(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,i,o=this.nodejsBaseUrl===null?t:_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"}},ke=Ee;ke.SyntaxError=ii,ke.ProgressEvent=ks,ke.SecurityError=ai,ke.XMLHttpRequest=Ee,ke.InvalidStateError=pr,ke.XMLHttpRequestUpload=ni,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke});var IT=S(require("semver"));We();Hl();Bt();rn();var Zp=S(require("chalk")),RT=require("events");ne();hn();J();ne();qi();$();var tf=S(require("os")),ql=S(require("path")),zl=S(require("chalk")),Zi=require("fs");pe();function rf(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=tf.homedir();(0,Zi.mkdirSync)(ql.resolve(n,".testim_logs"),{recursive:!0});let i=ql.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}`),fd&&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(zl.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(zl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Zi.writeFileSync)(i,`${s}
416
+ Browser session ended`),process.exit(0)};if(await he(r)){let f=JSON.parse(Ce.readFileSync(r));if(yT(f.pid)){let h=()=>yT(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await $i();await he(Cs)||await Ce.promises.mkdir(Cs,{recursive:!0});let l=[...ST(Cs,e,t,o).desiredCapabilities.chromeOptions.args,...za.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await za.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Cs,chromePath:o,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await hr(`localhost:${m.port}`)};return Ce.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",i),m.process.once("close",i),{webdriverApi:u}}async function cR(s){let e=`${bd}/extension/testim-full-master.zip`,t=ur.basename(e),r=ur.join(Ft,t),n=ur.join(Ft,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await he(r)){let f=await Ce.promises.stat(r);i=Date.now()-nR>f.mtimeMs}if(await Ce.promises.mkdir(Ft,{recursive:!0}),i){let f=(0,TT.default)("Downloading Testim Editor").start();await Ye(e,r);try{await nt(r,n)}catch{await Ce.promises.rm(r,{recursive:!0,force:!0}),await Ye(e,r);try{await nt(r,n)}catch{throw await Ce.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 Ce.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Ce.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await aR(s,o,n);await Zs({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=ST(Cs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Un(),Ue(wh)),{SeleniumPerfStats:c}=(us(),Ue(qg)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);vT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await hr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function ST(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&i.push(`--load-extension=${t}`),{logLevel:sR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function lR(){if(await he(qa))try{let{webSocketDebuggerUrl:s}=await uR();await pR(s),await Ce.promises.unlink(qa)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Ce.promises.unlink(qa)}}async function uR(){let s=await Ce.promises.readFile(qa,{encoding:"utf8"}),[e,t]=s.split(`
417
+ `).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 hr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function pR(s,e=100){let t=await dR(s,e);return Kt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function dR(s,e=100){let t=new wT.default(s,{timeout:e}),r=Kt(i=>{t.once("open",i)}).then(()=>{t.removeAllListeners()}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var bT,TT,wT,Ce,ur,za,sR,nR,Cs,iR,qa,vT,Yp=w(()=>{"use strict";bT=S(require("ms")),TT=S(require("ora")),wT=S(require("ws")),Ce=S(require("fs")),ur=S(require("path")),za=S(require("chrome-launcher"));pe();tn();J();el();F();sR=pi?"verbose":"silent",nR=(0,bT.default)("1h"),Cs=ur.join(Ft,"profile"),iR="DevToolsActivePort",qa=ur.join(Cs,iR);vT=!1});var qD=require("source-map-support/register");var ci=S(require("os")),ks=S(require("url")),_s=S(require("http")),Ya=S(require("https")),ri=S(require("form-data")),si=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)}},ni=class extends si{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 ri.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()}},Ps=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}},ii=class extends Error{},oi=class extends Error{},ai=class extends Error{},pr=class extends Error{},Ee=class extends si{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=_s.globalAgent;this.nodejsHttpsAgent=Ya.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 (${ci.type()} ${ci.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Ee.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new ni(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){Ee.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&&!ks.parse(r,!1,!0).protocol)throw new ii("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new ai(`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(Ee.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!==Ee.OPENED)throw new pr("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!==Ee.OPENED)throw new pr("XHR readyState must be OPENED");if(this._request)throw new pr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new oi(`Unsupported protocol ${this._url.protocol}`)}}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
418
+ `):""}overrideMimeType(t){if([Ee.LOADING,Ee.DONE].includes(this.readyState))throw new pr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new Ps("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new oi("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,i=(this._url.protocol==="http:"?_s:Ya).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 ri.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 ri.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",i=>this._onHttpResponseData(r,i)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=_s.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ee.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ee.LOADING&&this._setReadyState(Ee.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ee.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(Ee.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ee.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ee.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new Ps(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:ks.resolve(this.nodejsBaseUrl,t),a=ks.parse(o,!1,!0);return a.hash=null,a.auth&&(i!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?i||(i=a.auth):(i||(i=a.substring(0,r)),n||(n=a.substring(r+1)))),(i||n)&&(a.auth=`${i}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let i=r.toLowerCase();this._privateHeaders[i]||(this._mimeOverride!==null&&i==="content-type"&&(n=this._mimeOverride),this._responseHeaders[i]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let i=0;i<t.length;i++)n[i]=t[i];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},ke=Ee;ke.SyntaxError=ii,ke.ProgressEvent=Ps,ke.SecurityError=ai,ke.XMLHttpRequest=Ee,ke.InvalidStateError=pr,ke.XMLHttpRequestUpload=ni,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke});var IT=S(require("semver"));We();Hl();Bt();tn();var Zp=S(require("chalk")),RT=require("events");ne();gn();J();ne();qi();$();var tf=S(require("os")),ql=S(require("path")),zl=S(require("chalk")),Zi=require("fs");pe();function rf(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=tf.homedir();(0,Zi.mkdirSync)(ql.resolve(n,".testim_logs"),{recursive:!0});let i=ql.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}`),fd&&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(zl.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(zl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Zi.writeFileSync)(i,`${s}
419
419
  ${s==null?void 0:s.stack}
420
420
 
421
- ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Zs();var iv=A("process-handler"),sf=!1;function ov(s){return s instanceof Error?1:sf?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(me.SKIPPED)||[t,i].includes(me.FAILED)&&n===Xe.EVALUATING?!1:r!==!0)?1:0)}function av(){try{Xt("chromedriver").stop()}catch{}}function nf(){sf=!0}async function Kl(s){s!=null&&s.stack&&(es?console.error(s,s.stack):rf(s)),av(),await iv.waitForFlush(),process.exit(ov(s))}ge();$();le();var fR=A("cli-entry");function gR(s){if(!IT.satisfies(process.version,s))throw new x(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new x(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new x(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Zp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function hR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(F(),K)),Promise.resolve().then(()=>(kf(),Pf))]);U("Starting Testim.io CLI"),ef(Kl);try{gR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await L.fetch();let t=await e.process();if(U("in main, after options.process"),fc(global.proxyUri),RT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,mc(t.project),dm("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:i}=await Promise.resolve().then(()=>(vn(),Df));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Yr(),await fn(t);let{preloadTests:i}=await Promise.resolve().then(()=>(ao(),Nf));await i(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await br(t.playerLocation,t.canary);let o=await um();o.success?console.log(`created prefetched data at ${_i()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(sT(),rT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(bu(),yu));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(Yp(),ET));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(Wu(),Yg)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&nf(),U("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await Xm(t);return U("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof jr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Dl({...r,error:t.message}).catch(()=>{}),t instanceof x?(console.log(Zp.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),fR.error("runner ended with unexpected error",{err:t}),t)}}hR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Kl(s)});
421
+ ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Qs();var iv=A("process-handler"),sf=!1;function ov(s){return s instanceof Error?1:sf?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(me.SKIPPED)||[t,i].includes(me.FAILED)&&n===Xe.EVALUATING?!1:r!==!0)?1:0)}function av(){try{Xt("chromedriver").stop()}catch{}}function nf(){sf=!0}async function Kl(s){s!=null&&s.stack&&(es?console.error(s,s.stack):rf(s)),av(),await iv.waitForFlush(),process.exit(ov(s))}ge();$();le();var mR=A("cli-entry");function fR(s){if(!IT.satisfies(process.version,s))throw new x(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new x(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new x(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Zp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function gR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(F(),K)),Promise.resolve().then(()=>(kf(),Pf))]);U("Starting Testim.io CLI"),ef(Kl);try{fR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await L.fetch();let t=await e.process();if(U("in main, after options.process"),fc(global.proxyUri),RT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,mc(t.project),dm("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:i}=await Promise.resolve().then(()=>(wn(),Df));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Yr(),await mn(t);let{preloadTests:i}=await Promise.resolve().then(()=>(ao(),Nf));await i(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await br(t.playerLocation,t.canary);let o=await um();o.success?console.log(`created prefetched data at ${_i()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(sT(),rT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(bu(),yu));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(Yp(),ET));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(Wu(),Yg)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&nf(),U("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await Xm(t);return U("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof jr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Dl({...r,error:t.message}).catch(()=>{}),t instanceof x?(console.log(Zp.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),mR.error("runner ended with unexpected error",{err:t}),t)}}gR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Kl(s)});
422
422
  //# sourceMappingURL=cli.js.map