@testim/testim-cli 4.27.0 → 4.29.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 +78 -77
- package/cli.js.map +4 -4
- package/npm-shrinkwrap.json +52 -52
- package/package.json +3 -3
package/cli.js
CHANGED
|
@@ -1,58 +1,58 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
${l.msg}`));for(let m of rT)a[m]instanceof Error&&(l[m]={message:a[m].message,stack:a[m].stack,name:a[m].name,type:a[m].type,cause:a[m].cause,...a[m]});Object.keys(l).length>0&&(i&&!d&&(l.msg=i),p.text=l),this.logger.addLog(p),s(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Re.CoralogixLogger.configure(t),Lr.options=t}}});var $a={};W($a,{getLogger:()=>A,setExecutionId:()=>Ua,setProjectId:()=>ja,setProxyUri:()=>Ba});function oT(){let r=[],e=()=>Promise.resolve();if(!ke){let{CoralogixTransport:t}=(Ma(),fe(Da));t.configure(Wp);let s=new t({category:"ROOT"});r.push(s),e=()=>s.waitForFlush()}return Ap&&r.push(new wt.transports.Console({format:wt.format.combine(wt.format.colorize(),wt.format.simple())})),[r,e]}function Ua(r){Na=r}function ja(r){Vp=r}function Ba(r){if(ke||!r)return;let{CoralogixTransport:e}=(Ma(),fe(Da));e.configure({...Wp,proxyUri:r})}function Bp(r){return{projectId:Vp,time:new Date().toISOString(),...Na&&!r&&{executionId:Na}}}function A(r){return new Fa(uT.child({category:r}))}var $p,wt,sT,nT,Wp,iT,aT,cT,lT,uT,Na,Vp,Fa,$=T(()=>{"use strict";$p=E(require("os")),wt=E(require("winston"));le();B();sT=$p.hostname(),nT=ct(),Wp={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[iT,aT]=oT(),cT=Pp?"debug":"info",lT={release:Boolean(!0),branch:"production"},uT=wt.createLogger({levels:wt.config.syslog.levels,level:cT,transports:iT,defaultMeta:{name:"runner",hostname:sT,nodeVersion:process.version,runnerVersion:nT,...lT}}),Na=null,Vp=null;Fa=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,s={}){let{executionId:n}=s;try{this._logger.log(e,Object.assign({meta:s,message:t},Bp(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},Bp(n)))}catch{}}}waitForFlush(){return aT()}}});var Qn,Dr,P,$t,cr,vt,Yn,Mr,re,Ps,Et,Nr,St,Xn,Fr,Ur,jr,Cs,z=T(()=>{"use strict";Qn=require("p-retry"),Dr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},$t=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},cr=class extends Error{constructor(t,s){super(t);this.type=s}},vt=class extends Qn.AbortError{},Yn=class extends Qn.AbortError{},Mr=class extends Qn.AbortError{},re=class extends Error{},Ps=class extends Error{},Et=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Nr=class extends Et{constructor(){super(...arguments);this.name="GridConcurrencyError"}},St=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Xn=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Fr=class extends Error{},Ur=class extends Error{constructor(t){super();this.innerStack=t}},jr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Cs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Wa(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"&&typeof r.catch=="function"}function se(r){return(0,qp.setTimeout)(r)}function Va(r,e){let t=new Promise((s,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([r,t])}function ie(r,e,t="Timeout Error"){zn&&!Gp&&(Gp=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let s=new re(t);return e=zn?Number(zn)||6e5:e,Promise.race([r,se(e).then(()=>{throw s})])}async function ae(r,e,{concurrency:t}={}){if(t){Hp||=(await import("p-limit")).default;let s=Hp(t);return await Promise.all(Array.from(r,(n,o)=>s(()=>e(n,o))))}return await Promise.all(Array.from(r,e))}function Wt(r){return new Promise((e,t)=>{r((s,n)=>s?t(s):e(n))})}var qp,Gp,Hp,Ga=T(()=>{"use strict";qp=require("timers/promises");z();le();Gp=!1});var Os,zp,pT,ks,Kp,dT,mT,Jp,Yp=T(()=>{"use strict";Os=E(require("lodash"));le();zp=require("dns");$();Ga();pT=A("http-request-counters"),ks=!1,Kp=async()=>{if(ke)return!0;let r=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ae(r,t=>zp.promises.lookup(t)));return e||(ks=!0),e}catch{return pT.error("network connectivity test failed"),ks=!0,!1}},dT=Os.throttle(Kp,10*1e3),mT=60*1e3*15,Jp=()=>{let r={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},mT)}function t(n,o=n.name){return async function(...i){e(r.call,o);try{let a=await n.call(null,...i);return e(r.success,o),a}catch(a){throw e(r.fail,o),ks||dT(),a}}}async function s(){if(ks||!await Kp())return!1;let n=Os.sum([...r.fail.values()]),o=Os.sum([...r.call.values()]);return n<o*.1}return s.counters=r,t.counters=r,t.isNetworkHealthy=s,t.didNetworkConnectivityTestFail=()=>ks,t}});var Ze={};W(Ze,{deleteFullRes:()=>bT,deleteReq:()=>_s,didNetworkConnectivityTestFail:()=>Xa,download:()=>Ja,get:()=>$e,getFullRes:()=>wT,getText:()=>za,head:()=>vT,isNetworkHealthy:()=>Ya,post:()=>Be,postForm:()=>Ls,postFullRes:()=>TT,put:()=>Ka});function gT(){return global.caFileContent}function hT(r,e){let t=[];r.on("data",s=>{t.push(s)}),r.on("end",()=>{e(null,Buffer.concat(t))})}function yT(){return!Rt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Rt.default),global.proxyUri}function lr(r,e=!1){let t=gT();t&&r.ca(t);let s=!e&&yT();s&&r.proxy(s)}async function Xp(r,e={},t={},s=Br){let n=Rt.default.delete(r).send(e).timeout(s).set(t);return lr(n),await n}async function Qp(r,e,t={},s=Br,n=0){let o=Rt.default.post(r).send(e).timeout(s).set(t);lr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=r,i.originalRequestTimeout=s,i.additionalSetHeaders=t,i}}async function qa(r,e,t={},s=Br,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Rt.default.get(r).query(e||{}).timeout(s).set(t);return n&&i.buffer(!0),lr(i,o),await i}var Rt,Ha,Ge,Br,fT,Vt,_s,bT,Be,TT,Ls,za,$e,wT,vT,Ka,Ja,Ya,Xa,He=T(()=>{"use strict";Rt=E(require("superagent"));$();Yp();Ha=A("http-request"),Ge=Jp(),Br=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,fT=6e4;Vt=(r,e,t)=>{throw Ha.error(r,{...t,error:e}),e};_s=Ge(async(r,e,t,s)=>{try{let n=await Xp(r,e,t,s);return n.type==="text/plain"?n.text:n.body}catch(n){return Vt("failed to delete request",n,{url:r})}});bT=Ge(Xp),Be=Ge(async({url:r,body:e,headers:t,timeout:s,retry:n})=>{try{let o=await Qp(r,e,t,s,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Vt("failed to post request",o,{url:r})}});TT=Ge(Qp),Ls=Ge(async(r,e,t,s={},n=Br)=>{let o=Rt.default.post(r).type("form").timeout(n).set(s);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),lr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Vt("failed to post request",i,{url:r})}});za=Ge(async(r,e,t)=>{try{return(await qa(r,e,t)).text}catch(s){return Vt("failed to getText request",s,{url:r,query:e})}}),$e=Ge(async(r,e,t,s,n)=>{try{return(await qa(r,e,t,s,n)).body}catch(o){return Vt("failed to get request",o,{url:r,query:e})}}),wT=Ge((r,e,t,s)=>qa(r,e,t,s)),vT=Ge(async r=>{let e=Rt.default.head(r).timeout(Br);lr(e);try{return await e}catch(t){return Vt("failed to head request",t,{url:r})}}),Ka=Ge(async(r,e,t={},s=Br)=>{let n=Rt.default.put(r).send(e).timeout(s).set(t);lr(n);try{return(await n).body}catch(o){return Vt("failed to put request",o,{url:r})}}),Ja=Ge(async r=>{Ha.info("start to download",{url:r});let e=Rt.default.get(r).timeout(fT).buffer(!0).parse(hT);lr(e);try{let t=await e;return Ha.info("finished to download",{url:r}),t}catch(t){return Vt("failed to download",t,{url:r})}}),Ya=Ge.isNetworkHealthy,Xa=Ge.didNetworkConnectivityTestFail});function lt(){let r;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?r=Ot.resolve(__dirname,"../../"):r=Ot.resolve(__dirname,""),r):process.cwd()}function Zn(r,e){return je(r)?e||Ot.join(process.cwd(),r.replace(/^.*[\\/]/,"")):e||Ot.basename(r)}function ct(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function ST(){try{return Ep.node}catch{return""}}async function td(r,e,t=!0){let s=await It.promises.readdir(r,{withFileTypes:!0});await It.promises.mkdir(e,{recursive:t});for(let n of s){let o=Ot.join(r,n.name),i=Ot.join(e,n.name);n.isDirectory()?await td(o,i):await It.promises.copyFile(o,i)}}async function ge(r){try{return await It.promises.access(r),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Ot,Zp,ed,It,ET,_t,qe,eo,Qa,et,Za,rd=T(()=>{"use strict";Ot=E(require("path"));ka();Hn();Zp=E(require("p-retry")),ed=E(require("decompress")),It=require("fs"),ET=3;_t=async r=>{let e=await Promise.resolve().then(()=>(He(),Ze));return(0,Zp.default)(()=>e.download(r),{retries:ET,factor:1})},qe=async(r,e)=>{let t=await _t(r);return It.promises.writeFile(e,t.body)};eo=async(r,e)=>{let t=Zn(r,e);return je(r)?qe(r,t):It.promises.copyFile(r,t)},Qa=async r=>je(r)?_t(r):It.promises.readFile(r),et=async(r,e)=>await(0,ed.default)(r,e),Za=r=>(0,It.statSync)(r).size/1e6});var Lt={};W(Lt,{APPIUM_SESSION_MESSAGE:()=>nc,CLI_MODE:()=>Q,MOBILE_APP_SOURCE:()=>to,MOBILE_RUN_SKIP_REASON:()=>sc,gridMessages:()=>$r,gridTypes:()=>N,mobileWeb:()=>tc,runnerStatus:()=>ec,runnerTestStatus:()=>pe,sessionType:()=>ur,socketEventTypes:()=>tt,stepResult:()=>Ms,test:()=>rc,testRunStatus:()=>Ds,testStatus:()=>ze,timeoutMessages:()=>We});var We,Ds,ec,pe,ze,$r,tc,rc,tt,Q,ur,N,Ms,to,sc,nc,ce=T(()=>{"use strict";We={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Ds={COMPLETED:"completed",RUNNING:"running"},ec={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},pe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},ze={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},$r={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},tc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},rc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},tt={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"},ur={CODELESS:"codeless",CODEFUL:"codeful"},N={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC"},Ms={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"},to={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},sc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},nc={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"}});function pr(r){return r.files.length>0?ur.CODEFUL:ur.CODELESS}function Ns(r,e){var t,s,n;return((t=r.testConfigNames)!=null&&t.length||(s=r.testConfigIds)!=null&&s.length||r.testPlan.length||r.testPlanIds.length)&&!r.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=r.browser)==null?void 0:n.toLowerCase()]}function RT(){let{argv:r}=process;if(r.includes("--remoteRunId"))return{remoteRunId:r[r.indexOf("--remoteRunId")+1],projectId:r[r.indexOf("--project")+1],token:r[r.indexOf("--token")+1]}}var Fs,sd,Ke,IT,xT,AT,PT,CT,oc,nd=T(()=>{"use strict";ce();Fs=r=>{var e,t;return Boolean(((e=r.testPlan)==null?void 0:e.length)||((t=r.testPlanIds)==null?void 0:t.length))},sd=r=>Boolean(r.resultId&&r.source==="remote-run"),Ke=(r,e)=>r.testStatus===ze.QUARANTINE&&!sd(e)&&!e.runQuarantinedTests;IT=r=>Boolean(r.loginMode),xT=r=>Boolean(r.tunnelOnlyMode),AT=r=>Boolean(r.createPrefechedData),PT=r=>Boolean(r.installLazyDepsMode),CT=r=>Boolean(r.agentMode),oc=(r,e)=>{r.forEach((t,s)=>{e.has(t)&&(r[s]=`--${t}`)})}});function ro(r){let e=ic.default.duration(r);return`${e.hours()}:${e.minutes()}:${e.seconds()}.${e.milliseconds()}`}function ac(r){return ic.default.duration(r).asSeconds()}var ic,od=T(()=>{"use strict";ic=E(require("moment"))});var Us,Wr,js,id=T(()=>{"use strict";Us=r=>!(!r||"fileName"in r),Wr=r=>r&&"fileName"in r?r.fileName.endsWith(".app"):!1,js=r=>{var e,t;return((e=r.projectData)==null?void 0:e.type)==="ios"||((t=r.projectData)==null?void 0:t.type)==="android"}});function cc(r=4e3){let e=process.memoryUsage(),t=s=>Math.round(s/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>r,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 ad=T(()=>{"use strict"});var K={};W(K,{TESTIM_BROWSER_DIR:()=>Dt,buildBasicHeader:()=>Ca,calcPercentile:()=>oo,copyDir:()=>td,delay:()=>se,doesPathExist:()=>ge,download:()=>_t,downloadAndSave:()=>qe,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>RT,getBrowserInfo:()=>OT,getCdpAddressForHost:()=>fr,getCliLocation:()=>lt,getDuration:()=>ro,getDurationSec:()=>ac,getEnginesVersion:()=>ST,getEnvironmentGitBranch:()=>mr,getLocalFileSizeInMB:()=>Za,getMemorySnapshot:()=>cc,getPlanType:()=>no,getRunConfigByBrowserName:()=>$s,getRunnerVersion:()=>ct,getSessionType:()=>pr,getSource:()=>eo,getSourceAsBuffer:()=>Qa,getSourcePath:()=>Zn,getTestUrl:()=>at,getUniqBrowsers:()=>Ns,groupTestsByRetries:()=>uc,guid:()=>te,hasTestPlanFlag:()=>Fs,isAgentMode:()=>CT,isAppForVirtualIosDevice:()=>Wr,isAppFromDevice:()=>Us,isCreatePrefetchedDataMode:()=>AT,isInstallLazyDepsMode:()=>PT,isLoginMode:()=>IT,isMobileProject:()=>js,isPromise:()=>Wa,isQuarantineAndNotRemoteRun:()=>Ke,isRemoteRun:()=>sd,isTunnelOnlyMode:()=>xT,isURL:()=>je,promiseAbort:()=>Va,promiseFromCallback:()=>Wt,promiseMap:()=>ae,promiseTimeout:()=>ie,removePropertyFromObject:()=>so,replaceArgsWithNoDashes:()=>oc,unzipFile:()=>et});function OT(r){return r=r.toLowerCase(),lc.find(e=>e.browserValue===r)}function $s(r,e,t){r=r.toLowerCase();let s=lc.find(o=>o.browserName.toLowerCase()===r||r.includes(o.synonyms))||lc[0],n=Bs.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=Bs.find(o=>o.sl.platform===e.platform):e.platformName&&(n=Bs.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=Bs.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=Bs.find(o=>o.bs.platform===t.platform))),dr.merge(s,n)}function mr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function so(r,e,t){for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t(s,e)?delete r[s]:typeof r[s]=="object"&&so(r[s],e,t))}function _e(r){return r.ELEMENT||r[Bt]}function no(r){r||={};let e=Date.now(),t=r.expireAt||r.expireAT;return r.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function uc(r=[]){return dr.chain(r).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 s=dr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=dr.chain(s).last().cloneDeep().value();return n&&(n.retryTestResults=s,e.push(n)),e},[]).compact().value()}async function fr(r,e){let t=await Promise.resolve().then(()=>(He(),Ze));try{return(await t.get(`http://${r}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var cd,dr,ld,kT,Dt,Bs,lc,oo,B=T(()=>{"use strict";cd=E(require("os")),dr=E(require("lodash")),ld=E(require("path"));kr();rd();nd();od();ka();Ga();id();ad();kT=cd.homedir(),Dt=ld.join(kT,".testim-browser-profile"),Bs=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14"},sl:{platform:"macOS 11",safari_version:"14"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13"},sl:{platform:"macOS 10.15",safari_version:"13"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12"},sl:{platform:"macOS 10.14",safari_version:"12"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11"},sl:{platform:"macOS 10.13",safari_version:"11"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10"},sl:{platform:"macOS 10.12",safari_version:"10.0"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"9.0"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"8.0"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"7.0"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"6.0"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],lc=[{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"}];oo=(r,e)=>{if(r.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(r=[...r].sort((s,n)=>s-n),e<=0)return r[0];if(e>=100)return r.at(-1);let t=Math.ceil(r.length*(e/100))-1;return r[t]}});var pc={};W(pc,{$schema:()=>_T,default:()=>FT,definitions:()=>LT,properties:()=>NT,required:()=>MT,type:()=>DT});var _T,LT,DT,MT,NT,FT,ud=T(()=>{_T="http://json-schema.org/draft-07/schema#",LT={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}}}},DT="object",MT=["entries"],NT={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},FT={$schema:_T,definitions:LT,type:DT,required:MT,properties:NT}});async function yd(){try{return await ie(io.promises.readFile(uo()).then(async r=>{let e=await hd;return BT(e,r)}),3e4)}catch{return{}}}function BT(r,e){let t=e.slice(0,16),s=e.slice(16),n=Buffer.from(r),o=Gr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(s);return JSON.parse(Buffer.concat([i,o.final()]))}function ut(r,e,t=UT,s=void 0){return async()=>{if(!md)return await r();let n=e;s&&(e+=JSON.stringify(s));let o=await $T(e);if(o)return Ws.debug("cache hit:",{fnName:e}),o;if(Ws.debug("cache miss:",{fnName:e}),!fd)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await r();return i&&await WT(e,i,t),i}}async function $T(r){let t=(await po)[r];if(!t)return;let{value:s,expiry:n}=t;if(!(n<Date.now())&&s)return s}async function WT(r,e,t){if(dc)throw Ws.error("calling set after waitForSave is not allowed",{key:r,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let s=await po;s[r]={value:e,expiry:Date.now()+t},gd=new Promise(n=>{lo=n}),jT(s)}catch{Ws.error("failed updating cache")}}async function bd(){let r=await po;Object.keys(r).forEach(e=>{delete r[e]})}function Td(r){md=r}function VT(r=!0){fd=r}async function wd(){try{return dc=!0,await gd}finally{dc=!1}}function vd(r){co=r,po=yd()}var io,ao,Gr,pd,Ws,co,dd,lo,md,fd,dc,gd,hd,UT,uo,po,jT,Ed,Sd,tI,Rd,Gt=T(()=>{"use strict";io=E(require("fs")),ao=E(require("path")),Gr=E(require("crypto"));B();pd=require("lodash");$();Ws=A("local cache"),co=ao.resolve(lt(),"testim-cache"),md=!0,fd=!0,dc=!1,gd=new Promise(r=>{lo=r}),hd=new Promise(r=>{dd=r}),UT=1e3*60*60*3,uo=()=>ao.resolve(ao.resolve(co,"testim.cache"));po=yd(),jT=(0,pd.debounce)(async r=>{let e;try{let t=await hd,s=Gr.randomBytes(16),n=JSON.stringify(r),o=Buffer.from(t),i=Gr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),s),a=Buffer.concat([s,i.update(n),i.final()]);await ge(co)||await io.promises.mkdir(co,{recursive:!0}),await io.promises.writeFile(uo(),a)}catch(t){Ws.error("failed saving cache",{err:t}),e=t}lo(e?{success:!1,error:e}:{success:!0})},200);Ed=dd,Sd=Td.bind(void 0,!1),tI=Td.bind(void 0,!0),Rd=()=>VT(!1)});function mo(){return{cliLocation:lt(),userInfo:Hr.userInfo(),platform:Hr.platform(),release:Hr.release()}}var Hr,mc=T(()=>{"use strict";Hr=E(require("os"));B()});function GT(r){try{return fo.resolve(fo.dirname(require.resolve(`${r}/package.json`)),require(`${r}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(r);throw e}}function Ht(r){let e=GT(r);return require(e)}var fo,Vs=T(()=>{"use strict";fo=E(require("path"))});async function Pd(r){return(await xd(`npm view ${r} version`)).stdout.trim()}function gc(r){try{return Ht(r)}catch{return!1}}function Cd(r,e){return require(qr.join(r,`./node_modules/${e}/package.json`)).version}async function ho(r,e,t){function s(c){let p=/EACCES[^']+'(.+)'/.exec(c.stderr);return p===null?!1:p[1]}function n(c){return/The "to" argument must be of type string./.exec(c.stderr)}let o=qr.join(r,"npm-shrinkwrap.json"),i=qr.join(r,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await ge(o)&&(await fc.promises.rename(o,i),a=!0)}catch{}return await xd(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:r}).catch(c=>{let l=s(c),p=n(c);throw l||p?(Ad.info("Failed to install package due to insufficient write access",{...mo(),package:e,path:l||r}),console.error(`
|
|
2
|
+
"use strict";var Mb=Object.create;var Mn=Object.defineProperty;var Nb=Object.getOwnPropertyDescriptor;var Ub=Object.getOwnPropertyNames;var Fb=Object.getPrototypeOf,Bb=Object.prototype.hasOwnProperty;var T=(s,e)=>()=>(s&&(e=s(s=0)),e);var G=(s,e)=>{for(var t in e)Mn(s,t,{get:e[t],enumerable:!0})},up=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ub(e))!Bb.call(s,n)&&n!==t&&Mn(s,n,{get:()=>e[n],enumerable:!(r=Nb(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?Mb(Fb(s)):{},up(e||!s||!s.__esModule?Mn(t,"default",{value:s,enumerable:!0}):t,s)),fe=s=>up(Mn({},"__esModule",{value:!0}),s);var Ue={};G(Ue,{log:()=>L,measure:()=>$b});function L(...s){if(!mp)return;let e=Date.now();console.log(`${e-jb} ${e-dp} `,...s),dp=e}function $b(s,e){if(!mp)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var mp,jb,dp,Fe=T(()=>{"use strict";mp=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,jb=Date.now(),dp=Date.now()});var Ta,Wt,wa,Cr=T(()=>{"use strict";Ta={NULL:"\uE000",Unidentified:"\uE000",Cancel:"\uE001",Help:"\uE002","Back space":"\uE003",Backspace:"\uE003",Tab:"\uE004",Clear:"\uE005",Return:"\uE006",Enter:"\uE007",Shift:"\uE008",Control:"\uE009",Alt:"\uE00A",Pause:"\uE00B",Escape:"\uE00C",Space:"\uE00D"," ":"\uE00D",Pageup:"\uE00E",PageUp:"\uE00E",Page_Up:"\uE00E",Pagedown:"\uE00F",PageDown:"\uE00F",Page_Down:"\uE00F",End:"\uE010",Home:"\uE011","Left arrow":"\uE012",Arrow_Left:"\uE012",ArrowLeft:"\uE012","Up arrow":"\uE013",Arrow_Up:"\uE013",ArrowUp:"\uE013","Right arrow":"\uE014",Arrow_Right:"\uE014",ArrowRight:"\uE014","Down arrow":"\uE015",Arrow_Down:"\uE015",ArrowDown:"\uE015",Insert:"\uE016",Delete:"\uE017",Semicolon:"\uE018",Equals:"\uE019","Numpad 0":"\uE01A","Numpad 1":"\uE01B","Numpad 2":"\uE01C","Numpad 3":"\uE01D","Numpad 4":"\uE01E","Numpad 5":"\uE01F","Numpad 6":"\uE020","Numpad 7":"\uE021","Numpad 8":"\uE022","Numpad 9":"\uE023",Multiply:"\uE024",Add:"\uE025",Separator:"\uE026",Subtract:"\uE027",Decimal:"\uE028",Divide:"\uE029",F1:"\uE031",F2:"\uE032",F3:"\uE033",F4:"\uE034",F5:"\uE035",F6:"\uE036",F7:"\uE037",F8:"\uE038",F9:"\uE039",F10:"\uE03A",F11:"\uE03B",F12:"\uE03C",Command:"\uE03D",Meta:"\uE03D",Zenkaku_Hankaku:"\uE040",ZenkakuHankaku:"\uE040"},Wt="element-6066-11e4-a52e-4f735466cecf",wa=79});function te(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function ot(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function va(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Be(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var Ea=T(()=>{"use strict"});var Ra,fp,gp,Gn=T(()=>{Ra={ngrok:"4.3.3",webpack:"5.74.0",playwright:"0.12.1",puppeteer:"2.1.1","selenium-webdriver":"3.6.0","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},fp={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@testim/coralogix-logger":"1.1.27-beta.1","abort-controller":"3.0.0",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",decompress:"4.2.1",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"5.0.0","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.16.2",jsdom:"19.0.0",jsonwebtoken:"9.0.0",linkedom:"^0.14.25",lodash:"4.17.21","memory-fs":"0.5.0",moment:"2.29.4",ms:"2.1.2",npm:"8.19.2","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"5.0.0","rox-node":"4.9.18",semver:"7.5.4","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"3.8.3","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.6.0","winston-transport":"4.5.0",ws:"8.5.0",xml2js:"0.5.0",yaml:"2.2.2"},gp={node:">= 16.0.0"}});var As,hp,yp,Vn,bp,Hn,kr,Tp,me,wp,vp,qn,Ce,Ia,Ep,zn,Sp,aR,Rp,cR,Ip,xp,Or,Ap,Pp,Cp,kp,Op,_p,Lp,Dp,le=T(()=>{"use strict";As=process.env.SERVICES_HOST||"https://services.testim.io",hp="https://testimstatic.blob.core.windows.net",yp="https://tstresultfiles.azureedge.net";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:As,As=process.env.SERVICES_HOST);Vn=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),bp=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),Hn=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),kr=process.env.EDITOR_URL,Tp=process.env.WEBSOCKET_HOST||`${As}/ws`,me=As,wp=parseInt(process.env.LOGGER_CONSOLE||"0",10),vp=parseInt(process.env.LOGGER_DEBUG||"0",10),qn=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Ce=parseInt(process.env.IS_ON_PREM||"0",10),Ia=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Ep=parseInt(process.env.DEBUG_MODE||"0",10),zn=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Sp=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",aR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Rp=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),cR=process.env.APPIUM_VERSION||"1.10.1",Ip=process.env.GATEWAY_URL,xp=process.env.EXTENSION_SERVICES_HOST||As,Or=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:hp,Ap=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:yp,Pp=hp,Cp=yp,kp=5*60*1e3,Op=40,_p=process.env.HEADSPIN_MOBILE_DEVICES_API_URL||"https://api-dev.headspin.io/v0",Lp=process.env.TDC_MOBILE_DEVICES_API_URL||"https://api.tdc.tricentis-cloud.com/v0",Dp=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api"});var xa={};G(xa,{CoralogixTransport:()=>_r});var Re,Mp,Vb,Hb,_r,Aa=T(()=>{"use strict";Re=require("@testim/coralogix-logger"),Mp=E(require("winston-transport")),Vb={debug:Re.Severity.debug,silly:Re.Severity.verbose,verbose:Re.Severity.verbose,silent:Re.Severity.verbose,info:Re.Severity.info,http:Re.Severity.info,warn:Re.Severity.warning,warning:Re.Severity.warning,error:Re.Severity.error,critical:Re.Severity.critical,crit:Re.Severity.critical},Hb=["err","error","reason","e"],_r=class extends Mp.default{constructor(t){t=Object.assign({},_r.options,t);super(t);this.options=t,this.logger=new Re.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:o,message:i,meta:a={},...c}=t,l=Object.assign({},a,this.options.extraFields,c),d=new Re.Log;d.severity=Vb[o],d.text=i,d.category=n,l.className&&(d.className=l.className),l.methodName&&(d.methodName=l.methodName),l.threadId&&(d.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let m=!1;a instanceof Error&&(m=!0,l.msg=a.message+a.stack,i&&(l.msg=`${i}
|
|
3
|
+
${l.msg}`));for(let p of Hb)a[p]instanceof Error&&(l[p]={message:a[p].message,stack:a[p].stack,name:a[p].name,type:a[p].type,cause:a[p].cause,...a[p]});Object.keys(l).length>0&&(i&&!m&&(l.msg=i),d.text=l),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Re.CoralogixLogger.configure(t),_r.options=t}}});var La={};G(La,{getLogger:()=>x,setExecutionId:()=>ka,setProjectId:()=>Oa,setProxyUri:()=>_a});function Kb(){let s=[],e=()=>Promise.resolve();if(!Ce){let{CoralogixTransport:t}=(Aa(),fe(xa));t.configure(Fp);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return wp&&s.push(new yt.transports.Console({format:yt.format.combine(yt.format.colorize(),yt.format.simple())})),[s,e]}function ka(s){Pa=s}function Oa(s){Bp=s}function _a(s){if(Ce||!s)return;let{CoralogixTransport:e}=(Aa(),fe(xa));e.configure({...Fp,proxyUri:s})}function Np(s){return{projectId:Bp,time:new Date().toISOString(),...Pa&&!s&&{executionId:Pa}}}function x(s){return new Ca(Zb.child({category:s}))}var Up,yt,qb,zb,Fp,Jb,Yb,Xb,Qb,Zb,Pa,Bp,Ca,B=T(()=>{"use strict";Up=E(require("os")),yt=E(require("winston"));le();j();qb=Up.hostname(),zb=it(),Fp={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[Jb,Yb]=Kb(),Xb=vp?"debug":"info",Qb={release:Boolean(!0),branch:"production"},Zb=yt.createLogger({levels:yt.config.syslog.levels,level:Xb,transports:Jb,defaultMeta:{name:"runner",hostname:qb,nodeVersion:process.version,runnerVersion:zb,...Qb}}),Pa=null,Bp=null;Ca=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,Object.assign({meta:r,message:t},Np(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},Np(n)))}catch{}}}waitForFlush(){return Yb()}}});var Yn,Lr,P,Gt,lr,bt,Kn,Dr,re,Ps,Tt,Mr,wt,Jn,Nr,Ur,Fr,Cs,z=T(()=>{"use strict";Yn=require("p-retry"),Lr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Gt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},lr=class extends Error{constructor(t,r){super(t);this.type=r}},bt=class extends Yn.AbortError{},Kn=class extends Yn.AbortError{},Dr=class extends Yn.AbortError{},re=class extends Error{},Ps=class extends Error{},Tt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Mr=class extends Tt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},wt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Jn=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Nr=class extends Error{},Ur=class extends Error{constructor(t){super();this.innerStack=t}},Fr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Cs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Da(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function oe(s){return(0,Wp.setTimeout)(s)}function Ma(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ae(s,e,t="Timeout Error"){Hn&&!jp&&(jp=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new re(t);return e=Hn?Number(Hn)||6e5:e,Promise.race([s,oe(e).then(()=>{throw r})])}async function ie(s,e,{concurrency:t}={}){if(t){$p||=(await import("p-limit")).default;let r=$p(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function Vt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Wp,jp,$p,Na=T(()=>{"use strict";Wp=require("timers/promises");z();le();jp=!1});var Os,Gp,eT,ks,Vp,tT,rT,Hp,qp=T(()=>{"use strict";Os=E(require("lodash"));le();Gp=require("dns");B();Na();eT=x("http-request-counters"),ks=!1,Vp=async()=>{if(Ce)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ie(s,t=>Gp.promises.lookup(t)));return e||(ks=!0),e}catch{return eT.error("network connectivity test failed"),ks=!0,!1}},tT=Os.throttle(Vp,10*1e3),rT=60*1e3*15,Hp=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},rT)}function t(n,o=n.name){return async function(...i){e(s.call,o);try{let a=await n.call(null,...i);return e(s.success,o),a}catch(a){throw e(s.fail,o),ks||tT(),a}}}async function r(){if(ks||!await Vp())return!1;let n=Os.sum([...s.fail.values()]),o=Os.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>ks,t}});var Qe={};G(Qe,{deleteFullRes:()=>aT,deleteReq:()=>_s,didNetworkConnectivityTestFail:()=>Ga,download:()=>$a,get:()=>Ne,getFullRes:()=>lT,getText:()=>Ba,head:()=>uT,isNetworkHealthy:()=>Wa,post:()=>je,postForm:()=>Ls,postFullRes:()=>cT,put:()=>ja});function nT(){return global.caFileContent}function oT(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function iT(){return!vt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(vt.default),global.proxyUri}function ur(s,e=!1){let t=nT();t&&s.ca(t);let r=!e&&iT();r&&s.proxy(r)}async function zp(s,e={},t={},r=Br){let n=vt.default.delete(s).send(e).timeout(r).set(t);return ur(n),await n}async function Kp(s,e,t={},r=Br,n=0){let o=vt.default.post(s).send(e).timeout(r).set(t);ur(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function Fa(s,e,t={},r=Br,{isBinary:n=!1,skipProxy:o=!1}={}){let i=vt.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),ur(i,o),await i}var vt,Ua,Ge,Br,sT,Ht,_s,aT,je,cT,Ls,Ba,Ne,lT,uT,ja,$a,Wa,Ga,Ve=T(()=>{"use strict";vt=E(require("superagent"));B();qp();Ua=x("http-request"),Ge=Hp(),Br=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,sT=6e4;Ht=(s,e,t)=>{throw Ua.error(s,{...t,error:e}),e};_s=Ge(async(s,e,t,r)=>{try{let n=await zp(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Ht("failed to delete request",n,{url:s})}});aT=Ge(zp),je=Ge(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await Kp(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Ht("failed to post request",o,{url:s})}});cT=Ge(Kp),Ls=Ge(async(s,e,t,r={},n=Br)=>{let o=vt.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),ur(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Ht("failed to post request",i,{url:s})}});Ba=Ge(async(s,e,t)=>{try{return(await Fa(s,e,t)).text}catch(r){return Ht("failed to getText request",r,{url:s,query:e})}}),Ne=Ge(async(s,e,t,r,n)=>{try{return(await Fa(s,e,t,r,n)).body}catch(o){return Ht("failed to get request",o,{url:s,query:e})}}),lT=Ge((s,e,t,r)=>Fa(s,e,t,r)),uT=Ge(async s=>{let e=vt.default.head(s).timeout(Br);ur(e);try{return await e}catch(t){return Ht("failed to head request",t,{url:s})}}),ja=Ge(async(s,e,t={},r=Br)=>{let n=vt.default.put(s).send(e).timeout(r).set(t);ur(n);try{return(await n).body}catch(o){return Ht("failed to put request",o,{url:s})}}),$a=Ge(async s=>{Ua.info("start to download",{url:s});let e=vt.default.get(s).timeout(sT).buffer(!0).parse(oT);ur(e);try{let t=await e;return Ua.info("finished to download",{url:s}),t}catch(t){return Ht("failed to download",t,{url:s})}}),Wa=Ge.isNetworkHealthy,Ga=Ge.didNetworkConnectivityTestFail});function at(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Ot.resolve(__dirname,"../../"):s=Ot.resolve(__dirname,""),s):process.cwd()}function Xn(s,e){return Be(s)?e||Ot.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Ot.basename(s)}function it(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function dT(){try{return gp.node}catch{return""}}async function Xp(s,e,t=!0){let r=await Et.promises.readdir(s,{withFileTypes:!0});await Et.promises.mkdir(e,{recursive:t});for(let n of r){let o=Ot.join(s,n.name),i=Ot.join(e,n.name);n.isDirectory()?await Xp(o,i):await Et.promises.copyFile(o,i)}}async function ge(s){try{return await Et.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Ot,Jp,Yp,Et,pT,_t,He,Qn,Va,Ze,Ha,Qp=T(()=>{"use strict";Ot=E(require("path"));Ea();Gn();Jp=E(require("p-retry")),Yp=E(require("decompress")),Et=require("fs"),pT=3;_t=async s=>{let e=await Promise.resolve().then(()=>(Ve(),Qe));return(0,Jp.default)(()=>e.download(s),{retries:pT,factor:1})},He=async(s,e)=>{let t=await _t(s);return Et.promises.writeFile(e,t.body)};Qn=async(s,e)=>{let t=Xn(s,e);return Be(s)?He(s,t):Et.promises.copyFile(s,t)},Va=async s=>Be(s)?_t(s):Et.promises.readFile(s),Ze=async(s,e)=>await(0,Yp.default)(s,e),Ha=s=>(0,Et.statSync)(s).size/1e6});var Lt={};G(Lt,{APPIUM_SESSION_MESSAGE:()=>Ya,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>Zn,MOBILE_RUN_SKIP_REASON:()=>Ja,gridMessages:()=>jr,gridTypes:()=>N,mobileWeb:()=>za,runnerStatus:()=>qa,runnerTestStatus:()=>pe,socketEventTypes:()=>St,stepResult:()=>Ms,test:()=>Ka,testRunStatus:()=>Ds,testStatus:()=>qe,timeoutMessages:()=>$e});var $e,Ds,qa,pe,qe,jr,za,Ka,St,Y,N,Ms,Zn,Ja,Ya,ce=T(()=>{"use strict";$e={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Ds={COMPLETED:"completed",RUNNING:"running"},qa={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},pe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},qe={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},jr={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},za={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Ka={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},St={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Y={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},N={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC"},Ms={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},Zn={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Ja={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Ya={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 Ns(s,e){var t,r,n;return((t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length)&&!s.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function mT(){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 Us,Zp,ze,fT,gT,hT,yT,bT,Xa,ed=T(()=>{"use strict";ce();Us=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},Zp=s=>Boolean(s.resultId&&s.source==="remote-run"),ze=(s,e)=>s.testStatus===qe.QUARANTINE&&!Zp(e)&&!e.runQuarantinedTests;fT=s=>Boolean(s.loginMode),gT=s=>Boolean(s.tunnelOnlyMode),hT=s=>Boolean(s.createPrefechedData),yT=s=>Boolean(s.installLazyDepsMode),bT=s=>Boolean(s.agentMode),Xa=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})}});function eo(s){let e=Qa.default.duration(s);return`${e.hours()}:${e.minutes()}:${e.seconds()}.${e.milliseconds()}`}function Za(s){return Qa.default.duration(s).asSeconds()}var Qa,td=T(()=>{"use strict";Qa=E(require("moment"))});var Fs,$r,Bs,rd=T(()=>{"use strict";Fs=s=>!(!s||"fileName"in s),$r=s=>s&&"fileName"in s?s.fileName.endsWith(".app"):!1,Bs=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"}});function ec(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 sd=T(()=>{"use strict"});var K={};G(K,{TESTIM_BROWSER_DIR:()=>Dt,buildBasicHeader:()=>va,calcPercentile:()=>so,copyDir:()=>Xp,delay:()=>oe,doesPathExist:()=>ge,download:()=>_t,downloadAndSave:()=>He,extractElementId:()=>Oe,getArgsOnRemoteRunFailure:()=>mT,getBrowserInfo:()=>wT,getCdpAddressForHost:()=>mr,getCliLocation:()=>at,getDuration:()=>eo,getDurationSec:()=>Za,getEnginesVersion:()=>dT,getEnvironmentGitBranch:()=>dr,getLocalFileSizeInMB:()=>Ha,getMemorySnapshot:()=>ec,getPlanType:()=>ro,getRunConfigByBrowserName:()=>$s,getRunnerVersion:()=>it,getSource:()=>Qn,getSourceAsBuffer:()=>Va,getSourcePath:()=>Xn,getTestUrl:()=>ot,getUniqBrowsers:()=>Ns,groupTestsByRetries:()=>rc,guid:()=>te,hasTestPlanFlag:()=>Us,isAgentMode:()=>bT,isAppForVirtualIosDevice:()=>$r,isAppFromDevice:()=>Fs,isCreatePrefetchedDataMode:()=>hT,isInstallLazyDepsMode:()=>yT,isLoginMode:()=>fT,isMobileProject:()=>Bs,isPromise:()=>Da,isQuarantineAndNotRemoteRun:()=>ze,isRemoteRun:()=>Zp,isTunnelOnlyMode:()=>gT,isURL:()=>Be,promiseAbort:()=>Ma,promiseFromCallback:()=>Vt,promiseMap:()=>ie,promiseTimeout:()=>ae,removePropertyFromObject:()=>to,replaceArgsWithNoDashes:()=>Xa,unzipFile:()=>Ze});function wT(s){return s=s.toLowerCase(),tc.find(e=>e.browserValue===s)}function $s(s,e,t){s=s.toLowerCase();let r=tc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||tc[0],n=js.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=js.find(o=>o.sl.platform===e.platform):e.platformName&&(n=js.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=js.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=js.find(o=>o.bs.platform===t.platform))),pr.merge(r,n)}function dr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function to(s,e,t){for(let r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&to(s[r],e,t))}function Oe(s){return s.ELEMENT||s[Wt]}function ro(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function rc(s=[]){return pr.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=pr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=pr.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function mr(s,e){let t=await Promise.resolve().then(()=>(Ve(),Qe));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 nd,pr,od,TT,Dt,js,tc,so,j=T(()=>{"use strict";nd=E(require("os")),pr=E(require("lodash")),od=E(require("path"));Cr();Qp();ed();td();Ea();Na();rd();sd();TT=nd.homedir(),Dt=od.join(TT,".testim-browser-profile"),js=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14"},sl:{platform:"macOS 11",safari_version:"14"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13"},sl:{platform:"macOS 10.15",safari_version:"13"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12"},sl:{platform:"macOS 10.14",safari_version:"12"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11"},sl:{platform:"macOS 10.13",safari_version:"11"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10"},sl:{platform:"macOS 10.12",safari_version:"10.0"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"9.0"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"8.0"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"7.0"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"6.0"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],tc=[{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"}];so=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]}});var sc={};G(sc,{$schema:()=>vT,default:()=>xT,definitions:()=>ET,properties:()=>IT,required:()=>RT,type:()=>ST});var vT,ET,ST,RT,IT,xT,id=T(()=>{vT="http://json-schema.org/draft-07/schema#",ET={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}}}},ST="object",RT=["entries"],IT={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},xT={$schema:vT,definitions:ET,type:ST,required:RT,properties:IT}});async function md(){try{return await ae(no.promises.readFile(co()).then(async s=>{let e=await dd;return CT(e,s)}),3e4)}catch{return{}}}function CT(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Gr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(r);return JSON.parse(Buffer.concat([i,o.final()]))}function ct(s,e,t=AT,r=void 0){return async()=>{if(!ld)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await kT(e);if(o)return Ws.debug("cache hit:",{fnName:e}),o;if(Ws.debug("cache miss:",{fnName:e}),!ud)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await s();return i&&await OT(e,i,t),i}}async function kT(s){let t=(await lo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function OT(s,e,t){if(nc)throw Ws.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 lo;r[s]={value:e,expiry:Date.now()+t},pd=new Promise(n=>{ao=n}),PT(r)}catch{Ws.error("failed updating cache")}}async function fd(){let s=await lo;Object.keys(s).forEach(e=>{delete s[e]})}function gd(s){ld=s}function _T(s=!0){ud=s}async function hd(){try{return nc=!0,await pd}finally{nc=!1}}function yd(s){io=s,lo=md()}var no,oo,Gr,ad,Ws,io,cd,ao,ld,ud,nc,pd,dd,AT,co,lo,PT,bd,Td,DR,wd,qt=T(()=>{"use strict";no=E(require("fs")),oo=E(require("path")),Gr=E(require("crypto"));j();ad=require("lodash");B();Ws=x("local cache"),io=oo.resolve(at(),"testim-cache"),ld=!0,ud=!0,nc=!1,pd=new Promise(s=>{ao=s}),dd=new Promise(s=>{cd=s}),AT=1e3*60*60*3,co=()=>oo.resolve(oo.resolve(io,"testim.cache"));lo=md(),PT=(0,ad.debounce)(async s=>{let e;try{let t=await dd,r=Gr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Gr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(io)||await no.promises.mkdir(io,{recursive:!0}),await no.promises.writeFile(co(),a)}catch(t){Ws.error("failed saving cache",{err:t}),e=t}ao(e?{success:!1,error:e}:{success:!0})},200);bd=cd,Td=gd.bind(void 0,!1),DR=gd.bind(void 0,!0),wd=()=>_T(!1)});function uo(){return{cliLocation:at(),userInfo:Vr.userInfo(),platform:Vr.platform(),release:Vr.release()}}var Vr,oc=T(()=>{"use strict";Vr=E(require("os"));j()});function LT(s){try{return po.resolve(po.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 zt(s){let e=LT(s);return require(e)}var po,Gs=T(()=>{"use strict";po=E(require("path"))});async function Rd(s){return(await Ed(`npm view ${s} version`)).stdout.trim()}function ac(s){try{return zt(s)}catch{return!1}}function Id(s,e){return require(Hr.join(s,`./node_modules/${e}/package.json`)).version}async function fo(s,e,t){function r(c){let d=/EACCES[^']+'(.+)'/.exec(c.stderr);return d===null?!1:d[1]}function n(c){return/The "to" argument must be of type string./.exec(c.stderr)}let o=Hr.join(s,"npm-shrinkwrap.json"),i=Hr.join(s,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await ge(o)&&(await ic.promises.rename(o,i),a=!0)}catch{}return await Ed(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(c=>{let l=r(c),d=n(c);throw l||d?(Sd.info("Failed to install package due to insufficient write access",{...uo(),package:e,path:l||s}),console.error(`
|
|
4
4
|
|
|
5
5
|
Testim failed installing the package ${e} due to insufficient permissions.
|
|
6
6
|
This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
|
|
7
|
-
Testim had missing write access to ${l||
|
|
7
|
+
Testim had missing write access to ${l||s}
|
|
8
8
|
|
|
9
|
-
`),new
|
|
10
|
-
stdout: ${c} stderr: ${l}`}
|
|
9
|
+
`),new Fr(l||s)):c})}finally{if(a)try{await ic.promises.rename(i,o)}catch{}}}function xd(s,e,t,r){return new Promise((n,o)=>{let i=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",l="",d="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),m=(0,mo.spawn)("node",[DT,"i","--prefix",s,...d,...e,...i],a);m.stderr.pipe(process.stderr),m.stdout.pipe(process.stdout),m.stdout.on("data",p=>{c+=p}),m.stderr.on("data",p=>{l+=p}),m.on("close",p=>{var g;if(p){let f;try{let h=(g=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(l))==null?void 0:g[1];f=`404 Not Found - GET https://registry.npmjs.org/${h==null?void 0:h.split("@")[0]} - Not found`}catch{f=`Npm Install closed with exit code ${p}
|
|
10
|
+
stdout: ${c} stderr: ${l}`}Sd.debug(`Npm Install closed with exit code ${p}`,{message:f}),o(new wt(f))}else n(c)}),setTimeout(()=>{try{m.kill()}finally{o(new re)}},r)})}var ic,Hr,vd,mo,Ed,Sd,DT,Vs=T(()=>{"use strict";ic=E(require("fs")),Hr=E(require("path"));j();vd=require("util"),mo=require("child_process");B();oc();Gs();z();Ed=(0,vd.promisify)(mo.exec),Sd=x("cli-service");DT=Hr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var Od={};G(Od,{install:()=>NT,isReady:()=>FT,start:()=>UT});var Ad,Pd,Cd,kd,cc,MT,NT,UT,FT,_d=T(()=>{"use strict";Ad=E(require("fkill")),Pd=E(require("p-retry"));Vs();Ve();j();Gs();Cd="chromedriver",kd=9515,cc=`http://localhost:${kd}/wd/hub`,MT=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],NT=async()=>{await fo(at(),`${Cd} --detect_chromedriver_version`)},UT=async()=>{process.env.NODE_OPTIONS="",await(0,Ad.default)(`:${kd}`,{silent:!0}),await zt(Cd).start(MT,!0)},FT=async({chromeBinaryLocation:s})=>{await(0,Pd.default)(async()=>{var n;let e=await Ne(`${cc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await je({url:`${cc}/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(`${cc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var Hs={};G(Hs,{getSessionPlayerFolder:()=>dc,prepareChromeDriver:()=>gr,prepareCustomExtension:()=>uc,prepareExtension:()=>pc,preparePlayer:()=>hr});async function uc(s,e=!1){if(!s)return;if(Be(s)){let n=qr.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await BT(s)>lc&&!e)throw new P(Ld);return await He(s,n),n}let t=qr.resolve(s);if(!Md.existsSync(t))throw new P(`Failed to find custom extension in location: ${t}`);if(Ha(t)>lc&&!e)throw new P(Ld);return t}async function BT(s){let e=(Ve(),fe(Qe));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw ho.warn("failed to download custom extension",{err:t}),new P(`Failed to download custom extension from location: ${s}`)}}function pc(s){ho.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Xn(t)}));return ct(()=>ie(e,({location:t,path:r})=>Qn(t,r)),"prepareExtension",Ud,e)()}async function gr(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=await Promise.resolve().then(()=>(_d(),Od));try{await o.install(),await o.start(),t||await o.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(i){let a="Failed to initiate Chrome Driver";throw i instanceof Fr||(ho.error(a,{...s,...uo(),error:(0,Nd.serializeError)(i)}),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),i}}async function XT(){let r=`${_r}/extension/sessionPlayer_LATEST_RELEASE`;return(await _t(r)).body.toString("utf8")}async function QT(r,e){if(!je(r)||je(r)&&e||ke)return r;let t=await XT();return`${r}-${t}`}function wc(){let r=lt();return zr.resolve(r,"testim-bin")}function ZT(){let r=wc();return zr.resolve(r,"sessionPlayer.zip")}async function Wd(r,e,t=!1){try{return await eo(r,e),await et(e,wc())}catch(s){if(t)throw s;return await Wd(r,e,!0)}}async function yr(r,e){bo.info("prepare player",{location:r,canary:e});let t=ZT();return ut(async()=>{let s=await QT(r,e);return await Wd(s,t),{}},"preparePlayer",$d,[r,e,t])()}var Ud,jd,zr,Bd,bo,$d,yc,Fd,Kr=T(()=>{"use strict";Ud=E(require("ms")),jd=E(require("fs")),zr=E(require("path"));le();Gt();Bd=require("serialize-error");$();mc();z();B();bo=A("prepare runner and testim start"),$d=(0,Ud.default)("0.5 day"),yc=16,Fd=`The size of the custom extension is more than ${yc}MB`});function ew(){let r=qs.type().toLowerCase();return r==="darwin"?qs.arch()==="arm"?"mac_arm":"mac":r==="windows_nt"?qs.arch()==="x64"?"win64":"win32":"linux"}async function wo(){let r=ew(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(r in t))throw new P(`Unsupported platform: ${r}`);let s=parseInt(zs,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:s,win64:s},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[r]}/${zs}/${n[r]}.zip`,a=To.join(vc,n[r]),c=`${a}.zip`,l=To.join(a,o[r]);if(await ge(l))return l;if(!await ge(c)){let d=(0,Ec.default)("Downloading Chromium").start();try{await Vd.promises.mkdir(vc),await qe(i,c)}catch(m){let g=`Failed to download Chromium: ${m.message}`;throw d.fail(g),new Error(g)}d.succeed()}let p=(0,Ec.default)("Extracting Chromium").start();try{await et(c,vc)}catch(d){let m=`Failed to extract Chromium: ${d.message}`;throw p.fail(m),new Error(m)}return p.succeed(),l}var Vd,qs,To,Ec,zs,vc,Sc=T(()=>{"use strict";Vd=E(require("fs")),qs=E(require("os")),To=E(require("path")),Ec=E(require("ora"));z();B();zs="1000968",vc=To.join(Dt,`chrome-${zs}`)});async function Hd(r,e){return Eo=r,Ac=e,await Rc()}function qd(r,e,t){rt=r.token,Eo=e,Ac=t,Js=Pc(rt),vo=r.refreshToken,Ic=r.ngrokToken,xc=r.isNgrokWhitelisted}function tw(r=Eo,e=Ac){return ut(()=>(Ks.info("request to get cli token from server"),Be({url:`${me}/auth/token`,body:{projectId:r,token:e}})),"getTokenV3",Gd*10,{projectId:r,token:e})()}async function rw(){return Ks.info("request to refresh JWT cli token from server"),rt=(await Be({url:`${me}/auth/refreshToken`,body:{token:rt,refreshToken:vo}})).token,Js=Pc(rt),rt}async function Rc(){try{let r=await tw();return Ks.info("successfully get cli token from server"),rt=r.token,Js=Pc(rt),vo=r.refreshToken,Ic=r.ngrokToken,xc=r.isNgrokWhitelisted,rt}catch(r){throw r.message.includes("Unauthorized")?new P("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."):(Ks.error(`While trying to retrieve CLI token. caught error: ${r}`,{projectId:Eo}),new P(`While trying to retrieve CLI token, caught error: ${r}`))}}function Pc(r){return require("jsonwebtoken").decode(r).exp*1e3}async function qt(){if(!Js)return Rc();if(Js<Date.now()+4*Gd)try{return await rw()}catch(r){return Ks.error("failed to refresh token, executing fallback",r),Rc()}return rt}function So(){return vo}function Mt(){return rt?{uid:require("jsonwebtoken").decode(rt).id,ngrokToken:Ic,isNgrokWhitelisted:xc}:{}}var Ks,rt,Js,vo,Ic,xc,Eo,Ac,Gd,xt=T(()=>{"use strict";le();He();Gt();z();$();Ks=A("testim-custom-token"),Eo=null,Ac=null,Gd=5*60*1e3});var zd={};W(zd,{isCi:()=>Jr});var Jr,Ro=T(()=>{"use strict";Jr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Le={};W(Le,{addTestRetry:()=>Qc,clearTestResult:()=>Jc,deleteCloudflareTunnel:()=>rl,fetchLambdatestConfig:()=>zc,forceUpdateCloudflareTunnelRoutes:()=>tl,getAllGrids:()=>qc,getAppDetails:()=>Uc,getApplitoolsIntegrationData:()=>Zc,getCloudflareTunnel:()=>el,getEditorUrl:()=>lw,getGridById:()=>Ao,getGridByName:()=>Gc,getHybridGridProvider:()=>Vc,getLabFeaturesByProjectId:()=>Kc,getMobileDevicesFromGrid:()=>nl,getRealData:()=>Xs,getS3Artifact:()=>Ys,getS3ArtifactText:()=>kc,getSuiteTestList:()=>Fc,getTestPlan:()=>cw,getTestPlanTestList:()=>Nc,getTestResults:()=>br,getUsageForCurrentBillingPeriod:()=>jc,initializeUserWithAuth:()=>Hc,isTestResultCompleted:()=>Bc,keepAliveGrid:()=>$c,loadSfdcCredential:()=>Oc,loadTest:()=>_c,releaseGridSlot:()=>Wc,reportExecutionFinished:()=>xo,reportExecutionStarted:()=>Mc,saveRemoteStep:()=>Yc,saveTestPlanResult:()=>Lc,updateExecutionTests:()=>Dc,updateRemoteRunFailure:()=>sl,updateTestDataArtifact:()=>Co,updateTestResult:()=>Po,updateTestStatus:()=>Xr,uploadAppToBrowserStack:()=>ol,uploadRunDataArtifact:()=>Xc});async function Yr(){let r=await qt();if(!r)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${r}`}}async function Je({url:r,body:e,headers:t={},timeout:s,retry:n}){let o=await Yr(),i=Object.assign({},t,o);return Be({url:`${me}${r||""}`,body:e,headers:i,timeout:s,retry:n})}async function ow(r,e,t,s={},n=void 0){let o=await Yr(),i=Object.assign({},s,o);return await Ls(`${me}${r||""}`,e,t,i,n)}async function Io(r,e){let t=await Yr();return await Ka(`${me}${r||""}`,e,t)}async function iw(r,e){let t=await Yr();return await _s(`${me}${r||""}`,e,t)}async function aw(r,e){let t=await Yr();return await za(`${me}${r||""}`,e||void 0,t)}async function Ie(r,e,t,s){let n=await Yr();return await $e(`${me}${r||""}`,e||void 0,n,s,t)}function Ys(r,e){return(0,Z.default)(()=>Ie(`/storage${r}`,null,{isBinary:!0},e),{retries:ne,factor:1})}function kc(r){return(0,Z.default)(()=>aw(`/storage${r}`))}async function cw(r,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Z.default)(()=>Ie("/testPlan",{projectId:r,name:e.join(",")}),{retries:ne,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function Oc({branch:r,projectId:e}){let t=await(0,Z.default)(()=>Ie(`/branch/branchData/${r}`,{projectId:e}),{retries:ne,factor:1});return t==null?void 0:t.sfdcCredential}function _c({testId:r,branch:e,projectId:t,skipSharedSteps:s=!1,useBranchMap:n=!0}){return(0,Z.default)(()=>Ie(`/test/${r}`,{projectId:t,branch:e,skipSharedSteps:s,useBranchMap:n}),{retries:ne,factor:1})}function Lc(r,e,t){return(0,Z.default)(()=>Je({url:"/testPlan/result",body:{projectId:r,testPlanId:e,result:t}}),{retries:ne,factor:1})}function Xr(r,e,t,s,n,o,i=ne){return(0,Z.default)(()=>Io("/result/run/test",{runId:e,testId:t,resultId:s,status:n,projectId:r,runnerVersion:sw,...o}),{retries:i,factor:1})}function Dc(r,e,t,s,n,o,i,a){return(0,Z.default)(()=>Io("/result/run/tests",{runId:r,runnerStatuses:e,status:t,reason:s,success:n,startTime:o,endTime:i,projectId:a}),{retries:ne,factor:1})}async function Mc({executionId:r,projectId:e,labels:t,startTime:s,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:p}){let{isCi:d}=await Promise.resolve().then(()=>(Ro(),zd));return Je({timeout:9e4,url:"/result/run",body:{runId:r,projectId:e,labels:t,startTime:s,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:p,metadata:{isCiRun:d,localRunUserId:c,isLocalRun:l}},retry:3})}function xo(r,e,t,s,n={},o=void 0,i=void 0){let a=Date.now();return(0,Z.default)(()=>Io("/result/run",{runId:e,projectId:t,endTime:a,status:r,success:s,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ne,factor:1})}async function Nc(r,e,t,s,n){return(0,Z.default)(()=>Je({url:"/testPlan/list",body:{projectId:r,names:e,planIds:t,branch:s,intersections:n},timeout:12e4}),{retries:ne,factor:1})}function Fc({projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:p}){return(0,Z.default)(()=>Je({url:"/suite/v2/list",body:{projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:p}}),{retries:ne,factor:1})}async function Uc({appId:r,projectId:e}){try{return await(0,Z.default)(()=>Ie(`/mobile-app/app/${r}?projectId=${e}`),{retries:ne,factor:1})}catch(t){Ft.error("failed getting application details",{appId:r,error:t});return}}async function jc(r){try{return await(0,Z.default)(()=>Ie(`/plan/project/${r}/usage-current-billing-period`),{retries:ne,factor:1})}catch(e){Ft.error("failed getting usage for current billing period",{projectId:r,error:e});return}}function Bc(r,e,t){return(0,Z.default)(()=>Ie(`/result/${r}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ne,factor:1})}function br(r,e,t,s){return(0,Z.default)(()=>Ie(`/test/v2/${r}/result/${e}`,{projectId:t,branch:s}),{retries:ne,factor:1})}function $c(r,e){return Je({url:`/grid/keep-alive?reqId=${te()}`,body:{projectId:r,slots:e},timeout:1e4})}function Wc(r,e,t,s,n){return Je({url:`/grid/release?reqId=${te()}`,body:{companyId:r,projectId:e,slotId:t,gridId:s,browser:n}})}function Vc(r){return Je({url:"/grid/hybrid/provider",body:r})}function Gc(r,e,t,s,n){return(0,Z.default)(()=>Ie("/grid/name",{companyId:r,projectId:e,name:t,browser:s,executionId:n,reqId:te()}),{retries:ne,factor:1})}function Ao(r,e,t,s,n){return(0,Z.default)(()=>Ie(`/grid/${t}`,{companyId:r,projectId:e,browser:s,executionId:n,reqId:te()}),{retries:ne,factor:1})}async function Hc({projectId:r,token:e,branchName:t,lightweightMode:s,localGrid:n}){var o,i;try{return await(0,Z.default)(()=>Be({url:`${me}/executions/initialize`,body:{projectId:r,token:e,branchName:t||"master",lightweightMode:s,localGrid:n}}),{retries:ne,factor:1})}catch(a){throw Ft.error("error initializing info from server",a),(o=a==null?void 0:a.message)!=null&&o.includes("Bad Request")?new P("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."):(i=a==null?void 0:a.code)!=null&&i.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):a}}async function lw(){if(Or)return{editorUrl:Or};try{return await(0,Z.default)(()=>Ie("/system-info/editor-url"),{retries:ne,onFailedAttempt:r=>{if(r.attemptNumber>=ne)throw r},factor:1})}catch{return Ft.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function qc(r){return(0,Z.default)(()=>Ie("/grid",{companyId:r}),{retries:ne,factor:1})}function Xs(r,e,t){return(0,Z.default)(()=>Ie(`/real-data/${e}?${t}&projectId=${r}`),{retries:ne,factor:1})}function Po(r,e,t,s,n){return(0,Z.default)(()=>Je({url:"/result/test",body:{projectId:r,resultId:e,testId:t,testResult:s,remoteRunId:n}}),{retries:ne,factor:1})}function Jc(r,e,t,s){return(0,Z.default)(()=>Je({url:"/result/test/clear",body:{projectId:r,resultId:e,testId:t,testResult:s}}),{retries:ne,factor:1})}function Yc(r,e,t,s){return(0,Z.default)(()=>Je({url:"/remoteStep",body:{projectId:r,resultId:e,stepId:t,remoteStep:s}}),{retries:ne,factor:1})}function uw(r){return r.startsWith("/")?r:`/${r}`}function pw(r,e,t){let s=uw(r);return t&&(s=`/${t}${s}`),e&&(s=`/${e}${s}`),s}async function Jd(r,e,t,s,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${te()}${i||""}`,c=`${e}/${t}/${a}`,l=pw(c,"test-result-artifacts",r),p=Buffer.from(Kd.gzip(s,{level:3})),d={file:{fileName:a,buffer:p}};return await(0,Z.default)(()=>ow(`/storage${l}`,{},d,{"X-Asset-Encoding":"gzip"}),{retries:ne,factor:1}),l}function Qc({projectId:r,runId:e,testId:t,newResultId:s,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,Z.default)(()=>Je({url:"/result/test/retry",body:{projectId:r,newResultId:s,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ne,factor:1})}async function Zc(r){try{return await Ie(`/integration/applitools/v3/connected?projectId=${r}`)}catch(e){return Ft.warn("could'nt get applitools integration data.",{err:e}),{}}}async function el(r,e){try{return await Io("/tunnel",{companyId:r,routes:e})}catch(t){return Ft.warn("could'nt get tunnel.",{err:t}),{}}}async function tl(r,e){try{return await Je({url:`/tunnel/${e}`,body:{companyId:r}})}catch(t){Ft.warn("could'nt get tunnel.",{err:t});return}}async function rl(r,e){try{return await iw(`/tunnel/${e}`,{companyId:r})}catch(t){Ft.warn("could'nt get tunnel.",{err:t});return}}function sl(r){return Be({url:`${me}/result/remoteRunFailure`,body:r})}async function nl({projectId:r,projectType:e,gridId:t,companyId:s,selectors:n}){let o=`${nw}/mobileDevices/${t}/${s}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,Z.default)(()=>Ie(o,{projectId:r}),{retries:ne,factor:1})}catch(i){return Ft.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function ol({projectId:r,gridId:e,app:t,timeout:s}){return(0,Z.default)(()=>Je({url:`/mobile-app/app/upload-to-grid?projectId=${r}&gridId=${e}`,body:t,timeout:s}),{retries:ne,factor:1})}var zt,Kd,Z,Cc,sw,Ft,ne,nw,zc,Kc,Xc,Co,be=T(()=>{"use strict";zt=E(require("lodash")),Kd=E(require("pako"));B();le();ce();He();xt();Z=E(require("p-retry")),Cc=E(require("object-hash"));z();$();sw=ct(),Ft=A("testim service api"),ne=3,nw="/grid";zc=async()=>(0,Z.default)(()=>Ie("/grid/lt/config"),{retries:ne,factor:1}),Kc=async r=>(0,Z.default)(()=>Ie(`/labFeature/v2/project/${r}`),{retries:ne,factor:1});Xc=zt.memoize(async(r,e,t,s)=>{if(!zt.isEmpty(s))return await Jd(r,e,t,JSON.stringify(s),"test-run-data","application/json")},(r,e,t,s)=>`${(0,Cc.default)(s)}:${e}:${t}`),Co=zt.memoize(async(r,e,t,s,n)=>!s||zt.isEmpty(s)?void 0:await Jd(r,e,t,JSON.stringify((()=>{let i=zt.clone(s);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&Object.assign(i,{[c]:rc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(r,e,t,s)=>`${(0,Cc.default)(s)}:${e}:${t}`)});var Kt={};W(Kt,{getSessionPlayer:()=>ee,options:()=>al});var ko,al,il,ee,Te=T(()=>{"use strict";ko=require("path"),al={playerPath:void 0},ee=()=>{if(il)return il;let r=(Ue(),fe(Fe));r.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Kr(),fe(Hs)),t=e(),s=al.playerPath?(0,ko.resolve)(al.playerPath,"src/background/sessionPlayerInit.ts"):(0,ko.join)(t,"sessionPlayer.js"),n=require(s);return r.log("getSessionPlayerRequire end"),il=n,n}});function fw(r){process.nextTick(()=>{if([Q.SELENIUM,Q.APPIUM].includes(r))try{(Te(),fe(Kt)).getSessionPlayer(),require("jsdom")}catch{}})}async function Qs(r){let{project:e,token:t,lightweightMode:s,useLocalChromeDriver:n,useChromeLauncher:o,mode:i}=r,a=Boolean(s==null?void 0:s.general),c=Boolean(n||o),l=a?mw:dw;D("before initializeUserWithAuth");let p=await ut(async()=>(fw(i),await Hc({projectId:e,token:t,branchName:r.branch,lightweightMode:s,localGrid:c})),"initializeUserWithAuth",l,{project:e,token:t,branchName:r.branch,lightweightModeGeneral:a,localGrid:c})();return D("after initializeUserWithAuth"),qd(p.authData,r.project,r.token),p}var dw,mw,Yd=T(()=>{"use strict";Ue();be();Gt();xt();ce();dw=1e3*60*5,mw=1e3*60*60*10});async function Zd(r){var o;let e=Promise.resolve(),t=!r.host&&!r.gridId&&!r.grid&&(!r.testPlan||r.testPlan.length===0),s=r.files.length!==0;(t&&s||r.useLocalChromeDriver)&&(r.chromeBinaryLocation=r.downloadBrowser?await wo():r.chromeBinaryLocation,e=hr({projectId:r.project,userId:r.user},{chromeBinaryLocation:r.chromeBinaryLocation},Boolean((o=r.lightweightMode)==null?void 0:o.general)),r.useLocalChromeDriver=!0),!r.playerRequirePath&&r.mode!==Q.EXTENSION&&await yr(r.playerLocation,r.canary),r.mode===Q.EXTENSION&&!r.ext&&await Tc(r.extensionLocation);let n;if(r.installCustomExtension){let i=Boolean(r.useLocalChromeDriver||r.useChromeLauncher);n=await bc(r.installCustomExtension,i)}return await e,n}async function em(r){var i;gw.info("prepare MockNetwork",{location:r});let e=await Qa(r),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Xd*1e6)throw new Error(`${cl} exceeded ${Xd}MB`);let s;try{s=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${cl} cannot be parsed.${Oo.EOL}${a}`)}let n=new Qd.default;if(!n.validate(pc,s)){let a=(i=n.errors)==null?void 0:i.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Oo.EOL);throw new Error(`${cl} is malformed.${Oo.EOL}${a}`)}return s.entries}var Oo,Qd,Xd,cl,gw,ll=T(()=>{"use strict";Oo=E(require("os"));B();ud();Kr();Qd=E(require("ajv"));ce();Sc();Yd();Xd=1,cl="JSON file supplied to --mock-network-pattern",gw=($(),fe($a)).getLogger("prepare runner")});function rm(r,e=process){async function t(s){await ie(ae(tm,async n=>n()),1e4).catch(()=>null),r(s)}e.on("uncaughtException",async s=>{Zs.error("Caught exception",{err:s}),console.log("Uncaught exception"),s.message&&console.log("Message =",s.message),s.reason&&console.log("Reason =",s.reason),await t(s)}),e.on("unhandledRejection",s=>{var n;if(Zs.fatal("Caught unhandled promise rejection",s),!((n=s==null?void 0:s.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw s}),e.on("rejectionHandled",()=>{Zs.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let s="Runner aborted - SIGTERM event",n=new Error(s);throw Zs.error(s),t(n),n}),e.once("SIGINT",()=>{let s="Runner aborted - SIGINT event",n=new Error(s);throw Zs.error(s),t(n),n}),e.once("exit",s=>{r(s)})}function Qr(r){tm.push(r)}var Zs,tm,en=T(()=>{"use strict";$();B();Zs=A("process-handler"),tm=[]});function ml(r,e){let t=r.canary?"-master.zip":".zip",s=`${e?Mp:_r}/extension/testim-firefox-profile${t}`,n=`${e?Np:_r}/extension/testim-headless${t}`;return{firefox:s,chrome:n,"edge-chromium":n}}function am(r){let{chrome:e,firefox:t}=ml(r,!1);return r.browser==="firefox"?t:r.browser==="chrome"?e:[e,t]}function Lo(r){let e=`${_r}/extension/sessionPlayer`;return r.canary?`${e}-master`:e}var Do=T(()=>{"use strict";le()});function dm(r){ke||(r!=null&&r.userId||(r={anonymousId:pm}),um.identify(r))}function pt(r,e){return tn("ci",r,e)}function tn(r,e,t){if(ke)return;let s=r?{userId:r}:{anonymousId:pm};um.track(Object.assign(s,{event:e,properties:t}))}var lm,um,pm,Zr=T(()=>{"use strict";le();lm=E(require("analytics-node")),um=new lm.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),pm=require("crypto").randomBytes(20).toString("hex")});function mm(r){return r.start&&tn(null,"cli-start-command",{downloadBrowser:Boolean(r.downloadBrowser)}),!!(r.startV2||r.start||r.agent)}async function fm(r){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,s=!1,n=!1,o=!1;if(r.start&&(o=!0),Number.isNaN(r.agentPort))throw new P("Agent port is not number");if(typeof r.agent=="string"&&e.some(a=>r.agent.includes(a))){let a=r.agent.split(",").map(c=>c.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(s=!0),a.includes("playground-selenium")&&(n=!0)}let i=Lo(r);return console.log("Start Testim CLI on Agent mode"),{project:r.project,token:r.token,agentMode:!0,agentPort:r.agentPort,agentBind:r.agentBind,openEditor:r.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:s,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:r.ext,extensionPath:r.extensionPath,playerLocation:r.playerPath||i,canary:r.canary,playerPath:r.playerPath,playerRequirePath:r.playerRequirePath,downloadBrowser:Boolean(r.downloadBrowser)}}var gm=T(()=>{"use strict";Do();Zr();z()});function No(r){let{platform:e}=process;e==="win32"?(0,Mo.exec)(`start chrome ${r}`):e==="darwin"?(0,Mo.exec)(`open -a "Google Chrome" ${r}`):e==="linux"&&(0,Mo.exec)(`google-chrome ${r}`)}var Mo,fl=T(()=>{"use strict";Mo=require("child_process")});var sn={};W(sn,{doLogin:()=>bl,getProjectId:()=>Ew,getToken:()=>Sw});async function Ew(){return bm("projectId")}async function Sw(){return bm("token")}function ym(r,e){return Promise.race([r,se(e).then(()=>{throw new re("timeout")})])}async function Rw(){let r=(await import("express")).default(),e=async function(){return ym(new Promise(n=>{r.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((s,n)=>{let o=r.listen(42543,i=>{i&&n(i),s(o.address().port)})});try{let{getEditorUrl:s}=await Promise.resolve().then(()=>(be(),Le)),{editorUrl:n}=await s();No(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function bl({overwriteExisting:r=!0,projects:e=null}={}){let t=gl.homedir(),s=hl.join(t,".testim");if(await ge(s)&&!r)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await ym(Rw(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await hm(s,o);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await i({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(p=>({title:p.name,value:p}))});o.token=l.project.ci.token,o.projectId=l.project.id,await hm(s,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function hm(r,e){await yl.promises.writeFile(r,Fo.stringify(e)),console.log(`Testim credentials saved in '${r}'`)}async function bm(r){let e=gl.homedir(),t=hl.join(e,".testim"),s=await ge(t),n={};if(s)try{n=Fo.parse((await yl.promises.readFile(t)).toString())}catch{}return n||={},n[r]}var gl,hl,Fo,yl,es=T(()=>{"use strict";gl=E(require("os")),hl=E(require("path")),Fo=E(require("yaml"));B();yl=require("fs");z();fl()});var Rm={};W(Rm,{process:()=>Lw});var Tl,wm,wl,vm,dt,De,Em,Iw,xe,El,xw,Aw,Tm,Sm,Pw,vl,jo,Sl,Cw,Uo,At,kw,u,Ow,_w,Lw,Im=T(()=>{"use strict";Tl=E(require("ms")),wm=E(require("chalk")),wl=E(require("fs")),vm=E(require("url")),dt=E(require("lodash")),De=E(require("path"));B();Do();gm();Gt();Em=require("commander");ce();z();kr();B();Iw=r=>r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),xe=(r,e)=>(e.push(r),e),El=new Em.Command,xw=r=>r.split(","),Aw=(r,e)=>!r||r.length===0?e:r,Tm=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Sm=()=>{function r(f){return f.includes("-h, --help")}function e(f){return f.includes("--params [params-json-string]")}function t(f){return f.includes("--ext")||f.includes("--extension-path")}function s(f){return f.includes("--player-path")||f.includes("--player-require-path")}function n(f){return f.includes("--executionId")||f.includes("--source")||f.includes("--resultId")||f.includes("--remoteRunId")||f.includes("--schedulerId")}function o(f){return f.includes("--get-browser-timeout")||f.includes("--get-browser-retries")||f.includes("--get-session-timeout")||f.includes("--get-session-retries")||f.includes("--driver-request-timeout")||f.includes("--driver-request-retries")}function i(f){return f.includes("--user")}function a(f){return f.includes("shouldMonitorPerformance")}function c(f){return f.includes("--save-rca-locally")}function l(f){return f.includes("--exit-code-ignore-failing-tests")}function p(f){return f.includes("--high-speed")}function d(f){return f.includes("--urls")}function m(f){return f.includes("--test-start-timeout")}function g(f){return f.includes("--install-lazy-deps")}El.help(f=>f.split(`
|
|
17
|
-
`).filter(y=>!t(y)&&!e(y)&&!
|
|
18
|
-
`))},
|
|
19
|
-
WARNING: ${
|
|
20
|
-
`))},vl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:jo,argv:Sl,stdout:Cw,exit:Uo,cwd:At}=global.process,kw=["trace","debug","info","warn","error","silent"];oc(Sl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));El.description("Testim.io CLI").option("--run [file-glob-pattern]","codeful test files to run",xe,[]).option("-h --help","output usage information",Sm).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",xe,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",xe,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",xe,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",xe,[]).option("-l, --label [label]","labels to search test by",xe,[]).option("-n, --name [test-name]","test name to run",xe,[]).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",xw).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--is-regression-baseline-run","save doms and run results as regression baseline data").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",xe,[]).option("--test-plan-id [test-plan-id]","test plan to run",xe,[]).option("--suite [suite-name]","suite to run",xe,[]).option("--suite-id [suite-id]","suite ID to run",xe,[]).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",xe,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("-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("-rad --reset-app-data [reset-app-data]","set noReset appium capability to false, noReset capability is true by default",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(jo.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,Tl.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,Tl.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: ${vl.join("/")}`,xe,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",xe,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",xe,[]).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)",xe,[]).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)",xe,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(Sl);u=El.opts(),Ow=()=>{u.grid||u.gridId||(u.host||(u.host="ondemand.saucelabs.com"),u.port||(u.port=80))},_w=()=>{u.grid||u.gridId||(u.host||(u.host="hub-cloud.browserstack.com"),u.port||(u.port=80))},Lw=async()=>{var y,v,S,b,w,x,k,O,j;u.inspect&&require("inspector").open(u.inspect);let r={},e={},t=[],s={};if(!Sl.slice(2).length)throw Sm(),new Dr;if(u.requireCredentials){let R=await Promise.resolve().then(()=>(es(),sn)),I=await R.getProjectId(),L=await R.getToken();(!I||!L)&&await R.doLogin()}if(u.login)return await(await Promise.resolve().then(()=>(es(),sn))).doLogin(),{loginMode:!0};if(u.version){let R="Testim CLI Version: ";jo.npm_package_version&&(console.log(R,jo.npm_package_version),Uo(0));let I=ct();I&&(console.log(R,I),Uo(0)),console.log("Could not find version, please check the package.json manually"),Uo(0)}if(u.installLazyDeps)return{installLazyDepsMode:!0};u.disableFileCache&&Sd();let n=u.fileCacheLocation||u.usePrefechedData||u.createPrefechedData;if(n){let R=De.resolve(n);vd(R)}if(u.usePrefechedData&&Rd(),u.playerRequirePath){let R=De.resolve(u.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let I=De.join(R,"tsconfig.node.json"),F=require("ts-node").register({project:I,ignore:[/node_modules/,new RegExp(`^${dt.escapeRegExp(De.relative(At(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:F.config.options.paths,baseUrl:F.config.options.baseUrl}),(Te(),fe(Kt)).options.playerPath=R;let Y=require("module"),X=Y.prototype.require;Y.prototype.require=function(yt){return yt==="rox-alias"?X.call(this,"rox-node"):X.apply(this,arguments)}}if(u.caFile&&(global.caFileContent=wl.readFileSync(u.caFile)),u.proxy&&(global.proxyUri=u.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),u.proxyForGrid&&!u.proxy)throw new P("missing --proxy option");if(mm(u))return fm(u);try{let R={};u.configFile?R=require(De.join(At(),u.configFile)).config:u.optionsFile&&(R=require(De.join(At(),u.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(I=>{let L=Iw(I);u[L]=Aw(u[L],R[I])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(u.tunneld)return{tunnel:!0,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:u.token,project:u.project};let o=((y=u.testConfig)==null?void 0:y.length)||((v=u.testConfigId)==null?void 0:v.length),i=((S=u.testPlan)==null?void 0:S.length)||((b=u.testPlanId)==null?void 0:b.length),a=((w=u.suite)==null?void 0:w.length)||((x=u.suiteId)==null?void 0:x.length);if(u.seleniumCapsFile)try{s=require(De.join(At(),u.seleniumCapsFile))}catch(R){throw new P(`Failed to parse selenium caps file file error: ${R.message}`)}if((k=u.reporters)!=null&&k.includes("junit")&&!u.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!u.tunnel&&u.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!u.tunnel&&u.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!u.tunnel&&[u.tunnelPort,u.tunnelHostHeader,u.tunnelRegion,u.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(u.chromeExtraPrefs)try{e=require(De.join(At(),u.chromeExtraPrefs))}catch(R){throw new P(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(u.chromeExtraArgs){let R=u.chromeExtraArgs.split(",");for(let I of R){let[L]=I.split("=");Tm.includes(L)||u.useLocalChromeDriver||u.useChromeLauncher?(t.push(I),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(Tm)}`)}}if(u.paramsFile)try{r=Object.assign({},r,require(De.join(At(),u.paramsFile)))}catch(R){throw new P(`Failed to read/open params file error: ${R.message}`)}if(u.params)try{r=Object.assign({},r,JSON.parse(u.params))}catch(R){throw new P(`Failed to parse params string error: ${R.message}`)}if(u.sauceUser&&!u.sauceKey||!u.sauceUser&&u.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(u.sauceUser&&u.sauceKey&&(Ow(),u.saucelabs={},u.saucelabs.username=u.sauceUser,u.saucelabs.accessKey=u.sauceKey),u.sauceOptions)try{let R=require(De.join(At(),u.sauceOptions)),I=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let F=R.browserName.toLowerCase();switch(F){case"microsoftedge":u.browser="edge";break;default:u.browser=F}}u.browser==="edge"&&parseFloat(R.version)>=Pa&&(u.browser="edge-chromium");let L=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!I&&u.browser==="chrome"&&L)throw new P("The minimum chrome supported version is 50.0");u.saucelabs=Object.assign({},u.saucelabs,R)}catch(R){throw new P(`Failed to parse saucelabs options file error: ${R.message}`)}if(u.browserstackUser&&!u.browserstackKey||!u.browserstackUser&&u.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(u.browserstackUser&&u.browserstackKey&&(_w(),u.browserstack={},u.browserstack["browserstack.user"]=u.browserstackUser,u.browserstack["browserstack.key"]=u.browserstackKey),u.browserstackOptions)try{let R=require(De.join(At(),u.browserstackOptions)),I=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(u.browser=R.browserName.toLowerCase()),u.browser==="edge"&&parseFloat(R.browser_version)>=Pa&&(u.browser="edge-chromium"),!I&&parseFloat(R.browser_version)<50&&u.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");u.browserstack=Object.assign({},u.browserstack,R)}catch(R){throw new P(`Failed to parse browserstack options file error: ${R.message}`)}if(u.perfecto={},u.perfectoToken&&(u.perfecto.securityToken=u.perfectoToken),u.perfectoOptions)try{let R=require(De.join(At(),u.perfectoOptions)),I={location:"US East",securityToken:u.perfectoToken};u.perfecto=Object.assign({},I,R)}catch(R){throw new P(`Failed to parse perfecto options file error: ${R.message}`)}if(u.testobjectSauce={},u.testobjectKey&&(u.testobjectSauce.testobjectApiKey=u.testobjectKey),u.testobjectOptions)try{let R=require(De.join(At(),u.testobjectOptions)),I={testobjectApiKey:u.testobjectKey};u.testobjectSauce=Object.assign({},I,R)}catch(R){throw new P(`Failed to parse test object options file error: ${R.message}`)}if(!u.project){let I=await(await Promise.resolve().then(()=>(es(),sn))).getProjectId();if(I)u.project=I;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}u.testConfig&&(u.testConfig=[u.testConfig].flat()),u.testConfigId&&(u.testConfigId=[u.testConfigId].flat()),u.mode??="extension",u.retries=!u.retries||typeof u.retries=="boolean"?1:Number(u.retries)+1,u.browserTimeout=!u.browserTimeout||typeof u.browserTimeout=="boolean"?60*1e3:u.browserTimeout,u.newBrowserWaitTimeout=!u.newBrowserWaitTimeout||typeof u.newBrowserWaitTimeout=="boolean"?10*60*1e3:u.newBrowserWaitTimeout*60*1e3,u.getBrowserTimeout||(u.getBrowserTimeout=u.browserTimeout),u.getBrowserRetries||(u.getBrowserRetries=u.mode===Q.APPIUM?1:Math.round(u.newBrowserWaitTimeout/u.browserTimeout)),u.getSessionTimeout=u.browserTimeout<u.getSessionTimeout?u.getSessionTimeout:u.browserTimeout,u.driverRequestTimeout=u.browserTimeout<u.driverRequestTimeout?u.driverRequestTimeout:u.browserTimeout;let c=Boolean(u.timeout);if(u.timeout=!u.timeout||typeof u.timeout=="boolean"?10*60*1e3:u.timeout,u.beforeParallel=!u.beforeParallel||typeof u.beforeParallel=="boolean"?1:Number(u.beforeParallel),u.parallel=!u.parallel||typeof u.parallel=="boolean"?1:Number(u.parallel),u.afterParallel=!u.afterParallel||typeof u.afterParallel=="boolean"?1:Number(u.afterParallel),u.parallel>1&&u.run&&!u.gridId&&!u.grid&&(!u.testPlan||u.testPlan.length===0)&&!((O=u.testPlanId)!=null&&O.length)&&Cw.isTTY&&!u.headless&&!jo.TERM&&((await require("prompts")({type:"toggle",name:"isSure",message:"Running in parallel without --headless flag will open several browsers on your computer. Are you sure?",initial:!1,active:"yes",inactive:"no"})).isSure||Uo(0)),u.tunnelPort=!u.tunnelPort||typeof u.tunnelPort=="boolean"?"80":u.tunnelPort,u.port&&=Number(u.port),!u.token){let I=await(await Promise.resolve().then(()=>(es(),sn))).getToken();if(I)u.token=I;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let l=R=>R<=0||!Number.isInteger(R);if(l(u.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(u.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(l(u.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(l(u.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(l(u.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(l(u.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(l(u.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(l(u.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Q.EXTENSION,Q.SELENIUM,Q.APPIUM].includes(u.mode))throw new P(`runner mode <${u.mode}> is not supported`);if(u.mode!==Q.SELENIUM&&u.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!u.browser&&!o&&!i&&(u.browser="chrome"),u.appiumLogLevel||(u.appiumLogLevel="silent"),!kw.includes(u.appiumLogLevel))throw new P(`runner appium-log-level <${u.appiumLogLevel}> is not supported`);if(u.testPlan&&u.testPlan.length===0&&u.testPlanId&&u.testPlanId.length===0){if(typeof u.host!="string"&&typeof u.grid!="string"&&typeof u.gridId!="string"&&u.run.length===0&&!u.localTmaUrl&&!u.useLocalChromeDriver&&!u.useChromeLauncher&&!u.createPrefechedData)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(u.testId.length||u.label.length||u.name.length||o||u.browser||a||u.localTmaUrl||u.useLocalChromeDriver||u.useChromeLauncher)throw new P("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(u.beforeParallel!==1||u.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if((u.testId.length||i||u.label.length||u.name.length||a)&&u.file)throw new P("Cannot pass codeful automation tests with --testId --label --name or --suite");if([u.host,u.grid,u.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((j=u.host)!=null&&j.includes("/")&&(/^(f|ht)tps?:\/\//i.test(u.host)||(u.host=`http://${u.host}`),u.host=vm.parse(u.host).hostname),u.resultLabel.length){u.resultLabel=u.resultLabel.map(I=>I.trim()).filter(Boolean);let R=u.resultLabel.filter(I=>I.length>=250).filter(Boolean);if(u.branch==="auto-detect"&&u.resultLabel.includes("auto-detect-branch")&&mr()&&u.resultLabel.unshift(mr()),R.length)throw new P("A result label cannot exceed 250 characters")}let d=am(u),m=Lo(u);if(!u.w3cCapabilities&&!u.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(u.protocol||=u.port===443?"https":"http",!["http","https"].includes(u.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(u.rerunFailedByRunId&&u.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(u.rerunFailedByRunId&&(a||u.name.length||u.testId.length||u.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(u.run.length){let R=require("glob");if(u.files=dt.flatMap(u.run,I=>R.sync(I)),u.files.length===0)throw new P(`No files found at path '${u.run}'.`)}else u.files=[];if(u.setRetention&&!dt.inRange(dt.parseInt(u.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");u.setRetention&&=Number(u.setRetention);let g="is no longer supported, please use --override-mapping-file";if(u.mockNetworkHar)throw new P(`--mock-network-har ${g}`);if(u.mockNetworkPattern)throw new P(`--mock-network-pattern ${g}`);if(u.disableMockNetwork&&u.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!u.collectCodeCoverage&&u.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(u.collectCodeCoverage&&u.codeCoverageReporter&&dt.difference(u.codeCoverageReporter,vl).length){let R=dt.difference(u.codeCoverageReporter,vl);throw new P(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}u.codeCoverageReporter=u.codeCoverageReporter.length===0?["html","text"]:u.codeCoverageReporter,u.codeCoverageInclude=u.codeCoverageInclude.length===0?["src/**"]:u.codeCoverageInclude;let f={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},h=Object.keys(f).filter(R=>Boolean(u[R]));if(u.mode!==Q.EXTENSION&&h.length){let R=h.length>1?"are":"is";throw new P(`${h.map(I=>f[I]).join(" and ")} ${R} only applicable in extension mode`)}if(u.tmsFieldFile)try{let R=wl.readFileSync(u.tmsFieldFile);u.tmsCustomFields=JSON.parse(R)}catch(R){throw new P(`failed to parse field file error: ${R.message}`)}if(u.highSpeed&&(Pw("--high-speed","--turbo-mode"),u.turboMode=!0),u.skipLoadBalancer&&!u.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(u.deviceUdid&&(u.deviceName||u.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(u.resetAppData&&u.fullReset)throw new P("It is not possible to set both --reset-app-data and --full-reset capabilities to true at the same time!");if(u.resetOnSessionStartOnly&&!u.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),u.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"},I=typeof u.lightweightMode=="string"?JSON.parse(u.lightweightMode):{};u.lightweightMode=Object.assign({},R,I)}catch(R){throw new P(`failed to parse lightweightMode settings error: ${R.message}`)}else u.turboMode&&u.mode===Q.EXTENSION&&(u.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"});if(typeof u.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[u.testId].flat(),name:[u.name].flat(),label:[u.label].flat(),suites:[u.suite].flat(),suiteIds:[u.suiteId].flat(),testPlan:[u.testPlan].flat(),testPlanIds:[u.testPlanId].flat(),files:[u.files].flat(),webpackConfig:u.webpackConfig,reportFile:u.reportFile,urls:u.urls,reportFileClassname:u.overrideReportFileClassname,reporters:u.reporters,project:u.project,host:u.host,headless:u.headless,localTmaUrl:u.localTmaUrl,useLocalChromeDriver:u.useLocalChromeDriver,chromeBinaryLocation:u.chromeBinaryLocation,useChromeLauncher:u.useChromeLauncher,port:u.port,grid:u.grid,gridId:u.gridId,disableNativeEvents:u.disableNativeEvents,saucelabs:u.saucelabs,browserstack:u.browserstack,baseUrl:u.baseUrl,branch:(u.branch==="auto-detect"?mr():u.branch)||"master",autoDetect:u.branch==="auto-detect",token:u.token,userParamsData:r,mode:u.mode,isRegressionBaselineRun:u.isRegressionBaselineRun,browser:u.browser,beforeParallel:u.beforeParallel,parallel:u.parallel,afterParallel:u.afterParallel,canary:u.canary,rerunFailedByRunId:u.rerunFailedByRunId,disableGridCheck:u.disableGridCheck,disableTimeoutRetry:u.disableTimeoutRetry,resultLabels:u.resultLabel,path:u.path,protocol:u.protocol,perfecto:u.perfecto,experitestToken:u.experitestToken,testobjectSauce:u.testobjectSauce,gridUsername:u.gridUsername,gridPassword:u.gridPassword,overrideExecutionName:u.overrideExecutionName,tmsSuppressReporting:Boolean(u.suppressTmsReporting)||Boolean(u.tmsSuppressReporting),tmsRunId:u.tmsRunId,tmsCustomFields:u.tmsCustomFields,proxyForGrid:u.proxyForGrid,retentionDays:u.setRetention,passZeroTests:Boolean(u.passZeroTests),runQuarantinedTests:Boolean(u.runQuarantinedTests),deviceName:u.deviceName,deviceUdid:u.deviceUdid,osVersion:u.osVersion,skipLoadBalancer:u.skipLoadBalancer,lockDevice:u.lockDevice,appId:u.appId,appiumLogLevel:u.appiumLogLevel,resetAppData:u.resetAppData,fullReset:u.fullReset,resetOnSessionStartOnly:u.resetOnSessionStartOnly,ext:u.ext,extensionLocation:[u.extensionPath||d].flat(),extensionPath:u.extensionPath,playerLocation:u.playerPath||m,playerPath:u.playerPath,playerRequirePath:u.playerRequirePath,tunnel:u.tunnel,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,externalLambdatestTunnelId:u.externalLambdatestTunnelId,externalLambdatestUseWss:u.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(u.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(u.externalLambdatestMitm),beforeTest:u.beforeTest,afterTest:u.afterTest,beforeSuite:u.beforeSuite,afterSuite:u.afterSuite,timeout:u.timeout,timeoutWasGiven:c,browserTimeout:u.browserTimeout,newBrowserWaitTimeout:u.newBrowserWaitTimeout,getBrowserTimeout:u.getBrowserTimeout,getBrowserRetries:u.getBrowserRetries,getSessionTimeout:u.getSessionTimeout,getSessionRetries:u.getSessionRetries,driverRequestTimeout:u.driverRequestTimeout,driverRequestRetries:u.driverRequestRetries,testStartTimeout:u.testStartTimeout,testConfigNames:u.testConfig,testConfigIds:u.testConfigId,overrideMappingFile:u.overrideMappingFile,disableMockNetwork:u.disableMockNetwork,codeCoverageUrlFilter:u.codeCoverageUrlFilter,collectCodeCoverage:u.collectCodeCoverage,codeCoverageReportPath:u.codeCoverageReportPath,codeCoverageSourceMapPath:u.codeCoverageSourceMapPath,codeCoverageReporter:u.codeCoverageReporter,codeCoverageInclude:u.codeCoverageInclude,executionId:u.executionId,remoteRunId:u.remoteRunId,schedulerId:u.schedulerId,source:u.source,resultId:u.resultId,installCustomExtension:u.installCustomExtension,w3cCapabilities:u.w3cCapabilities,oldCapabilities:u.oldCapabilities,chromeBlockLocation:u.chromeBlockLocation,chromeUserDataDir:u.chromeUserDataDir,retries:u.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:u.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:s,shouldMonitorPerformance:u.monitorPerformance,user:u.user,lightweightMode:u.lightweightMode,createPrefechedData:u.createPrefechedData,saveRCALocally:u.saveRcaLocally,exitCodeIgnoreFailingTests:u.exitCodeIgnoreFailingTests,disableSockets:u.disableSockets,intersections:{labels:u.intersectWithLabel.length?[u.intersectWithLabel].flat():void 0,suiteNames:u.intersectWithSuite.length?[u.intersectWithSuite].flat():void 0,suiteIds:u.intersectWithSuiteId.length?[u.intersectWithSuiteId].flat():void 0},downloadBrowser:u.downloadBrowser}}});var Cm={};W(Cm,{installAllLazyDependencies:()=>Nw,lazyRequire:()=>ve});async function ve(r,e={}){let t=gc(r);if(t)return t;let s;e.silent||(s=(0,xm.default)(`Installing ${r} before first usage...`).start());try{let n=await Mw(r);return s&&s.succeed(),n}catch(n){Dw.warn("failed to install dependency lazily",{dependency:r,err:n});let o=Pm(r),i=`${r}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${r} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw s&&s.fail(l),n}}async function Mw(r){return ts.has(r)||(ts.set(r,Am(r)),ts.get(r).catch(()=>{ts.delete(r)})),ts.get(r)}async function Am(r){let e=gc(r);if(e)return e;let t=Pm(r),s=`${r}@${t}`;return await ho(lt(),s),Ht(r)}async function Nw(){let r=Object.keys(_a);for(let e of r)await Am(e)}function Pm(r){let e=Object.entries(_a).find(([t])=>t===r);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var xm,Dw,ts,Tr=T(()=>{"use strict";xm=E(require("ora"));Gs();$();B();Hn();Vs();Dw=A("lazy-require"),ts=new Map});var Om={};W(Om,{preloadTests:()=>nn});async function nn(r){if(!Array.isArray(r.testId)||!r.testId.length)return{};let e={branch:r.branch,projectId:r.project};return await ut(async()=>{let t=await ae(r.testId,s=>_c({...e,testId:s}),{concurrency:2});return km.keyBy(t,"testData.id")},"loadTests",Fw,[e,r.testId])()}var km,Fw,Bo=T(()=>{"use strict";km=E(require("lodash"));Gt();be();B();Fw=1e3*60*60*10});function Rl(){return ct()}async function Dm(){if(!ke)try{let r=await ie(jw(),5e3,"The API call to NPM timed out"),e=Rl();e&&Lm.lt(e,r)&&console.log(_m.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(r){Uw.warn("Failed to get NPM version",{err:r})}}var _m,Lm,Uw,jw,Il=T(()=>{"use strict";_m=E(require("chalk")),Lm=E(require("semver"));B();le();Gs();Gt();$();Uw=A("npm-driver"),jw=ut(()=>Pd("@testim/testim-cli"),"getNpmVersion")});var xl,$w,rs,Mm,Nm,Al,Fm,Um=T(()=>{"use strict";B();z();$();Tr();xl=A("testimNgrok"),$w=".whitelisted-ngrok.testim.io",rs="",Nm=async(r,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${te()}-${r.projectData.projectId}${$w}`);let s={proto:"http",addr:r.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};r.tunnelHostHeader&&(s.host_header=r.tunnelHostHeader),r.tunnelRegion&&(s.region=r.tunnelRegion);let o=await(await ve("ngrok")).connect(s);r.tunnelUseHttpAddress&&o.startsWith("https://")?(xl.info("replace https to http"),rs=o.replace("https://","http://")):rs=o,r.tunnelDiagnostics&&Al(),r.baseUrl=rs},Al=async(r=!0)=>{try{let t=(await ve("ngrok")).getApi(),{tunnels:s}=await t.listTunnels(),n=s.find(o=>o.public_url===rs);console.log("ngrok stats",n),xl.info("ngrok stats",{tunnel:n})}catch(e){xl.error("error collecting ngrok stats",{err:e})}r&&(Mm=setTimeout(()=>Al(),1e4))},Fm=async r=>{if(!rs)return;clearTimeout(Mm),r.tunnelDiagnostics&&await Al(!1),await(await ve("ngrok")).disconnect(rs)}});var Jt,Cl,jm,Vw,Gw,Pl,$o,Vo,Wo,Hw,Bm,$m,Wm=T(()=>{"use strict";Jt=E(require("os")),Cl=E(require("fs")),jm=E(require("child_process"));B();be();Vw="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",Gw={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"}},Pl=Jt.tmpdir(),$o=`${Pl}/cloudflared`,Vo=null,Wo=null,Hw=async()=>{if(await ge($o))return;let e=Gw[Jt.platform()+Jt.arch()];if(!e)throw new Error(`tunnel on ${Jt.platform()+Jt.arch()} platform is not supported.`);let t=e.extract?Pl+e.path:$o;await qe(`${Vw}/${e.path}`,t),e.extract&&await et(t,Pl),await Cl.promises.chmod($o,"755")},Bm=async r=>{let e=r.baseUrl||`http://localhost:${r.tunnelPort||80}`,t="tunnelRoutes"in r&&r.tunnelRoutes||[e],[s]=await Promise.all([el(r.company.companyId,t),Hw()]);Vo=s._id,Wo=jm.spawn($o,["tunnel","--no-autoupdate","run","--force","--token",s.token],{stdio:"inherit"}),await tl(r.company.companyId,Vo),"tunnelRoutesOutput"in r&&r.tunnelRoutesOutput&&await Cl.promises.writeFile(r.tunnelRoutesOutput,JSON.stringify(s.routesMapping,null,2)),r.baseUrl=`${r.tunnelUseHttpAddress?"http":"https"}://${s.routesMapping[e]}`},$m=async r=>{let e=[];return Vo&&e.push(rl(r.company.companyId,Vo)),Wo&&e.push(new Promise((t,s)=>{Wo.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),Wo.kill()})),await Promise.all(e)}});var q,Gm,zw,Kw,Jw,Vm,Go,kl,M,he=T(()=>{"use strict";q=E(require("rox-node"));$();B();le();Gm=A("FeatureFlagsService"),zw=!ke&&!0&&!_p,Kw=2e4,Jw=60*60*24,Vm=["labs","disabled","enabled"],Go=class extends q.default.Variant{constructor(e="disabled"){super(e,Vm)}getValue(){let e=super.getValue();return Vm.includes(e)?e:(Gm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},kl=class{constructor(){this.flags={useNewWSCLI:new q.default.Flag,useSafariWebdriverVisibilityChecks:new q.default.Flag,useClickimVisibilityChecks:new q.default.Flag,runGetElementCodeInAut:new q.default.Flag,enableFrameSwitchOptimization:new q.default.Flag,maximumJsResultSize:new q.default.Configuration(2e3*1024),skipFileInputClicks:new q.default.Flag,errorMessageOnBadNetwork:new q.default.Flag(!0),warnOnBadNetwork:new q.default.Flag(!1),overrideAzureStorageUrl:new q.default.Flag,useJsInputCodeInSafari:new q.default.Flag,useJsInputCodeInFirefox:new q.default.Flag,autoSaveDownloadFileFireFox:new q.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new q.default.Flag(!0),experimentalPreCodeCompilation:new q.default.Flag(!0),experimentalAsyncCustomCode:new q.default.Flag,useSameBrowserForMultiTests:new Go("labs"),highSpeedMode:new Go,usePortedHtml5DragDrop:new q.default.Flag,testNamesToBeforeSuiteHook:new q.default.Flag,addCustomCapabilities:new q.default.Variant("{}"),LTNetworkCapabilities:new q.default.Flag,downloadToBase64:new q.default.Flag,publicGridURL:new q.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new q.default.Flag(!0),unsupportedCapsFields:new q.default.Variant("[]"),useLinkedomToParseHtml:new q.default.Flag,dontFocusOnInit:new q.default.Flag,retryOnSeleniumHubError:new q.default.Flag},q.default.register("default",this.flags)}setProjectId(e){q.default.setCustomStringProperty("projectId",e)}setProjectType(e){q.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){q.default.setCustomStringProperty("productType",e)}setCompanyId(e){q.default.setCustomStringProperty("companyId",e)}setPlanType(e){q.default.setCustomStringProperty("planType",e)}setIsPOC(e){q.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){q.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){q.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!zw)return;let e={fetchIntervalInSec:Jw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ie(q.default.setup(kp,e),Kw).catch(t=>Gm.error("failed to get feature flag status",t))}},M=new kl});var qm,zm,Yt,Km,Jm,Hm,Yw,Xw,Ho,Qw,Zw,oe,qo=T(()=>{"use strict";qm=E(require("ms")),zm=E(require("p-retry")),Yt=E(require("os")),Km=E(require("portfinder")),Jm=E(require("child_process"));B();He();be();z();$();Do();ce();he();Hm=A("lambdatestService"),Yw="https://downloads.lambdatest.com/tunnel/v3",Xw={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"},Ho=`${Yt.tmpdir()}/LT`,Qw=`${Ho}/LT`,Zw=(0,qm.default)("15m"),oe=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===N.LAMBDATEST||e.type===N.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){oe.isLambdatestGrid(e)&&(oe.lambdatestConfigPromise||=zc(),oe.lambdatestConfig=await oe.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Zw:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(Qw))return;let t=Xw[Yt.platform()+Yt.arch()];if(!t)throw new Error(`tunnel on ${Yt.platform()+Yt.arch()} platform is not supported.`);let s=`${Ho}.zip`;await qe(`${Yw}/${t}`,s),await et(s,Ho)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){oe.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Km.getPortPromise(),{gridData:s={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;oe.tunnelName=te();let a=["--tunnelName",oe.tunnelName,"--infoAPIPort",String(t)];if(e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),s.tunnelUser&&s.tunnelKey)a=[...a,"--user",s.tunnelUser,"--key",s.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(i)try{let p=new URL(i);a=[...a,"--proxy-host",p.hostname],p.port&&(a=[...a,"--proxy-port",p.port]),p.username&&p.password&&(a=[...a,"--proxy-user",p.username,"--proxy-pass",p.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),oe.tunnel=Jm.spawn("./LT",a,{cwd:Ho});let c="",l="";oe.tunnel.stdout.on("data",p=>{c+=p.toString()}),oe.tunnel.stderr.on("data",p=>{l+=p.toString()});try{let p=await(0,zm.default)(()=>$e(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});Hm.info("LT tunnel info",p)}catch(p){throw Hm.error("Failed to start LT tunnel",{err:p,stdoutResult:c,stderrResult:l}),p}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!oe.tunnel))return new Promise((t,s)=>{oe.tunnel.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),oe.tunnel.kill()})}getCapabilities(e,t,s,n,o){if(!this.isActive)return{};let i=oe.lambdatestConfig.CAPABILITIES[t]||{},a={...oe.tunnelName&&{tunnel:!0,tunnelName:oe.tunnelName}},c=[],{mode:l,canary:p,ext:d,extensionPath:m,installCustomExtension:g}=e;if(l===Q.EXTENSION&&!d){let f=ml({canary:p},!0);!m&&f[t]&&(c=[...c,f[t]]),m&&je(m)&&(c=[...c,m])}return g&&je(g)&&(c=[...c,g]),{build:s,name:`${n} - ${o}`,platform:oe.lambdatestConfig.PLATFORM,selenium_version:oe.lambdatestConfig.SELENIUM_VERSION,resolution:oe.lambdatestConfig.RESOLUTION,timezone:oe.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled()}}}});var Ol={};W(Ol,{connect:()=>Ko,disconnect:()=>Jo,serveTunneling:()=>tv});var zo,Ym,Xm,ev,Ko,Jo,tv,_l=T(()=>{"use strict";Um();en();Wm();xt();zo=E(require("ora"));$();ce();qo();Ym=A("tunnel"),Xm=r=>{var e;return[N.LAMBDATEST,N.HYBRID].includes((e=r.gridData)==null?void 0:e.type)&&r.gridData.tunnel==="lambdatest"},ev=r=>{var e;return r.tunnelRoutes||((e=r.gridData)==null?void 0:e.type)===N.HYBRID&&r.gridData.tunnel==="cloudflare"},Ko=async r=>{if(!r.tunnel)return;let e=Mt(),t;try{Xm(r)?(t=(0,zo.default)("Starting testim lambdatest tunnel...").start(),await oe.connectTunnel(r)):ev(r)?(t=(0,zo.default)("Starting testim cloudflare tunnel...").start(),await Bm(r)):(t=(0,zo.default)("Starting testim ngrok tunnel...").start(),await Nm(r,e)),t.succeed()}catch(s){let n="Failed to start tunnel. Please contact support@testim.io";throw Ym.error("Failed to open tunnel",{err:s}),t==null||t.fail(n),new Error(n)}},Jo=async r=>{if(r.tunnel)try{Xm(r)?await oe.disconnectTunnel(r):"tunnelRoutes"in r?await $m(r):await Fm(r)}catch(e){let t="catch error - failed to close tunnel";throw Ym.error(t,{err:e}),new Error(t)}},tv=async(r,e=new Promise(()=>{}))=>(await Ko(r),Qr(()=>Jo(r)),await e)});function rv(r){if(r.protocol)return r.protocol;if([N.TESTIM,N.BROWSERSTACK,N.SAUCELABS].includes(r.type)&&r.port===443)return"https";if([N.TESTIM_ENTERPRISE,N.LAMBDATEST,N.DEVICE_FARM].includes(r.type)){let e=Qm.exec(r.host);return(e==null?void 0:e[2])||"https"}return""}function sv(r){let e=Qm.exec(r);return e==null?void 0:e[3]}function Xo(r){var y,v,S,b,w,x,k,O,j;let e=r&&sv(r.host),t=r==null?void 0:r.port,s=r==null?void 0:r.path,n=r&&rv(r),o=r==null?void 0:r.token,i=r==null?void 0:r.slotId,a=(y=r==null?void 0:r.hybrid)==null?void 0:y.tunnel,c=(v=r==null?void 0:r.external)==null?void 0:v.user,l=(S=r==null?void 0:r.external)==null?void 0:S.key,p=r==null?void 0:r.type,d=p===N.HYBRID?a&&((x=(w=(b=r.hybrid)==null?void 0:b.external)==null?void 0:w[r.hybrid.tunnel])==null?void 0:x.user):c,m=p===N.HYBRID?a&&((j=(O=(k=r.hybrid)==null?void 0:k.external)==null?void 0:O[r.hybrid.tunnel])==null?void 0:j.key):l,g=r==null?void 0:r.name,f=r&&(r._id||r.gridId),h=r==null?void 0:r.provider;return{host:e,port:t,path:s,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:l,type:p,name:g,provider:h,tunnelUser:d,tunnelKey:m}}async function ef(r,e,t,s,n){let o;try{o=await n()}catch(i){throw Ye.error("failed to get grid",{projectId:r,companyId:e,err:i}),new Error($r.UNKNOWN)}if(Ye.info("get grid info",Object.assign({},o,{projectId:r,companyId:e})),!o||!["success","error"].includes(o.status))throw Ye.error("invalid response - get grid",{res:o}),new Error($r.UNKNOWN);if(o.status==="success"){let i=Xo(o.grid);return nv(t,e,i.gridId,i.slotId,s),i}throw o.code==="not-found"?new Et($r.NOT_FOUND):o.code==="no-available-slot"?new Nr(`Failed to run test on ${s} - concurrency limit reached`):(Ye.error("invalid code error response - get grid",{res:o}),new Et($r.UNKNOWN))}function ov(r,e,t,s,n,o){return ef(t,e,r,n,()=>Ao(e,t,s,n,o))}function iv(r,e,t,s,n,o,i){return ef(t,e,r,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(p=>(p.name||"").toLowerCase()===s.toLowerCase());return c!=null&&c._id?Ao(e,t,c._id,n,o):Gc(e,t,s,n,o)})}function tf(r){return qc(r)}async function rf(r,e,t){let n=(t||await tf(r)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return Xo(n)}async function av(r,e,t){let n=(t||await tf(r)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return Xo(n)}async function Ll(r,e){let t=on[r];if(!t)return;let{slotId:s,gridId:n,browser:o,companyId:i}=t;if(delete on[r],!s){Ye.warn("failed to find grid slot id",{projectId:e});return}Ye.info("release slot id",{projectId:e,companyId:i,slotId:s,gridId:n,browser:o});try{await Wc(i,e,s,n,o)}catch(a){Ye.error("failed to release slot",{projectId:e,err:a})}}async function cv(r){let e=Object.values(on).filter(Boolean);if(e.length!==0){Ye.info("keep alive worker slots",{projectId:r,slots:e});try{await $c(r,e)}catch(t){Ye.error("failed to update grid keep alive",{err:t,slots:e,projectId:r})}}}function lv(r){Zm=global.setInterval(cv,1e4,r)}async function uv(r){let e=Object.keys(on);if(e.length){Ye.warn("not all slots released before end runner flow",{projectId:r});try{await ae(e,t=>Ll(Number(t),r))}catch(t){Ye.error("failed to release all slots",{err:t,projectId:r})}}}async function pv(r){await uv(r),clearInterval(Zm)}function dv(r,e){let{testobjectSauce:t,saucelabs:s}=e;if(r==="testobject")return t.testobjectApiKey;if(r==="saucelabs")return s.accessKey}function mv(r,e){let{saucelabs:t}=e;if(r==="saucelabs")return t.username}function sf(r){let t=(()=>Yo.isEmpty(r.testobjectSauce)?Yo.isEmpty(r.saucelabs)?Yo.isEmpty(r.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:s,port:n,path:o,protocol:i}=r,a=dv(t,r),c=mv(t,r);return{host:s,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function nf(r,e){let t=r.company.companyId;return await rf(t,e.gridId,r.allGrids)}async function of(r){let{allGrids:e,company:t,host:s,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:c}=r;if(n||i||o)return{mode:"local"};if(s)return sf(r);let l=t==null?void 0:t.companyId;if(a)return rf(l,a,e);if(c)return av(l,c,e);if(Fs(r)||r.tunnelOnlyMode){Ye.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new Et("Missing host or grid configuration")}async function af(r,e,t,s){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:p,company:d}=t,m=d==null?void 0:d.companyId;if(l||p||c)return{mode:"local"};if(n)return sf(t);if(a)return ov(s,m,o,a,r,e);if(i)return iv(s,m,o,i,r,e,t);throw new Et("Missing host or grid configuration")}var Yo,Ye,on,Qm,Zm,nv,an,cf,ss=T(()=>{"use strict";Yo=E(require("lodash"));be();$();B();ce();z();Ye=A("grid-service"),on={},Qm=/(^(https?):\/{2})?(.*)/,Zm=null;nv=(r,e,t,s,n)=>{on[r]={gridId:t,companyId:e,slotId:s,browser:n}};an={start:lv,end:pv};cf=async(r={},e={},t={},s={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=r,{gridId:i,type:a}=e,c=r.browser||t.browserValue,l=Boolean(r.tunnel),{maxRetries:p,currentRetry:d}=n;if(!i||!a||(a===N.LAMBDATEST&&await((f=s.enableIfNeeded)==null?void 0:f.call(s,e)),a!==N.HYBRID||!o||!c||!p||!d))return e;let m=await Vc({companyId:o,gridId:i,maxRetries:p,currentRetry:d,browser:c,usingTunnel:l});Ye.info("handling hybrid grid",{response:m,companyId:o});let g=Xo({...e,...m.connectionDetails,provider:m.provider});return m.provider!=="lambdatest"&&((h=s.disable)==null||h.call(s)),m.provider==="lambdatest"&&await((y=s.enableIfNeeded)==null?void 0:y.call(s,g)),g}});function ln(){return Qo||"master"}function lf(r="master",e="false"){if(typeof r!="string"&&(r!=null&&r.branch)&&r.branch==="master"){Qo="master";return}if(r&&!r.isArchived){Qo=r.branch||r;return}Qo=e?"master":void 0}var Qo,Dl=T(()=>{"use strict"});var un,Ml,fv,Nl,gv,Fl,Zo,ei,ti,ri,si,ni=T(()=>{"use strict";B();ce();un=r=>{let{status:e,sessionType:t,success:s,mobile:n}=r;return n!=null&&n.isAppFromDevice||n!=null&&n.isAppForIosVirtualDevice?!1:e===pe.FAILED||t===ur.CODEFUL&&s===!1},Ml=r=>{let{status:e}=r;return e===pe.ABORTED},fv=r=>{let{status:e,sessionType:t,success:s}=r;return e===pe.PASSED||t===ur.CODEFUL&&s===!0},Nl=r=>r.runnerStatus===ec.SKIPPED,gv=r=>r.testStatus===ze.EVALUATING,Fl=(r,e)=>e?!r.runConfig:!1,Zo=(r,e)=>Object.values(r).filter(t=>{var s,n;return Nl(t)&&(Ke(t,e)||((s=t.mobile)==null?void 0:s.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,ei=r=>Object.values(r).filter(e=>un(e)&&gv(e)).length,ti=(r,e)=>Object.values(r).filter(t=>un(t)&&!Fl(t,e)),ri=(r,e)=>Object.values(r).filter(t=>fv(t)&&!Fl(t,e)),si=(r,e)=>Object.values(r).filter(t=>Ml(t)&&!Fl(t,e))});function hv(r){let e=r.indexOf("--token");if(e===-1&&(e=r.indexOf("--t")),e!==-1)try{let t=r.slice();return t.splice(e,2),t}catch{}return r}var oi,pf,ii,df=T(()=>{"use strict";$();ni();oi=A("debug-reporter"),pf={token:void 0,userParamsData:void 0,projectData:void 0,allGrids:void 0,gridData:void 0,awsAccessKeyId:void 0,awsSecretAccessKey:void 0,runParams:void 0,perfecto:void 0,testobjectSauce:void 0},ii=class{constructor(e){this.options=e}onTestStarted(e,t){oi.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let s=this.options.gridData||{},n=s.provider,o=s.host,i=s.gridId,a=s.type,c=s.failedGetBrowserAttempts;oi.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}onTestPlanStarted(e,t,s,n,o,i,a){let c=hv(process.argv);oi.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:Object.assign({},this.options,pf),args:c})}onTestPlanFinished(e,t,s,n,o,i){let a=ri(e,i).length,c=Object.keys(e).length-a;oi.info("Test Plan Finished",{isAnonymous:o,passed:a,failed:c,testPlanName:t,options:Object.assign({},this.options,pf),duration:s,executionId:n})}}});var Ul,Pt,pn=T(()=>{"use strict";ce();Ul=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===N.DEVICE_FARM}},Pt=new Ul});var Bl={};W(Bl,{Reporter:()=>yv});var Xt,dn,wr,ai,mf,jl,yv,$l=T(()=>{"use strict";Xt=E(require("chalk")),dn=E(require("lodash"));B();ce();pn();ni();wr={success:Xt.default.green,warn:Xt.default.yellow,error:Xt.default.red},{CLI_MODE:ai}=Lt,mf="device",jl=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,s,n){let o=n?"File":"Test",i=e.isTestsContainer?"":`(${e.testId})`,a=e.isTestsContainer?"":`url: ${Xt.default.underline(at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`${o} "${e.name}" started ${i} ${a}`.trim())}onTestFinished(e,t,s,n){if(n)return;let o=e.success?pe.PASSED:pe.FAILED,i=e.isTestsContainer?" ":`(${e.testId})`,a=wr[e.success?"success":"error"];console.log(a(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${o} ${i} duration: ${ro(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(s=>{let n=at(this.options.editorUrl,this.options.project,s.testId,s.resultId,this.branchToUse);return s.isTestsContainer?s.name:`${s.name} : ${n}`});console.log(wr.error("Failed runs are:")),console.log(wr.error(t.join(`
|
|
21
|
-
\r`)))}onTestPlanFinished(e,t,s,n,o,i){let a=ti(e,i),c=ri(e,i),l=si(e,i),p=c.length,d=l.length,m=a.length,g="",f="";if(Pt.isTestStatusEnabled){let b=ei(e);g=` FAILED-EVALUATING: ${b}`,m-=b,f=` SKIPPED: ${Zo(e,this.options)}`}let h=this.buildTestPlanName(o,t,i),y,v=wr[m?"error":"success"],S=`PASSED: ${p} FAILED: ${m}${g} ABORTED: ${d}${f} Duration: ${ro(s)}`;i||h.trim()===""||h.trim()==="Anonymous"?y=`Tests completed. ${S} (Execution ID: ${n})`:y=`Test plan${h} completed ${S} (${n})`,this.printWorkerDivider(),console.log(v(y)),this.printWorkerDivider(),this.printAllFailedTests(a)}buildTestPlanName(e,t,s){if(s)return"";let n=dn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,o=dn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=dn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,a=dn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,c=[i,o,n,a].filter(Boolean).join(", ");return e?` anonymous (${c})`:` '${t}'`}onTestPlanStarted(e,t,s,n,o,i,a,c){let l=m=>{m.forEach((g,f)=>{var v;let h=(v=g.testData)!=null&&v.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=c?"":`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${Ke(g,this.options)?"-quarantine":""}`,y,h)})},p=a?`config '${a}'`:"default configs";if(c)console.log(`Run test plan, Project: ${this.options.project} (Execution ID: ${o}):`);else{let m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",g=`${p}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${g} (${o})`)}this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log(c?"File list:":"Test list:"),l(t),s.length>0&&(console.log("After all:"),l(s)),this.printWorkerDivider()}onGetSlot(e,t){let s=this.options.grid||this.options.gridId,n=this.options.mode===ai.APPIUM?mf:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${Xt.default.underline(n)} slot from ${Xt.default.underline(s)}`)}onGetSession(e,t,s){let n=s===ai.APPIUM?mf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Xt.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e,t,s){let n=t?"file":"test";console.log(this.toWorkerIdPrefix(e),`Wait for ${n} complete`),s&&t&&console.log(this.toWorkerIdPrefix(e),`Chrome Debugger available at ${s}`)}onGetBrowserFailure(e,t,s){if(s!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===ai.APPIUM?"device":"browser";if(n)console.log(wr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(wr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===ai.APPIUM?"Appium":"Selenium";console.log(wr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},yv=jl});var Gl={};W(Gl,{Reporter:()=>Sv});function bv(r){let e=r.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function Tv(r){return r.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${r.visitedUrlsList||""}`}function wv(r){return`${r.visitedUrlsJson||""}`}async function vv(r,e,t,s,n,o){function i(m){let g=at(r,t,m.testId,m.resultId,s),f={$:{name:bv(m),classname:n,time:ac(m.duration),ownedBy:m.testOwnerName,ownerEmail:m.testOwnerEmail},"system-out":g};if(un(m)||Ml(m)){let h=`Step Failed: ${m.failureReason||m.reason}`,y=un(m)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Nl(m)&&Ke(m,o)&&Pt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=Tv(m),f["visited-urls-json"]=wv(m)),f}function a(m){let{results:g,testPlanName:f,configName:h}=m,y=g||{},S={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:l(y),failure:p(y),timestamp:c(e)};if(Pt.isTestStatusEnabled){S.skipped=Zo(y,o);let b=ei(y);S.failure-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(m){let g=Object.keys(m).map(h=>m[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function l(m){return Object.keys(m).length}function p(m){return ti(m).length+si(m).length}let d={testsuites:{testsuite:e.map(m=>a(m))}};try{return new Vl.Builder().buildObject(d)}catch(m){return Ev(m)}}function Ev(r){let e=new Vl.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:r.message}}}}}};return e.buildObject(t)}var Vl,ff,Wl,Sv,Hl=T(()=>{"use strict";Vl=E(require("xml2js"));B();ff=require("fs");pn();ni();Wl=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,s=this.options.project,n=await vv(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await ff.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Sv=Wl});var gf={};W(gf,{Reporter:()=>Rv});function ns(r){return r?r.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 ql,zl,Rv,hf=T(()=>{"use strict";$();ql=A("team-city-reporter");zl=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${s}`;return ns(n)}onTestStarted(e,t,s,n,o){if(s){ql.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${o}']`)}onTestFailed(e,t,s,n,o,i){if(o){ql.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ns(t)}' details='${ns(s)}' flowId='${i}']`)}onTestFinished(e,t,s){if(s){ql.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,s="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ns(s)}']`)}onTestPlanStarted(e,t,s,n){console.log(`##teamcity[testSuiteStarted name='${ns(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ns(t)}']`)}},Rv=zl});var yf={};W(yf,{Reporter:()=>Iv});var Kl,Iv,bf=T(()=>{"use strict";Kl=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,s,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},Iv=Kl});var Tf={};W(Tf,{Reporter:()=>xv});var Jl,xv,wf=T(()=>{"use strict";B();fl();Jl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e,t,s,n){if(n)return;let o=at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return No(o)}},xv=Jl});var Av,Yl,J,Ct=T(()=>{"use strict";df();$();Av=A("reporter"),Yl=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 s=e.reporters;if(this.reporters.push(new ii(e)),s===void 0||s.length===0){let{Reporter:n}=await Promise.resolve().then(()=>($l(),Bl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(Hl(),Gl));this.reporters.push(new o(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(hf(),gf)),s.includes("console")&&Promise.resolve().then(()=>($l(),Bl)),s.includes("junit")&&Promise.resolve().then(()=>(Hl(),Gl)),s.includes("json")&&Promise.resolve().then(()=>(bf(),yf)),s.includes("chrome")&&Promise.resolve().then(()=>(wf(),Tf))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,n,o,i,a){let c={};if(a){let p=Object.values(a);if(p.length>0){for(let d of Object.values(a))c[d.id]=d;for(let d of Object.keys(e))p.some(m=>m.parentResultId!==d)||(c[d]=e[d])}else Av.warn("childTestResults is not array"),c=e}else c=e;let l=Date.now()-(s||0);return[c,t,l,n,o,i,void 0]}onAllTestPlansFinishedMutator(e){for(let t of e)if(t.childTestResults){t.results={};let s=Object.values(t.childTestResults);for(let n of s)t.results[n.id]=n;for(let n of Object.keys(e))s.some(o=>o.parentResultId!==n)||(t.results[n]=e[n])}return[e]}generateHook(e,t){return async(...s)=>{var o;let n=t==null?void 0:t(...s);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||s))}}},J=new Yl});function Ef(r,e){return e!=null&&e.type&&(r[`${e.type}Mode`]=!0),r}function Sf({executionId:r,projectId:e,testId:t,resultId:s,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,source:p,user:d,lightweightMode:m,isStartUp:g,projectType:f,appSource:h}){let y=Ef({executionId:r,projectId:e,testId:t,resultId:s,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,source:vf(p,d),isStartUp:g,projectType:f,...["android","ios"].includes(f)&&h&&{appSource:h}},m);pt("test-run-ci",y)}function Rf({executionId:r,projectId:e,testId:t,resultId:s,result:n,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,sessionType:p,source:d,user:m,lightweightMode:g,logger:f,isStartUp:h,projectType:y,appSource:v}){try{let S=Ef({executionId:r,projectId:e,testId:t,resultId:s,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,sessionType:p,mockNetworkEnabled:n.wasMockNetworkActivated,source:vf(d,m),isStartUp:h,projectType:y,...["android","ios"].includes(y)&&v&&{appSource:v}},g);if(n.success){pt("test-run-ci-success",S);return}pt("test-run-ci-fail",Object.assign({},S,{failureReason:n.failureReason}))}catch(S){f.error("failed to update test end analytics",{err:S})}}function If({executionId:r,projectId:e,sessionType:t}){pt("batch-run-ci",{executionId:r,projectId:e,sessionType:t})}var vf,Xl=T(()=>{"use strict";Zr();Ro();vf=(r,e)=>r!=="cli"&&r!=="cli-local"?r:Jr&&e?"ci-with-user":Jr?"ci":e?"cli-with-user":r});var Af,ci,Pf=T(()=>{"use strict";Af=require("istanbul-lib-report"),ci=class extends Af.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let s=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,s.toJSON())}}});var Cf,kf,Of,mn,mt,_f,li,Ql,Lf,Pv,Df,Mf,Cv,kv,Nf,Ov,_v,Lv,Dv,Mv,Ff,Uf=T(()=>{"use strict";Cf=E(require("ora")),kf=E(require("moment")),Of=E(require("test-exclude")),mn=E(require("fs")),mt=E(require("path")),_f=E(require("istanbul-reports")),li=E(require("istanbul-lib-report"));be();z();B();$();Tr();Pf();Ql=A("test-run-status"),Lf=r=>{try{return new URL(r)}catch{try{return new URL(`file://${r}`)}catch{return{}}}},Pv=r=>!!Lf(r).search,Df=r=>r?Lf(r).pathname.substring(1):"",Mf=(r,e)=>{let t=Df(e);return!new Of.default({relativePath:!1,include:r}).shouldInstrument(t)},Cv=r=>r.substring(0,r.indexOf("?")),kv=async({source:r,sourceMapDir:e,sourceMapType:t})=>{let s=await ve("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?s.fromMapFileSource(r,e):s.fromSource(r)},Nf=(r,e)=>`${mt.resolve(r,Df(e))}.js`,Ov=async(r,e,t)=>{let{codeCoverageInclude:s}=r;await ae(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ae(o.sources,async(i,a)=>{if(Mf(s,i))return;let c=Nf(e,i);await mn.promises.mkdir(mt.parse(c).dir,{recursive:!0}),await mn.promises.writeFile(c,o.sourcesContent[a])})})},_v={getPath(r){if(typeof r=="string")return r;let e=r.getQualifiedName();return r.isSummary()?e!==""?e+="/index.html":e="index.html":(Pv(e)&&(e=Cv(e)),e+=".html"),e},relativePath(r,e){let t=this.getPath(e),s=mt.dirname(this.getPath(r));return mt.posix.relative(s,t)},assetPath(r,e){return this.relativePath(this.getPath(r),e)}},Lv=async(r,e,t,s)=>{let{codeCoverageReporter:n}=r,o={},i=li.createContext({dir:t,coverageMap:e,watermarks:li.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Nf(s,a);return mn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ci({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:_v}),_f.create(a,c).execute(i)}),o},Dv=async(r,{source:e,sourceMap:t,functions:s})=>{let{codeCoverageInclude:n}=r;if(!t||t.sourcemap.sources.length===0)return;let i=(await ve("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Mf(n,a));return await i.load(),i.applyCoverage(s),i.toIstanbul()},Mv=async(r,e)=>{let{mergeProcessCovs:s}=await ve("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await Xs(r,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Ys(c,9e4);await ae(l,async p=>{if(!o.has(p.url)){let d=p.text;p.sourceUrl&&(o.set(p.url,"TEMP"),d=await kc(p.sourceUrl)),o.set(p.url,{text:d,url:p.url,sourceMapType:p.sourceMapType,hash:p.hash})}delete p.text,n=s([n,{result:[p]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},Ff=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;Ql.info("start js coverage process");let n=(0,Cf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=mt.resolve(r.codeCoverageReportPath||"./coverage"),i=mt.resolve(o,`.js/${(0,kf.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?mt.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:p}]=await Promise.all([ve("istanbul-lib-coverage"),Mv(r.project,s)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Ql.info("start js coverage merge and remap",{numOfFiles:p.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),m={};await ae(l.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:v}=p.get(f),S=await kv({sourceMapType:v,source:y,sourceMapDir:a});m[f]=S;let b=await Dv(r,{source:y,sourceMap:S,functions:h});d.merge(b)}),await Ov(r,i,m);let g=await Lv(r,d,o,i);return n.succeed(),g}catch(c){let l="Failed to report coverage information";c instanceof P?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Ql.error(l,{err:c})}}});var jf={};W(jf,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>Ut});var Ae,Nv,Ut,os=T(()=>{"use strict";B();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Nv=["ALL",...Object.values(Ae)],Ut=class{constructor(){this.marks=Object.fromEntries(Nv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=te();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let s=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(s);return}this.marks[t].push(s)}getStats(){let e=Object.entries(this.marks).flatMap(([t,s])=>!Array.isArray(s)||!s.length?[]:[[`${t}_COUNT`,s.length],[`${t}_P50`,oo(s,50)],[`${t}_P95`,oo(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Vf={};W(Vf,{initServer:()=>jv,mapFilesToLocalDrive:()=>eu});function eu(r,e){try{r.failurePath=(r.failurePath||[]).map(t=>Object.assign(t,ui[t.id]?{screenshot:ui[t.id]}:{})),Object.keys(pi).forEach(t=>{r.assets||={},r.assets[Wf[t]]=pi[t]}),r.assets||={},r.assets.screenshots=Object.values(ui)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),r.failurePath||=[],r.assets||={},r.assets.screenshots||=[]}}async function jv({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await ve("multer"),n=typeof t=="string"?t:Fv;await Zl.promises.mkdir(n,{recursive:!0});let o=s({storage:s.diskStorage({async destination(c,l,p){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return p(new Error("missing testResultId"),"");let m=fn.join(n,d.testResultId);try{await Zl.promises.mkdir(m,{recursive:!0})}catch(g){return p(g,"")}return p(null,m)},filename(c,l,p){let{fileName:d}=c.body,m=JSON.parse(c.body.metadata||"{}");if(!m.stepId&&!d)return p(new Error("missing stepId or fileName"),"");if(m.stepId){let g=fn.extname(d);return p(null,`step_${m.stepId}_${m.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return p(null,d)}})}),i=(0,$f.default)();i.post("/",o.single("file"),(c,l)=>{let p=JSON.parse(c.body.metadata||"{}");p.stepId&&(ui[p.stepId]=c.file.path),p.testResultId&&Uv.includes(p.subType)&&(pi[p.subType]||=[],pi[p.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let p=a(i);p.listen(r,e),p.on("error",d),p.on("listening",()=>c(p.address()));function d(m){if(m.syscall!=="listen")return l(m);switch(m.code){case"EACCES":case"EPERM":return l(new P(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return l(new P(`Port ${r} is already in use`));default:return l(m)}}})}var Zl,Bf,fn,$f,Fv,ui,pi,Wf,Uv,tu=T(()=>{"use strict";Zl=E(require("fs")),Bf=E(require("os")),fn=E(require("path")),$f=E(require("express"));z();Tr();Fv=fn.join(Bf.tmpdir(),"testim/rca/"),ui={},pi={},Wf={"test-log":"consoleLogs","har-file":"networkLogs"},Uv=Object.keys(Wf)});var Qt,ru,di,Gf=T(()=>{"use strict";Qt=E(require("lodash"));B();$();ru=A("override-test-data-builder"),di=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}isObjectNotArray(e){return Qt.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)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!Qt.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(s=>this.overrideSingleTest(s,e.overrideTestData[s])),delete e.overrideTestData):ru.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(Qt.isObject(e.overrideAllTestsData)&&!Qt.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):ru.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}ru.error("skip override test data to test name",{testName:e,projectId:s}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let s=this.mapTestListToUniqueId(e);if(s.length!==0)return this.createNewTestPerOverrideTestData(s,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return Qt.chain(t).map(s=>{if(s.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(s)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:s}=this;return[...new Set(e)].map(n=>{let o=s.map(p=>this.generateTestUniqId(p)),i=o.indexOf(n),a=o.lastIndexOf(n),c=s[i],l=this.createNewTestItems(c,t);return s.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((s,n)=>{let o=te();return Object.assign({},e,{resultId:o,testData:{value:s,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 mi(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw Xe.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var vr,Xe,Bv,$v,Wv,Vv,fi,Hf=T(()=>{"use strict";vr=E(require("lodash"));B();ce();ss();be();z();$();Ct();en();Uf();os();tu();le();he();Gf();pn();Xe=A("test-run-status"),Bv=mr(),$v=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Wv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Vv=ct();fi=class{constructor(e,t,s,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ut;var a,c,l,p;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Ns(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Jn||t.parallel||1,browser:o,gitBranch:Bv,gitCommit:$v,gitRepoUrl:Wv,runnerVersion:Vv,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:s,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(d=>d.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(p=t.gridData)==null?void 0:p.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:pr(t)},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:s,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,isTestsContainer:l,testId:p,name:d,testStatus:m,testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:v,testSuites:S,allLabels:b}=a,w={originalTestResultId:t,previousTestResultId:s,config:vr.cloneDeep(c),testId:p,status:"QUEUED",name:d,resultId:e,isTestsContainer:l,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},w,{testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:v,testSuites:S,allLabels:b}),Qc({projectId:n,runId:o,testId:p,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:w})}getAllTestResults(){return this.testRunStatus}testStart(e,t,s,n){let o=this.getTestResult(s);o.workerId=e;let i=this.options.files.length>0;return J.onTestStarted(o,e,n,i,s),o}async updateTestStatusRunning(e,t,s){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Co(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(p){Xe.error("failed to upload test data artifact (runner)",{err:p})}let c=vr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Xr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:s})}async testStartReport(e,t,s){if(Ke(e,this.options))return;let n=this.exportsGlobal;try{let o=await mi(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw Xe.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,n,o){let i=this.testStart(e,t,s,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Xe.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,n){let{name:o,testId:i,testStatus:a}=s,{resultId:c,success:l}=t;if(a===ze.EVALUATING&&Pt.isTestStatusEnabled){J.onTestIgnored(e,s,`test in ${ze.EVALUATING} status`);return}if(l){J.onTestPassed(o);return}J.onTestFailed(s,s.failureReason,at(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);J.onTestIgnored(e,s,`test in ${ze.QUARANTINE}`)}monitorMemoryUsage(e){let t=cc();if(t.isOverThreshold){let s=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Xe.info(`using ${s} to parse html`,{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}}testEnd(e,t,s,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&eu(i,Xe),i.resultUrl=at(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o);let c=this.options.files.length>0;this.monitorMemoryUsage(i),J.onTestFinished(i,e,o,c);let l=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=l,i}async testEndReport(e,t,s,n){var i;let o=s.exportsGlobal;try{try{await mi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Xe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await Xr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Xe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,n,o,i){let a=this.testEnd(e,t,s,n,o);return this.testEndReport(a,s,t,i)}getMobileRunSkippedReason(e,t){let s="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=sc;return e&&(s=n),Wr(t)&&(s=o),s}calcTestRunStatus(){let{options:e,testInfoList:t}=this,s=e.company.companyId,n=t.map(o=>{var d,m,g;let i=e.browser?$s(e.browser,e.saucelabs,e.browserstack):o.runConfig,a=!M.flags.allowAppFromDeviceRuns.isEnabled()&&Us(o.nativeApp),c=js(e)&&(Wr(o.nativeApp)||a),l=Ke(o,e)||c,p={testId:o.testId,status:l?pe.SKIPPED:pe.QUEUED,name:o.name,resultId:o.resultId,testStatus:o.testStatus||ze.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...c&&{reason:this.getMobileRunSkippedReason(a,o.nativeApp)},config:Object.assign({},this.execConfig,{companyId:s,testData:((d=o.testData)==null?void 0:d.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((m=o.testData)==null?void 0:m.total)||null,testDataIndex:((g=o.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,p]});return Object.fromEntries(n)}async executionStart(e,t,s,n,o){Xe.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Qr(()=>Promise.all([an.end(t),xo("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=s||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},p=await mi(i.beforeSuite,l),d=new di(p,vr.cloneDeep(this.testInfoList),t);this.testInfoList=d.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=p;let{testInfoList:m}=this,g=[],f=[],h=[];for(let v of m){if(v.isBeforeTestPlan){g.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}f.push(v)}let y=async()=>{let v=vr.cloneDeep(this.testRunStatus);await ae(Object.keys(v),async x=>{var I;let k=v[x],O=(I=k.config)==null?void 0:I.testData,j=k.testId,R=await Co(t,j,x,O,c.defaults);R&&(delete k.config.testData,k.config.testDataUrl=R)});let S=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:s,executions:v,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:S,intersections:i.intersections},w=Mc(b);return this.executionStartedPromise=w,w.catch(x=>Xe.error(x)),w};try{await y()}catch(v){Xe.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){vr.chain(e).keys().each(t=>{let s=t;this.seleniumPerfStats.marks[s]&&(this.seleniumPerfStats.marks[s]=[...this.seleniumPerfStats.marks[s],...e[s]])}).value()}async executionEnd(e){var p;let t=uc(this.testRunStatus),s=t.length,n=0,o=0,i=0;for(let{status:d,testStatus:m}of t)d===pe.PASSED&&n++,d===pe.SKIPPED&&o++,d===pe.FAILED&&m===ze.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await mi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:n,skipped:o})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Xe.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Ff(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:l}),!((p=this.options.lightweightMode)!=null&&p.onlyTestIdsNoSuite))try{return await xo("FINISHED",e,this.options.project,s===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Xe.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,s,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await Dc(e,["QUEUED"],t,s,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=s,a.success=n}return this.testRunStatus}}});function hn(r){return r===N.TESTIM_TDC||r===N.TESTIM_HEADSPIN}function Gv(r){let e=zf(r);return hn(r)?`${e}/lock`:""}function zf(r){return r===N.TESTIM_HEADSPIN?"https://api-dev.headspin.io/v0/devices":r===N.TESTIM_TDC?"https://api.tricentis.headspin.io/v0/devices":""}function Kf(r){return{...hn(r.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`}}}function Hv(r,e){return{...hn(r.type)&&{device_id:e}}}async function Jf(r,e){let t=Gv(r.type),s=Kf(r),n=Hv(r,e);try{await Be({url:t,headers:s,body:n})}catch(o){throw gn.debug(`error while locking device ${e}`,{error:o}),o.status===401?new Error(`failed to lock device ${e}, device may be already locked and in use`):o}}async function su(r,e){let s=`${zf(r.type)}/device_id:${e}/automation-config`;try{let n=await $e(s,void 0,Kf(r));return qv(n,r.accessToken)}catch(n){throw gn.error("error while getting automation config for device",{error:n,deviceId:e}),n}}function qv(r,e){let t=Object.keys(r)[0],s=r[t].driver_url,n=new URL(s);return{hostname:n.hostname,port:Number(n.port),protocol:n.protocol.slice(0,-1),path:`/v0/${e}/wd/hub`}}async function Yf(r,e){let t={};return hn(r.type)&&(t=await su(r,e)),t}function Xf(r){if(hn(r.type))return{protocol:r.protocol||"https",hostname:r.host,port:r.port,path:`/v0/${r.accessToken}/wd/hub`};if([N.BROWSERSTACK,N.SAUCELABS].includes(r.type))return{protocol:r.protocol||"https",hostname:r.host,port:443,path:"/wd/hub",user:r.user,key:r.key}}async function zv({capabilities:r,gridType:e,projectId:t,projectType:s,companyId:n,gridId:o}){var i,a;if(e===N.TESTIM_HEADSPIN||e===N.TESTIM_TDC){let c=await nl({projectId:t,projectType:s,companyId:n,gridId:o,selectors:`device_id:${r.udid}`});return((i=c==null?void 0:c[0])==null?void 0:i.name)||r.device}return e===N.BROWSERSTACK?(a=r.mobile)==null?void 0:a.version.split("-")[0]:e===N.SAUCELABS?r.testobject_device_name:r.device}async function gi(r,e,t){var h;let{executionId:s,testId:n,testResultId:o}=r,{project:i,projectData:{type:a}={},company:{companyId:c=""}={},gridData:{gridId:l="",type:p=""}={}}=t,d=e.capabilities,m=await zv({capabilities:d,gridType:p,projectId:i,projectType:a,companyId:c,gridId:l}),g=d.platformVersion;!g&&p===N.BROWSERSTACK&&(g=(h=d.mobile)==null?void 0:h.version.split("-")[1]);let f={name:m,model:d.deviceModel,osVersion:g,udid:d.udid,osType:d.platformName,scaleFactor:d.pixelRatio,virtual:!1};await Xr(i,s,n,o,"RUNNING",{device:f})}async function nu({appId:r,projectId:e,token:t}){try{let s=await Uc({appId:r,projectId:e});if(!s)throw gn.error("mobile app not found",{appId:r,projectId:e}),new Error("mobile app not found");return{appUrl:`${me}/storage${s.filePath}?access_token=${t}`,mobileApp:s}}catch(s){throw gn.error("error while getting app details",{error:s,appId:r,projectId:e}),s}}function Jv(r){let e=0,t=Math.ceil(r/1024);return e=(Math.ceil(t/(Up*60))+1)*60*1e3,Math.max(Fp,e)}async function Qf({testRunHandler:r,options:e}){let t="",s,{appId:n,project:o,authData:{token:i=""}={},gridData:{gridId:a="",type:c="",host:l=""}={}}=e;n?t=(await nu({appId:n,projectId:o,token:i})).appUrl:t=r.nativeAppLink||"";let p=Kv[c]({testRunHandler:r,mobileApp:s,gridHost:l}),d=!!p&&c===N.TESTIM_TDC,m=!!p&&c===N.TESTIM_HEADSPIN;if(p&&(t=p),!p&&N.BROWSERSTACK===c){if(r.isAppFromDevice)throw new Error("app from device is not supported in browserstack");let g=s||r.mobileApp,f=(0,qf.default)("uploading app to browserstack please wait..").start();try{let h=await ol({projectId:o,gridId:a,app:g,timeout:Jv(g.fileSize)});f.succeed("app uploaded successfully to browserstack"),t=h.browserStackAppId}catch(h){throw f.fail("failed to upload app to browserstack"),gn.error("failed to upload app to browserstack",{error:h}),new Error("failed to upload app to browserstack")}}return{appPath:t,isTdcAppIdExists:d,isHSAppIdExists:m}}var qf,gn,Kv,hi=T(()=>{"use strict";$();ce();le();be();He();qf=E(require("ora")),gn=A("mobile-grid-service");Kv={[N.TESTIM_TDC]:({testRunHandler:r,mobileApp:e})=>r.getTdcAppPath(e),[N.TESTIM_HEADSPIN]:({testRunHandler:r,mobileApp:e})=>r.getHeadspinAppPath(e),[N.BROWSERSTACK]:({testRunHandler:r,mobileApp:e})=>r.getBrowserStackAppPath(e),[N.SAUCELABS]:({testRunHandler:r,mobileApp:e,gridHost:t})=>r.getSauceLabsAppPath(t,e)}});function Xv(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function lu(r){return tg.readFileSync(r,{encoding:"base64"})}function og(r,e,t){if(!(t!=null&&t.isLambdatestRun()&&je(r))&&r){let s=lu(r);is.info(`adding extension: custom, path: ${r} length: ${s.length} hash: ${cu(s)} current extension count: ${e.length}`),e.push(s)}}function ig(r,e,t,s,n){if(n!=null&&n.isLambdatestRun())return;if(r.ext||s){let c=typeof r.ext=="string"?r.ext:`${__dirname}/..`,l=s||c,p=`--load-extension=${l}`;is.info(`adding extension: testim unpacked , path: ${l}`),t.push(p);return}let o=r.canary?"-master.zip":".zip",i=au.join(process.cwd(),`testim-headless${o}`),a=lu(i);is.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${cu(a)} current extension count: ${e.length}`),e.push(a)}function Qv(r,e,t,s,n,o,i){var f,h;let a=t.seleniumName||t.browserValue,c=[],l=[...ng];e.headless&&l.push("--headless");let p={prefs:{"profile.default_content_setting_values.popups":ou.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":ou.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};iu(n)&&(p.prefs["download.default_directory"]="C:\\Users\\testnode",r.desiredCapabilities.version="latest-1",r.desiredCapabilities["aws:maxDurationSecs"]=2400,r.desiredCapabilities["aws:idleTimeoutSecs"]=60),iu(n)&&a==="MicrosoftEdge"&&(r.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(p.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(p.prefs["profile.default_content_setting_values.geolocation"]=ou.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(f=e.projectData)==null?void 0:f.defaults)!=null&&h.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(r.desiredCapabilities,{browserName:a});function d(){t.mobileEmulation&&(p.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+tc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}d(),og(s,c,i),e.mode===Q.EXTENSION&&ig(e,c,l,o,i),c.length>0&&(p.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(p.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),p.args=l;let m={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],g={MicrosoftEdge:"ms",chrome:"goog"}[a];return oe.isLambdatestGrid(n)&&delete p.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(r.desiredCapabilities[m]=p),(e.w3cCapabilities||n.type==="testimEnterprise")&&(r.desiredCapabilities[`${g}:${m}`]=p),r}function eE(r,e,t){let s={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"browser.helperApps.neverAsk.saveToDisk":eg.join(","),"browser.helperApps.neverAsk.openFile":eg.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(r.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:s}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(r.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Q.EXTENSION)if(e.ext)r.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=au.join(process.cwd(),`testim-firefox-profile${n}`);r.desiredCapabilities.firefox_profile=lu(o)}return e.headless&&(r.desiredCapabilities["moz:firefoxOptions"].args||(r.desiredCapabilities["moz:firefoxOptions"].args=[]),r.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),r}function tE(r,e,t){let{saucelabs:s}=r;if(s!=null&&s.username&&s.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=s.appiumVersion||t.sl.appiumVersion;let o=(0,sg.cloneDeep)(t.sl);return t.sl.screenResolution&&(n["sauce:options"].screenResolution=t.sl.screenResolution,delete o.screenResolution),Object.assign({},o,s,n)}return Object.assign({},s,n)}return{}}function rE(r,e,t){return ft.isEmpty(r.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,r.browserstack,{name:e})):Object.assign({},r.browserstack,{name:e})}function sE(r){return r.perfecto?r.perfecto:{}}function nE(r,e,t){if(r.experitestToken){let s=e==="safari";return{accessKey:r.experitestToken,browserVersion:"latest",platformName:s?"MAC":"WIN10",seleniumScreenshot:s,newSessionWaitTimeout:t}}return{}}function oE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:n}=r,o=s||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Ca(o,i)),a}function yi(r,e,t,s,n,o,i,a=null){var h,y;if(s.mode==="local"){let v=[],S=[...ng],b={};return r.headless&&S.push("--headless"),r.silentDebuggerExtensionApi&&S.push("--silent-debugger-extension-api"),r.remoteDebuggingPort!==void 0&&S.push(`--remote-debugging-port=${r.remoteDebuggingPort}`),r.chromeExtraArgs&&r.chromeExtraArgs.forEach(w=>S.push(`--${w}`)),r.chromeBinaryLocation&&(b.binary=r.chromeBinaryLocation),r.mode!=="selenium"&&ig(r,v,S,null,a),og(n,v,a),{logLevel:Zf,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:S,extensions:v,...b},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=r,p=oE(r,s),d={hostname:s.host,host:s.host,port:s.port||4444,path:s.path||"/wd/hub",protocol:s.protocol||"http",logLevel:Zf,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,r.getSessionTimeout),getSessionRetries:a.getSessionRetries||r.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ft.isEmpty(p)&&{headers:p},...r.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};iu(s)&&(r.oldCapabilities=!1,r.w3cCapabilities=!0,d.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),r.disableNativeEvents&&(d.desiredCapabilities.nativeEvents=!1),s.user&&s.key&&(s.type==="saucelabs"&&(r.saucelabs||={},r.saucelabs.username||=s.user,r.saucelabs.accessKey||=s.key),s.type==="browserstack"&&(r.browserstack||={},r.browserstack["browserstack.user"]||=s.user,r.browserstack["browserstack.key"]||=s.key)),s.key&&s.type==="perfecto"&&(r.perfecto.securityToken=s.key);let m=Number(r.browserTimeout/1e3),g=r.browser||(t==null?void 0:t.browserValue);ft.merge(d.desiredCapabilities,tE(r,e,t),rE(r,e,t),sE(r),nE(r,g,m),a==null?void 0:a.getCapabilities(r,g,o,i,e));let f=null;switch(!r.ext&&!r.extensionPath&&((h=s.host)!=null&&h.endsWith(".testim.io"))&&!r.canary&&r.mode===Q.EXTENSION&&(g==="chrome"?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),(y=s.host)!=null&&y.endsWith(".testim.io")&&g==="edge-chromium"&&(d.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":d=Zv(d,r,t,n,s,f,a);break;case"firefox":d=eE(d,r,a);break;case"safari":case"safari technology preview":d=Xv(d,g);break;default:break}ft.merge(d.desiredCapabilities,r.seleniumCapsFileContent);try{let v={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},S=k=>k[s.provider]||k[d.host]||k[v[d.host]],b=k=>{var O,j;return S(k)||k[(O=d.desiredCapabilities)==null?void 0:O.browserName]||k[(j=d.desiredCapabilities)==null?void 0:j.version]||k||{}},w=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),x=b(b(w));Object.keys(x).length&&(is.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(d.desiredCapabilities,x))}catch(v){is.error("Failed to load custom capabilities",{error:v,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return d.desiredCapabilities&&!d.capabilities&&(Yv(d),d.capabilities={alwaysMatch:d.desiredCapabilities,firstMatch:[{}]},delete d.desiredCapabilities),d.hostname=d.host,d}function uu({nativeApp:r,appPath:e,gridInfo:t}){if(!r&&!e)throw Error("missing mobile app!");let s=[N.BROWSERSTACK,N.SAUCELABS,N.TESTIM_HEADSPIN,N.TESTIM_TDC];if(t.mode!=="local"&&!s.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function iE({deviceUdid:r,gridInfo:e,testRunConfig:t}){let{staticAllocation:s}=(t==null?void 0:t.mobile)||{};if(e.type!==N.TESTIM_TDC&&e.type!==N.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!r&&!(s!=null&&s.deviceUdid))throw Error("missing device udid or test run config is not static")}function ag(r,e,t){let{fullReset:s,resetAppData:n,skipLoadBalancer:o}=e,{executionId:i,testResultId:a}=t,c=r===N.TESTIM_TDC?"tdc":"headspin";return{[`${c}:capture`]:!0,...o&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:[{executionId:i},{testResultId:a}],...!s&&!n&&{"appium:noReset":!0},...!s&&n&&{"appium:noReset":!1}}}function cg({projectType:r,sessionCaps:e,options:t,nativeApp:s,appPath:n,androidActivityWait:o,isHSAppIdExists:i,isTdcAppIdExists:a}){let{fullReset:c,resetAppData:l,resetOnSessionStartOnly:p}=t,d={"appium:app":n};switch(i&&(d={"headspin:app.id":n}),a&&(d={"tdc:app.id":n}),r){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...c&&{"appium:fullReset":c,"appium:resetOnSessionStartOnly":p},...s&&{"appium:bundleId":s.id},...n&&d};case"android":return{...e,platformName:"Android",...c&&{"appium:fullReset":c},...!c&&l&&{"appium:autoGrantPermissions":!0},"appium:automationName":"UiAutomator2","appium:appWaitActivity":o,...s&&{"appium:appPackage":s.id||s.packageName,"appium:appActivity":s.activity},...n&&d};default:throw Error(`unsupported mobile project ${r}`)}}function lg({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,sessionTags:n,options:o,isHSAppIdExists:i}){let a=ag(N.TESTIM_HEADSPIN,o,n);return a=cg({projectType:r,sessionCaps:a,options:o,nativeApp:e,appPath:t,androidActivityWait:s,isHSAppIdExists:i}),a}function ug({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,sessionTags:n,options:o,isTdcAppIdExists:i}){let a=ag(N.TESTIM_TDC,o,n);return a=cg({projectType:r,sessionCaps:a,options:o,nativeApp:e,appPath:t,androidActivityWait:s,isTdcAppIdExists:i}),a}function aE({osVersion:r,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:s}=e;return r||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:s!=null&&s.osVersionRegex?s==null?void 0:s.osVersionRegex:".*")}function cE({deviceName:r,mobileConfig:e,projectType:t}){let{staticAllocation:s,dynamicAllocation:n,selectedGrid:o}=e;return r||(s!=null&&s.deviceName?s.deviceName:n!=null&&n.deviceNameRegex?n.deviceNameRegex:(o==null?void 0:o.type)===N.BROWSERSTACK&&t==="ios"?"iPhone.*":".*")}function lE({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,p=(a==null?void 0:a.mobile)||{},{type:d}=o,m=d===N.BROWSERSTACK?"browserstack":"saucelabs",g=aE({osVersion:c,mobileConfig:p}),f=cE({deviceName:l,mobileConfig:p,projectType:r}),h={...d===N.BROWSERSTACK&&{os_version:g,device:f,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...d===N.SAUCELABS&&{platformVersion:g,deviceName:f,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${m}.user`]:o.user,[`${m}.key`]:o.key,[`${m}.debug`]:!0,[`${m}.networkLogs`]:!0};switch(r){case"ios":return{...h,autoAcceptAlerts:!0,platformName:"iOS",automationName:"XCUITest",...e&&{bundleId:e.id},...t&&{app:t}};case"android":return{...h,autoGrantPermissions:!0,platformName:"Android",automationName:"UiAutomator2",appWaitActivity:s,...e&&{appPackage:e.id||e.packageName,appActivity:e.activity},...t&&{app:t}};default:throw Error(`unsupported mobile project ${r}`)}}function pg(r){return N.TESTIM_HEADSPIN===r.gridInfo.type?lg(r):N.TESTIM_TDC===r.gridInfo.type?ug(r):lE(r)}function dg(r){return uu(r),pg(r)}function uE(r,e){var l,p;let{staticAllocation:t,dynamicAllocation:s,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=r,c={};return n==="dynamic"&&(!o&&((l=s==null?void 0:s.selector)!=null&&l.manufacturer)&&(c.manufacturer=s.selector.manufacturer),!i&&((p=s==null?void 0:s.selector)!=null&&p.osVersion)&&(c.os_version=s.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),o&&(c.manufacturer=o),i&&(c.os_version=i),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}function mg(r){let{gridInfo:e,nativeApp:t,options:s,appPath:n,testRunConfig:o}=r,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);uu({nativeApp:t,appPath:n,gridInfo:e});let a=Xf(e),c=pg(r);if(e.type===N.TESTIM_HEADSPIN||e.type===N.TESTIM_TDC){let l=e.type===N.TESTIM_HEADSPIN?"headspin":"tdc",p=uE(s,o==null?void 0:o.mobile);if(!ft.isEmpty(p)){let d=Object.entries(p).map(([m,g])=>g.split(",").map(f=>f===".*"?"":`${m}:${f}`).join(",")).join(" ");c[`${l}:selector`]=d}}return{...a,desiredCapabilities:c,capabilities:c,connectionRetryCount:0,logLevel:s.appiumLogLevel}}async function fg(r){var y,v;let{projectType:e,gridInfo:t,nativeApp:s,options:n,appPath:o,androidActivityWait:i,sessionTags:a,isHSAppIdExists:c,isTdcAppIdExists:l,testRunConfig:p}=r,{deviceUdid:d}=n;uu({nativeApp:s,appPath:o,gridInfo:t}),iE({deviceUdid:d,gridInfo:t,testRunConfig:p});let m=await Yf(t,d),g=t.type===N.TESTIM_TDC,f={projectType:e,nativeApp:s,appPath:o,androidActivityWait:i,options:n,sessionTags:a,...!g&&{isHSAppIdExists:c},...g&&{isTdcAppIdExists:l},testRunConfig:p},h=g?ug(f):lg(f);return(v=(y=p==null?void 0:p.mobile)==null?void 0:y.staticAllocation)!=null&&v.deviceUdid&&(h["appium:udid"]=p.mobile.staticAllocation.deviceUdid),d&&(h["appium:udid"]=d),{...m,desiredCapabilities:h,capabilities:h,connectionRetryCount:0,logLevel:n.appiumLogLevel}}var tg,au,rg,ft,sg,is,Zf,ou,ng,cu,iu,Yv,Zv,eg,yn=T(()=>{"use strict";tg=E(require("fs")),au=E(require("path")),rg=E(require("crypto")),ft=E(require("lodash"));B();le();$();he();ce();qo();hi();sg=require("lodash"),is=A("testim-desired-capabilities-builder"),Zf=Kn?"debug":"silent",ou={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ng=["--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"],cu=(...r)=>rg.createHash("sha256").update(r.join("")).digest("hex"),iu=r=>r.type===N.DEVICE_FARM||r.type===N.HYBRID&&r.provider==="devicefarm",Yv=r=>{var s;let{desiredCapabilities:e}=r;Object.prototype.hasOwnProperty.call(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.prototype.hasOwnProperty.call(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.prototype.hasOwnProperty.call(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.prototype.hasOwnProperty.call(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.prototype.hasOwnProperty.call(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.prototype.hasOwnProperty.call(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((s=e["goog:chromeOptions"])==null?void 0:s.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in r.desiredCapabilities&&(r.user=r.desiredCapabilities.username,delete r.desiredCapabilities.username),"accessKey"in r.desiredCapabilities&&(r.key=r.desiredCapabilities.accessKey,delete r.desiredCapabilities.accessKey);let t;try{t=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{is.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};Zv=ft.memoize(Qv,(r,e,t,s,n,o)=>{let i=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(ft.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return cu(i,a,c,s,l,o)}),eg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Me(r){var e,t,s,n,o,i,a;return((e=r.message)==null?void 0:e.match(/Command not found/))||r.message==="HTTP method not allowed"||r.message==="Unknown error"||((t=r.message)==null?void 0:t.match(/Unknown timeout type/))||r.name==="unknown command"||((s=r.message)==null?void 0:s.match(/did not match a known command/))||((n=r.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=r.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=r.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=r.message)==null?void 0:a.match(/\.\w* is not a function/))}function gg(r,e,t){if(!e||!r)return r;if(r.includes("%"))return r.replace(/ /g,"%20");try{return decodeURI(r)!==r?r:encodeURI(r)}catch(s){return t&&t.warn("tried to encode url but failed",{err:s,url:r}),r}}var pu=T(()=>{"use strict"});function du(r){function e(m){return m?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(m.nodeType):!1}function t(m){return m?s(m.parentNode,e):null}function s(m,g){for(let f=m;f&&f!==m.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(m,g){for(let f=m;f&&f!==m.ownerDocument;f=t(f))if(g(f))return f;return null}function o(m,g){if(!m||!g)return null;m instanceof DocumentFragment&&(m=m.host);let h=window.getComputedStyle(m).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(m);return o(y,g)}function i(m){let g=m.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(m.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(m,"stroke-width");return!!h&&parseInt(h,10)>0}return o(m,"overflow")==="hidden"?!1:Array.from(m.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(m){return o(m,"overflow")==="hidden"}function c(m){return!m||!a(m)||!m.childNodes.length?!1:Array.from(m.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function l(m){var g;return m?(g=m.parentNode)!=null&&g.host?!0:l(m.parentNode):!1}if(!r||!l(r)&&!document.contains(r))return!1;switch(r.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=s(r,f=>f.tagName.toUpperCase()==="SELECT");return du(g)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(o(r,"visibility")!=="visible")return!1;let p=!!n(r,m=>Number(o(m,"opacity"))===0),d=!!n(r,m=>o(m,"display")==="none");return!(p||d||!i(r)||c(r))}var hg=T(()=>{"use strict"});var yg,bg,bn,pE,dE,Ti,Tg=T(()=>{"use strict";yg=E(require("promise-queue")),bg=E(require("webdriverio"));le();Ue();B();$();kr();hg();pu();os();bn=A("WebDriverApi"),pE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},dE={implicit:0,pageLoad:1,script:2},Ti=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:s,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw bn.warn("error from selenium",{err:e,testResultId:n,testName:s,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof La<"u"&&(e=La);let t=1/0;this.queue=new yg.default(e,t)}async addToQueue(e){var s,n;let t=(s=this.seleniumPerfStats)==null?void 0:s.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,s){var o,i;this.testName=t,this.testResultId=s,e.deprecationWarnings=!1,this.initQueueRequests(),D("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{bn.info("requesting browser",{testResultId:s,testName:t}),D("before this.client.init"),this.client=await bg.remote(e)}),D("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ae.GET_BROWSER)}}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){bn.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Me(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Me(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let s=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return s!=null&&s.targetInfos?s.targetInfos:[]}async takeScreenshot(){var t,s;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ae.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(s=this.seleniumPerfStats)==null||s.markEnd(e,Ae.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ae.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(_e(e)))}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),s=()=>this.execute(du,{ELEMENT:e,[Bt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return s();try{return await t()}catch(n){if(Me(n))return this.unsupportedActions.add("elementIdDisplayed"),s();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(gg(e,this.isSafari(),bn))})}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 s=()=>{let o=[];return o[dE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await s()}catch(o){if(Me(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(n,o){window.scrollTo(n,o)};return this.execute(s,e,t)}async setValue(e,t){return await this.elementIdClear(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(pE);if(typeof e=="string"&&e.match(/(width|height)/)){let s=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[s]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async keys(e){let t=i=>Aa.hasOwnProperty(i)?[Aa[i]]:i.split(""),s=[];if(typeof e=="string")s=t(e);else if(Array.isArray(e))for(let i of e)s=s.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:s})},o=()=>{let i=s.map(c=>({type:"keyDown",value:c})),a=s.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Me(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let s=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,s)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(_e(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),s=await t.$('button[type="submit"]');return await s.isExisting()?s.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,s){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:s})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(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,s){let n={...typeof t=="number"&&{xOffset:t},...typeof s=="number"&&{yOffset:s}};return this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.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 s=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);s=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return s();try{return await n()}catch(o){if(Me(o))return this.unsupportedActions.add("windowHandleSize"),s();throw o}})}}setCookie(e,t,s,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var s;return(await((s=this.client)==null?void 0:s.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(){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 s;return(s=this.client)==null?void 0:s.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 s;return(s=this.client)==null?void 0:s.isAppInstalled(e)});return bn.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 wg={};W(wg,{doubleClick:()=>mE});var mE,vg=T(()=>{"use strict";mE=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let n=r.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(m){function g(S,b,w){return w>S&&w<b}let f=m.pointerPosition||{},h=s.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,v=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:v}},a=function(m,g){return{screenX:0,screenY:0,clientX:m,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(m,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(m,h)},l=function(m,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(m,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},p=function(){var g;let m=document.activeElement;for(;(g=m.shadowRoot)!=null&&g.activeElement;)m=m.shadowRoot.activeElement;return m},d=function(m){let g=i(m),f=m.event;return t.includes(f)?c(f,g.x,g.y):l(f,g.x,g.y)};try{n.map(g=>d(g)).filter(Boolean).forEach(g=>s.dispatchEvent(g));let m=p();dispatchFocus(r.elementToFocusLocatedElement,m),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(m){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:m.toString(),success:!1})}}});var Tn={};W(Tn,{dispatchFocus:()=>fE});function fE(r,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function s(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=s();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(r){let o=getLocatedElement(r);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var wn=T(()=>{"use strict"});var xg={};W(xg,{WebDriver:()=>Sr});async function bE(r){var e,t;try{let s=(t=(e=r==null?void 0:r.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return s?await hE(s):void 0}catch(s){Ve.info("Error getting cdpAddress",s);return}}var as,Rg,Ig,Ve,Zt,gE,Eg,hE,er,yE,Sg,Er,Sr,vn=T(()=>{"use strict";as=E(require("lodash"));B();Ue();yn();Rg=E(require("p-retry")),Ig=E(require("ua-parser-js"));kr();$();pu();Tg();z();he();os();Ve=A("webdriver"),[Zt,gE]=[0,2],{extractElementId:Eg,getCdpAddressForHost:hE}=K,er=()=>(Te(),fe(Kt)).getSessionPlayer().codeSnippets,yE=()=>(Te(),fe(Kt)).getSessionPlayer().locatorBuilderUtils,Sg=()=>(Te(),fe(Kt)).getSessionPlayer().utils,Er=()=>(Te(),fe(Kt)).getSessionPlayer().positionUtils;Sr=class extends Ti{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}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(s=>s!==t)}async init(t,s,n,o,i,a,c,l=new Ut,p=!1,d=void 0){var h,y,v,S,b,w,x,k;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(y=(h=t==null?void 0:t.company)==null?void 0:h.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let m=yi(t,s,n,o,i,a,c,d);m.desiredCapabilities&&delete m.desiredCapabilities.marionette,m.capabilities&&delete m.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(d==null?void 0:d.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=l;let g=p?0:1500,f=p?()=>null:()=>this.executeJS("window.focus()");try{D("before initClient in webdriver.js init");let O=await this.initClient(m,s,c);D("after initResult before getCdpAddress in init"),this.cdpUrl=await bE(O),D("after getCdpAddress in webdriver.js init"),Ve.info(`init new session testName: ${s}`,{sessionId:this.getSessionId(),testResultId:c}),await se(g),M.flags.dontFocusOnInit.isEnabled()||await f(),D("after focus and delay in webdriver.js init")}catch(O){let j=JSON.stringify(as.omit(m,"capabilities.extensions","capabilities.capabilities.extensions"));Ve.error("failed to init webdriver",{err:O,capabilitiesAsString:j});let R=((b=(S=t==null?void 0:t.company)==null?void 0:S.activePlan)==null?void 0:b.plan)==="free";throw(w=O.stack)!=null&&w.includes("at startWebDriverSession")&&((x=O.message)!=null&&x.startsWith("Failed to create session"))&&((k=O.message)!=null&&k.includes("Timeout awaiting 'request'"))&&R?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):O.message.match(/Invalid username or password/)?new Mr(O.message):O.message.match(/capabilit(y|ies)/)?new Yn(O.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>as.zip(o.slice(0,-1),o.slice(1)),s=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(s).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let s=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(p=>p.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=te();s(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ve.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ve.warn("failed to click on alert",{err:c}));return}if(Ve.warn("err while getting testim status",{err:a}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4)}async switchToLocatedFrame(t){let s=await this.getElement(t),n=Eg(s.value);return await this.switchToFrame({ELEMENT:n,[Bt]:n}),s}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(s){throw(t=s.message)!=null&&t.includes("ECONNREFUSED")?new Xn:s}}async getElement(t){var o;let s=this.seleniumPerfStats.markStart(Ae.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(s,Ae.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
22
|
-
var fn = ${
|
|
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),i}}async function jT(){let s=`${Or}/extension/sessionPlayer_LATEST_RELEASE`;return(await _t(s)).body.toString("utf8")}async function $T(s,e){if(!Be(s)||Be(s)&&e||Ce)return s;let t=await jT();return`${s}-${t}`}function dc(){let s=at();return qr.resolve(s,"testim-bin")}function WT(){let s=dc();return qr.resolve(s,"sessionPlayer.zip")}async function Fd(s,e,t=!1){try{return await Qn(s,e),await Ze(e,dc())}catch(r){if(t)throw r;return await Fd(s,e,!0)}}async function hr(s,e){ho.info("prepare player",{location:s,canary:e});let t=WT();return ct(async()=>{let r=await $T(s,e);return await Fd(r,t),{}},"preparePlayer",Ud,[s,e,t])()}var Dd,Md,qr,Nd,ho,Ud,lc,Ld,zr=T(()=>{"use strict";Dd=E(require("ms")),Md=E(require("fs")),qr=E(require("path"));le();qt();Nd=require("serialize-error");B();oc();z();j();ho=x("prepare runner and testim start"),Ud=(0,Dd.default)("0.5 day"),lc=16,Ld=`The size of the custom extension is more than ${lc}MB`});function GT(){let s=qs.type().toLowerCase();return s==="darwin"?qs.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?qs.arch()==="x64"?"win64":"win32":"linux"}async function bo(){let s=GT(),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 P(`Unsupported platform: ${s}`);let r=parseInt(zs,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${zs}/${n[s]}.zip`,a=yo.join(mc,n[s]),c=`${a}.zip`,l=yo.join(a,o[s]);if(await ge(l))return l;if(!await ge(c)){let m=(0,fc.default)("Downloading Chromium").start();try{await Bd.promises.mkdir(mc),await He(i,c)}catch(p){let g=`Failed to download Chromium: ${p.message}`;throw m.fail(g),new Error(g)}m.succeed()}let d=(0,fc.default)("Extracting Chromium").start();try{await Ze(c,mc)}catch(m){let p=`Failed to extract Chromium: ${m.message}`;throw d.fail(p),new Error(p)}return d.succeed(),l}var Bd,qs,yo,fc,zs,mc,gc=T(()=>{"use strict";Bd=E(require("fs")),qs=E(require("os")),yo=E(require("path")),fc=E(require("ora"));z();j();zs="1000968",mc=yo.join(Dt,`chrome-${zs}`)});async function $d(s,e){return To=s,Tc=e,await hc()}function Wd(s,e,t){et=s.token,To=e,Tc=t,Js=wc(et),Ys=s.refreshToken,yc=s.ngrokToken,bc=s.isNgrokWhitelisted}function VT(s=To,e=Tc){return ct(()=>(Ks.info("request to get cli token from server"),je({url:`${me}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",jd*10,{projectId:s,token:e})()}async function HT(){Ks.info("request to refresh JWT cli token from server");let s=await je({url:`${me}/auth/refreshToken`,body:{token:et,refreshToken:Ys}});return et=s.token,Js=wc(et),s.refreshToken&&(Ys=s.refreshToken),et}async function hc(){try{let s=await VT();return Ks.info("successfully get cli token from server"),et=s.token,Js=wc(et),Ys=s.refreshToken,yc=s.ngrokToken,bc=s.isNgrokWhitelisted,et}catch(s){throw s.message.includes("Unauthorized")?new P("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."):(Ks.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:To}),new P(`While trying to retrieve CLI token, caught error: ${s}`))}}function wc(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Kt(){if(!Js)return hc();if(Js<Date.now()+4*jd)try{return await HT()}catch(s){return Ks.error("failed to refresh token, executing fallback",s),hc()}return et}function wo(){return Ys}function Mt(){return et?{uid:require("jsonwebtoken").decode(et).id,ngrokToken:yc,isNgrokWhitelisted:bc}:{}}var Ks,et,Js,Ys,yc,bc,To,Tc,jd,Rt=T(()=>{"use strict";le();Ve();qt();z();B();Ks=x("testim-custom-token"),To=null,Tc=null,jd=5*60*1e3});var Gd={};G(Gd,{isCi:()=>Kr});var Kr,vo=T(()=>{"use strict";Kr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var _e={};G(_e,{addTestRetry:()=>Hc,clearTestResult:()=>Wc,deleteCloudflareTunnel:()=>Jc,fetchLambdatestConfig:()=>Bc,forceUpdateCloudflareTunnelRoutes:()=>Kc,getAllGrids:()=>Fc,getAppDetails:()=>kc,getApplitoolsIntegrationData:()=>qc,getCloudflareTunnel:()=>zc,getEditorUrl:()=>QT,getGridById:()=>Ro,getGridByName:()=>Nc,getHybridGridProvider:()=>Mc,getLabFeaturesByProjectId:()=>jc,getMobileDevicesFromGrid:()=>Xc,getRealData:()=>$c,getS3Artifact:()=>Xs,getS3ArtifactText:()=>Ec,getSuiteTestList:()=>Cc,getTestPlan:()=>XT,getTestPlanTestList:()=>Pc,getTestResults:()=>br,getUsageForCurrentBillingPeriod:()=>Oc,initializeUserWithAuth:()=>Uc,isTestResultCompleted:()=>_c,keepAliveGrid:()=>Lc,loadSfdcCredential:()=>Sc,loadTest:()=>Rc,releaseGridSlot:()=>Dc,reportExecutionFinished:()=>So,reportExecutionStarted:()=>Ac,saveRemoteStep:()=>Gc,saveTestPlanResult:()=>Ic,updateExecutionTests:()=>xc,updateRemoteRunFailure:()=>Yc,updateTestDataArtifact:()=>xo,updateTestResult:()=>Io,updateTestStatus:()=>yr,uploadAppToBrowserStack:()=>Qc,uploadRunDataArtifact:()=>Vc});async function Jr(){let s=await Kt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Ke({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await Jr(),i=Object.assign({},t,o);return je({url:`${me}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function KT(s,e,t,r={},n=void 0){let o=await Jr(),i=Object.assign({},r,o);return await Ls(`${me}${s||""}`,e,t,i,n)}async function Eo(s,e){let t=await Jr();return await ja(`${me}${s||""}`,e,t)}async function JT(s,e){let t=await Jr();return await _s(`${me}${s||""}`,e,t)}async function YT(s,e){let t=await Jr();return await Ba(`${me}${s||""}`,e||void 0,t)}async function Ie(s,e,t,r){let n=await Jr();return await Ne(`${me}${s||""}`,e||void 0,n,r,t)}function Xs(s,e){return(0,Z.default)(()=>Ie(`/storage${s}`,null,{isBinary:!0},e),{retries:se,factor:1})}function Ec(s){return(0,Z.default)(()=>YT(`/storage${s}`))}async function XT(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Z.default)(()=>Ie("/testPlan",{projectId:s,name:e.join(",")}),{retries:se,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function Sc({branch:s,projectId:e}){let t=await(0,Z.default)(()=>Ie(`/branch/branchData/${s}`,{projectId:e}),{retries:se,factor:1});return t==null?void 0:t.sfdcCredential}function Rc({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Z.default)(()=>Ie(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:se,factor:1})}function Ic(s,e,t){return(0,Z.default)(()=>Ke({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:se,factor:1})}function yr(s,e,t,r,n,o,i=se){return(0,Z.default)(()=>Eo("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:qT,...o}),{retries:i,factor:1})}function xc(s,e,t,r,n,o,i,a){return(0,Z.default)(()=>Eo("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:se,factor:1})}async function Ac({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(vo(),Gd));return Ke({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function So(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,Z.default)(()=>Eo("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:se,factor:1})}async function Pc(s,e,t,r,n){return(0,Z.default)(()=>Ke({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:se,factor:1})}function Cc({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}){return(0,Z.default)(()=>Ke({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:se,factor:1})}async function kc({appId:s,projectId:e}){try{return await(0,Z.default)(()=>Ie(`/mobile-app/app/${s}?projectId=${e}`),{retries:se,factor:1})}catch(t){Ut.error("failed getting application details",{appId:s,error:t});return}}async function Oc(s){try{return await(0,Z.default)(()=>Ie(`/plan/project/${s}/usage-current-billing-period`),{retries:se,factor:1})}catch(e){Ut.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function _c(s,e,t){return(0,Z.default)(()=>Ie(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:se,factor:1})}function br(s,e,t,r){return(0,Z.default)(()=>Ie(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:se,factor:1})}function Lc(s,e){return Ke({url:`/grid/keep-alive?reqId=${te()}`,body:{projectId:s,slots:e},timeout:1e4})}function Dc(s,e,t,r,n){return Ke({url:`/grid/release?reqId=${te()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Mc(s){return Ke({url:"/grid/hybrid/provider",body:s})}function Nc(s,e,t,r,n){return(0,Z.default)(()=>Ie("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:te()}),{retries:se,factor:1})}function Ro(s,e,t,r,n){return(0,Z.default)(()=>Ie(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:te()}),{retries:se,factor:1})}async function Uc({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n}){var o,i;try{return await(0,Z.default)(()=>je({url:`${me}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n}}),{retries:se,factor:1})}catch(a){throw Ut.error("error initializing info from server",a),(o=a==null?void 0:a.message)!=null&&o.includes("Bad Request")?new P("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."):(i=a==null?void 0:a.code)!=null&&i.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):a}}async function QT(){if(kr)return{editorUrl:kr};try{return await(0,Z.default)(()=>Ie("/system-info/editor-url"),{retries:se,onFailedAttempt:s=>{if(s.attemptNumber>=se)throw s},factor:1})}catch{return Ut.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function Fc(s){return(0,Z.default)(()=>Ie("/grid",{companyId:s}),{retries:se,factor:1})}function $c(s,e,t){return(0,Z.default)(()=>Ie(`/real-data/${e}?${t}&projectId=${s}`),{retries:se,factor:1})}function Io(s,e,t,r,n){return(0,Z.default)(()=>Ke({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:se,factor:1})}function Wc(s,e,t,r){return(0,Z.default)(()=>Ke({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:se,factor:1})}function Gc(s,e,t,r){return(0,Z.default)(()=>Ke({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:se,factor:1})}function ZT(s){return s.startsWith("/")?s:`/${s}`}function ew(s,e,t){let r=ZT(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Hd(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${te()}${i||""}`,c=`${e}/${t}/${a}`,l=ew(c,"test-result-artifacts",s),d=Buffer.from(Vd.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Z.default)(()=>KT(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:se,factor:1}),l}function Hc({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,Z.default)(()=>Ke({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:se,factor:1})}async function qc(s){try{return await Ie(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Ut.warn("could'nt get applitools integration data.",{err:e}),{}}}async function zc(s,e){try{return await Eo("/tunnel",{companyId:s,routes:e})}catch(t){return Ut.warn("could'nt get tunnel.",{err:t}),{}}}async function Kc(s,e){try{return await Ke({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Ut.warn("could'nt get tunnel.",{err:t});return}}async function Jc(s,e){try{return await JT(`/tunnel/${e}`,{companyId:s})}catch(t){Ut.warn("could'nt get tunnel.",{err:t});return}}function Yc(s){return je({url:`${me}/result/remoteRunFailure`,body:s})}async function Xc({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${zT}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,Z.default)(()=>Ie(o,{projectId:s}),{retries:se,factor:1})}catch(i){return Ut.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function Qc({projectId:s,gridId:e,app:t,timeout:r}){return(0,Z.default)(()=>Ke({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:se,factor:1})}var Jt,Vd,Z,vc,qT,Ut,se,zT,Bc,jc,Vc,xo,ye=T(()=>{"use strict";Jt=E(require("lodash")),Vd=E(require("pako"));j();le();ce();Ve();Rt();Z=E(require("p-retry")),vc=E(require("object-hash"));z();B();qT=it(),Ut=x("testim service api"),se=3,zT="/grid";Bc=async()=>(0,Z.default)(()=>Ie("/grid/lt/config"),{retries:se,factor:1}),jc=async s=>(0,Z.default)(()=>Ie(`/labFeature/v2/project/${s}`),{retries:se,factor:1});Vc=Jt.memoize(async(s,e,t,r)=>{if(!Jt.isEmpty(r))return await Hd(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,vc.default)(r)}:${e}:${t}`),xo=Jt.memoize(async(s,e,t,r,n)=>!r||Jt.isEmpty(r)?void 0:await Hd(s,e,t,JSON.stringify((()=>{let i=Jt.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&Object.assign(i,{[c]:Ka.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,vc.default)(r)}:${e}:${t}`)});var Yt={};G(Yt,{getSessionPlayer:()=>ee,options:()=>el});var Ao,el,Zc,ee,be=T(()=>{"use strict";Ao=require("path"),el={playerPath:void 0},ee=()=>{if(Zc)return Zc;let s=(Fe(),fe(Ue));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(zr(),fe(Hs)),t=e(),r=el.playerPath?(0,Ao.resolve)(el.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ao.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Zc=n,n}});function sw(s){process.nextTick(()=>{if([Y.SELENIUM,Y.APPIUM].includes(s))try{(be(),fe(Yt)).getSessionPlayer(),require("jsdom")}catch{}})}async function Qs(s){let{project:e,token:t,lightweightMode:r,useLocalChromeDriver:n,useChromeLauncher:o,mode:i}=s,a=Boolean(r==null?void 0:r.general),c=Boolean(n||o),l=a?rw:tw;L("before initializeUserWithAuth");let d=await ct(async()=>(sw(i),await Uc({projectId:e,token:t,branchName:s.branch,lightweightMode:r,localGrid:c})),"initializeUserWithAuth",l,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:a,localGrid:c})();return L("after initializeUserWithAuth"),Wd(d.authData,s.project,s.token),d}var tw,rw,qd=T(()=>{"use strict";Fe();ye();qt();Rt();ce();tw=1e3*60*5,rw=1e3*60*60*10});async function Jd(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await bo():s.chromeBinaryLocation,e=gr({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!==Y.EXTENSION&&await hr(s.playerLocation,s.canary),s.mode===Y.EXTENSION&&!s.ext&&await pc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await uc(s.installCustomExtension,n)}return await e,t}async function Yd(s){var i;nw.info("prepare MockNetwork",{location:s});let e=await Va(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>zd*1e6)throw new Error(`${tl} exceeded ${zd}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${tl} cannot be parsed.${Po.EOL}${a}`)}let n=new Kd.default;if(!n.validate(sc,r)){let a=(i=n.errors)==null?void 0:i.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Po.EOL);throw new Error(`${tl} is malformed.${Po.EOL}${a}`)}return r.entries}var Po,Kd,zd,tl,nw,rl=T(()=>{"use strict";Po=E(require("os"));j();id();zr();Kd=E(require("ajv"));ce();gc();qd();zd=1,tl="JSON file supplied to --mock-network-pattern",nw=(B(),fe(La)).getLogger("prepare runner")});function Qd(s,e=process){async function t(r){await ae(ie(Xd,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Zs.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(Zs.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",()=>{Zs.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Zs.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Zs.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function Yr(s){Xd.push(s)}var Zs,Xd,en=T(()=>{"use strict";B();j();Zs=x("process-handler"),Xd=[]});function il(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?Pp:Or}/extension/testim-firefox-profile${t}`,n=`${e?Cp:Or}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function sm(s){let{chrome:e,firefox:t}=il(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function ko(s){let e=`${Or}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Oo=T(()=>{"use strict";le()});function cm(s){Ce||(s!=null&&s.userId||(s={anonymousId:am}),im.identify(s))}function lt(s,e){return tn("ci",s,e)}function tn(s,e,t){if(Ce)return;let r=s?{userId:s}:{anonymousId:am};im.track(Object.assign(r,{event:e,properties:t}))}var om,im,am,Xr=T(()=>{"use strict";le();om=E(require("analytics-node")),im=new om.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),am=require("crypto").randomBytes(20).toString("hex")});function lm(s){return s.start&&tn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function um(s){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,r=!1,n=!1,o=!1;if(s.start&&(o=!0),Number.isNaN(s.agentPort))throw new P("Agent port is not number");if(typeof s.agent=="string"&&e.some(a=>s.agent.includes(a))){let a=s.agent.split(",").map(c=>c.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(r=!0),a.includes("playground-selenium")&&(n=!0)}let i=ko(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,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:r,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||i,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var pm=T(()=>{"use strict";Oo();Xr();z()});function Lo(s){let{platform:e}=process;e==="win32"?(0,_o.exec)(`start chrome ${s}`):e==="darwin"?(0,_o.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,_o.exec)(`google-chrome ${s}`)}var _o,al=T(()=>{"use strict";_o=require("child_process")});var sn={};G(sn,{doLogin:()=>pl,getProjectId:()=>pw,getToken:()=>dw});async function pw(){return fm("projectId")}async function dw(){return fm("token")}function mm(s,e){return Promise.race([s,oe(e).then(()=>{throw new re("timeout")})])}async function mw(){let s=(await import("express")).default(),e=async function(){return mm(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ye(),_e)),{editorUrl:n}=await r();Lo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function pl({overwriteExisting:s=!0,projects:e=null}={}){let t=cl.homedir(),r=ll.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await mm(mw(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await dm(r,o);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await i({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}))});o.token=l.project.ci.token,o.projectId=l.project.id,await dm(r,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function dm(s,e){await ul.promises.writeFile(s,Do.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function fm(s){let e=cl.homedir(),t=ll.join(e,".testim"),r=await ge(t),n={};if(r)try{n=Do.parse((await ul.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var cl,ll,Do,ul,Qr=T(()=>{"use strict";cl=E(require("os")),ll=E(require("path")),Do=E(require("yaml"));j();ul=require("fs");z();al()});var wm={};G(wm,{process:()=>vw});var ml,hm,fl,ym,Ft,De,bm,fw,Le,yl,gw,hw,gm,Tm,yw,gl,hl,bl,SI,dl,It,bw,u,Tw,ww,vw,vm=T(()=>{"use strict";ml=E(require("ms")),hm=E(require("chalk")),fl=E(require("fs")),ym=E(require("url")),Ft=E(require("lodash")),De=E(require("path"));j();Oo();pm();qt();bm=require("commander");ce();z();Cr();j();fw=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Le=(s,e)=>(e.push(s),e),yl=new bm.Command,gw=s=>s.split(","),hw=(s,e)=>!s||s.length===0?e:s,gm=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Tm=()=>{function s(f){return f.includes("-h, --help")}function e(f){return f.includes("--params [params-json-string]")}function t(f){return f.includes("--ext")||f.includes("--extension-path")}function r(f){return f.includes("--player-path")||f.includes("--player-require-path")}function n(f){return f.includes("--executionId")||f.includes("--source")||f.includes("--resultId")||f.includes("--remoteRunId")||f.includes("--schedulerId")}function o(f){return f.includes("--get-browser-timeout")||f.includes("--get-browser-retries")||f.includes("--get-session-timeout")||f.includes("--get-session-retries")||f.includes("--driver-request-timeout")||f.includes("--driver-request-retries")}function i(f){return f.includes("--user")}function a(f){return f.includes("shouldMonitorPerformance")}function c(f){return f.includes("--save-rca-locally")}function l(f){return f.includes("--exit-code-ignore-failing-tests")}function d(f){return f.includes("--high-speed")}function m(f){return f.includes("--urls")}function p(f){return f.includes("--test-start-timeout")}function g(f){return f.includes("--install-lazy-deps")}yl.help(f=>f.split(`
|
|
17
|
+
`).filter(y=>!t(y)&&!e(y)&&!s(y)&&!r(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!c(y)&&!l(y)&&!d(y)&&!m(y)&&!p(y)&&!g(y)).join(`
|
|
18
|
+
`))},yw=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(hm.default.yellow(`
|
|
19
|
+
WARNING: ${s} is deprecated. ${t}
|
|
20
|
+
`))},gl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:hl,argv:bl,stdout:SI,exit:dl,cwd:It}=global.process,bw=["trace","debug","info","warn","error","silent"];Xa(bl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));yl.description("Testim.io CLI").option("-h --help","output usage information",Tm).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",Le,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Le,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Le,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Le,[]).option("-l, --label [label]","labels to search test by",Le,[]).option("-n, --name [test-name]","test name to run",Le,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",gw).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--is-regression-baseline-run","save doms and run results as regression baseline data").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Le,[]).option("--test-plan-id [test-plan-id]","test plan to run",Le,[]).option("--suite [suite-name]","suite to run",Le,[]).option("--suite-id [suite-id]","suite ID to run",Le,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Le,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--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("-rad --reset-app-data [reset-app-data]","set noReset appium capability to false, noReset capability is true by default",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(hl.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,ml.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,ml.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: ${gl.join("/")}`,Le,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Le,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Le,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Le,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Le,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(bl);u=yl.opts(),Tw=()=>{u.grid||u.gridId||(u.host||(u.host="ondemand.saucelabs.com"),u.port||(u.port=80))},ww=()=>{u.grid||u.gridId||(u.host||(u.host="hub-cloud.browserstack.com"),u.port||(u.port=80))},vw=async()=>{var y,v,S,b,w,I,C,k;u.inspect&&require("inspector").open(u.inspect);let s={},e={},t=[],r={};if(!bl.slice(2).length)throw Tm(),new Lr;if(u.requireCredentials){let R=await Promise.resolve().then(()=>(Qr(),sn)),M=await R.getProjectId(),O=await R.getToken();(!M||!O)&&await R.doLogin()}if(u.login)return await(await Promise.resolve().then(()=>(Qr(),sn))).doLogin(),{loginMode:!0};if(u.version){let R="Testim CLI Version: ";hl.npm_package_version&&(console.log(R,hl.npm_package_version),dl(0));let M=it();M&&(console.log(R,M),dl(0)),console.log("Could not find version, please check the package.json manually"),dl(0)}if(u.installLazyDeps)return{installLazyDepsMode:!0};u.disableFileCache&&Td();let n=u.fileCacheLocation||u.usePrefechedData||u.createPrefechedData;if(n){let R=De.resolve(n);yd(R)}if(u.usePrefechedData&&wd(),u.playerRequirePath){let R=De.resolve(u.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let M=De.join(R,"tsconfig.node.json"),D=require("ts-node").register({project:M,ignore:[/node_modules/,new RegExp(`^${Ft.escapeRegExp(De.relative(It(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:D.config.options.paths,baseUrl:D.config.options.baseUrl}),(be(),fe(Yt)).options.playerPath=R;let V=require("module"),J=V.prototype.require;V.prototype.require=function(de){return de==="rox-alias"?J.call(this,"rox-node"):J.apply(this,arguments)}}if(u.caFile&&(global.caFileContent=fl.readFileSync(u.caFile)),u.proxy&&(global.proxyUri=u.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),u.proxyForGrid&&!u.proxy)throw new P("missing --proxy option");if(lm(u))return um(u);try{let R={};u.configFile?R=require(De.join(It(),u.configFile)).config:u.optionsFile&&(R=require(De.join(It(),u.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(M=>{let O=fw(M);u[O]=hw(u[O],R[M])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(u.tunneld)return{tunnel:!0,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:u.token,project:u.project};let o=((y=u.testConfig)==null?void 0:y.length)||((v=u.testConfigId)==null?void 0:v.length),i=((S=u.testPlan)==null?void 0:S.length)||((b=u.testPlanId)==null?void 0:b.length),a=((w=u.suite)==null?void 0:w.length)||((I=u.suiteId)==null?void 0:I.length);if(u.seleniumCapsFile)try{r=require(De.join(It(),u.seleniumCapsFile))}catch(R){throw new P(`Failed to parse selenium caps file file error: ${R.message}`)}if((C=u.reporters)!=null&&C.includes("junit")&&!u.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!u.tunnel&&u.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!u.tunnel&&u.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!u.tunnel&&[u.tunnelPort,u.tunnelHostHeader,u.tunnelRegion,u.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(u.chromeExtraPrefs)try{e=require(De.join(It(),u.chromeExtraPrefs))}catch(R){throw new P(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(u.chromeExtraArgs){let R=u.chromeExtraArgs.split(",");for(let M of R){let[O]=M.split("=");gm.includes(O)||u.useLocalChromeDriver||u.useChromeLauncher?(t.push(M),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(gm)}`)}}if(u.paramsFile)try{s=Object.assign({},s,require(De.join(It(),u.paramsFile)))}catch(R){throw new P(`Failed to read/open params file error: ${R.message}`)}if(u.params)try{s=Object.assign({},s,JSON.parse(u.params))}catch(R){throw new P(`Failed to parse params string error: ${R.message}`)}if(u.sauceUser&&!u.sauceKey||!u.sauceUser&&u.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(u.sauceUser&&u.sauceKey&&(Tw(),u.saucelabs={},u.saucelabs.username=u.sauceUser,u.saucelabs.accessKey=u.sauceKey),u.sauceOptions)try{let R=require(De.join(It(),u.sauceOptions)),M=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let D=R.browserName.toLowerCase();switch(D){case"microsoftedge":u.browser="edge";break;default:u.browser=D}}u.browser==="edge"&&parseFloat(R.version)>=wa&&(u.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!M&&u.browser==="chrome"&&O)throw new P("The minimum chrome supported version is 50.0");u.saucelabs=Object.assign({},u.saucelabs,R)}catch(R){throw new P(`Failed to parse saucelabs options file error: ${R.message}`)}if(u.browserstackUser&&!u.browserstackKey||!u.browserstackUser&&u.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(u.browserstackUser&&u.browserstackKey&&(ww(),u.browserstack={},u.browserstack["browserstack.user"]=u.browserstackUser,u.browserstack["browserstack.key"]=u.browserstackKey),u.browserstackOptions)try{let R=require(De.join(It(),u.browserstackOptions)),M=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(u.browser=R.browserName.toLowerCase()),u.browser==="edge"&&parseFloat(R.browser_version)>=wa&&(u.browser="edge-chromium"),!M&&parseFloat(R.browser_version)<50&&u.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");u.browserstack=Object.assign({},u.browserstack,R)}catch(R){throw new P(`Failed to parse browserstack options file error: ${R.message}`)}if(u.perfecto={},u.perfectoToken&&(u.perfecto.securityToken=u.perfectoToken),u.perfectoOptions)try{let R=require(De.join(It(),u.perfectoOptions)),M={location:"US East",securityToken:u.perfectoToken};u.perfecto=Object.assign({},M,R)}catch(R){throw new P(`Failed to parse perfecto options file error: ${R.message}`)}if(u.testobjectSauce={},u.testobjectKey&&(u.testobjectSauce.testobjectApiKey=u.testobjectKey),u.testobjectOptions)try{let R=require(De.join(It(),u.testobjectOptions)),M={testobjectApiKey:u.testobjectKey};u.testobjectSauce=Object.assign({},M,R)}catch(R){throw new P(`Failed to parse test object options file error: ${R.message}`)}if(!u.project){let M=await(await Promise.resolve().then(()=>(Qr(),sn))).getProjectId();if(M)u.project=M;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}u.testConfig&&(u.testConfig=[u.testConfig].flat()),u.testConfigId&&(u.testConfigId=[u.testConfigId].flat()),u.mode??="extension",u.retries=!u.retries||typeof u.retries=="boolean"?1:Number(u.retries)+1,u.browserTimeout=!u.browserTimeout||typeof u.browserTimeout=="boolean"?60*1e3:u.browserTimeout,u.newBrowserWaitTimeout=!u.newBrowserWaitTimeout||typeof u.newBrowserWaitTimeout=="boolean"?10*60*1e3:u.newBrowserWaitTimeout*60*1e3,u.getBrowserTimeout||(u.getBrowserTimeout=u.browserTimeout),u.getBrowserRetries||(u.getBrowserRetries=u.mode===Y.APPIUM?1:Math.round(u.newBrowserWaitTimeout/u.browserTimeout)),u.getSessionTimeout=u.browserTimeout<u.getSessionTimeout?u.getSessionTimeout:u.browserTimeout,u.driverRequestTimeout=u.browserTimeout<u.driverRequestTimeout?u.driverRequestTimeout:u.browserTimeout;let c=Boolean(u.timeout);if(u.timeout=!u.timeout||typeof u.timeout=="boolean"?10*60*1e3:u.timeout,u.beforeParallel=!u.beforeParallel||typeof u.beforeParallel=="boolean"?1:Number(u.beforeParallel),u.parallel=!u.parallel||typeof u.parallel=="boolean"?1:Number(u.parallel),u.afterParallel=!u.afterParallel||typeof u.afterParallel=="boolean"?1:Number(u.afterParallel),u.tunnelPort=!u.tunnelPort||typeof u.tunnelPort=="boolean"?"80":u.tunnelPort,u.port&&=Number(u.port),!u.token){let M=await(await Promise.resolve().then(()=>(Qr(),sn))).getToken();if(M)u.token=M;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let l=R=>R<=0||!Number.isInteger(R);if(l(u.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(u.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(l(u.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(l(u.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(l(u.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(l(u.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(l(u.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(l(u.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(u.mode))throw new P(`runner mode <${u.mode}> is not supported`);if(u.mode!==Y.SELENIUM&&u.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!u.browser&&!o&&!i&&(u.browser="chrome"),u.appiumLogLevel||(u.appiumLogLevel="silent"),!bw.includes(u.appiumLogLevel))throw new P(`runner appium-log-level <${u.appiumLogLevel}> is not supported`);if(u.testPlan&&u.testPlan.length===0&&u.testPlanId&&u.testPlanId.length===0){if(typeof u.host!="string"&&typeof u.grid!="string"&&typeof u.gridId!="string"&&!u.localTmaUrl&&!u.useLocalChromeDriver&&!u.useChromeLauncher&&!u.createPrefechedData)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(u.testId.length||u.label.length||u.name.length||o||u.browser||a||u.localTmaUrl||u.useLocalChromeDriver||u.useChromeLauncher)throw new P("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(u.beforeParallel!==1||u.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([u.host,u.grid,u.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((k=u.host)!=null&&k.includes("/")&&(/^(f|ht)tps?:\/\//i.test(u.host)||(u.host=`http://${u.host}`),u.host=ym.parse(u.host).hostname),u.resultLabel.length){u.resultLabel=u.resultLabel.map(M=>M.trim()).filter(Boolean);let R=u.resultLabel.filter(M=>M.length>=250).filter(Boolean);if(u.branch==="auto-detect"&&u.resultLabel.includes("auto-detect-branch")&&dr()&&u.resultLabel.unshift(dr()),R.length)throw new P("A result label cannot exceed 250 characters")}let m=sm(u),p=ko(u);if(!u.w3cCapabilities&&!u.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(u.protocol||=u.port===443?"https":"http",!["http","https"].includes(u.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(u.rerunFailedByRunId&&u.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(u.rerunFailedByRunId&&(a||u.name.length||u.testId.length||u.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(u.setRetention&&!Ft.inRange(Ft.parseInt(u.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");u.setRetention&&=Number(u.setRetention);let g="is no longer supported, please use --override-mapping-file";if(u.mockNetworkHar)throw new P(`--mock-network-har ${g}`);if(u.mockNetworkPattern)throw new P(`--mock-network-pattern ${g}`);if(u.disableMockNetwork&&u.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!u.collectCodeCoverage&&u.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(u.collectCodeCoverage&&u.codeCoverageReporter&&Ft.difference(u.codeCoverageReporter,gl).length){let R=Ft.difference(u.codeCoverageReporter,gl);throw new P(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}u.codeCoverageReporter=u.codeCoverageReporter.length===0?["html","text"]:u.codeCoverageReporter,u.codeCoverageInclude=u.codeCoverageInclude.length===0?["src/**"]:u.codeCoverageInclude;let f={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},h=Object.keys(f).filter(R=>Boolean(u[R]));if(u.mode!==Y.EXTENSION&&h.length){let R=h.length>1?"are":"is";throw new P(`${h.map(M=>f[M]).join(" and ")} ${R} only applicable in extension mode`)}if(u.tmsFieldFile)try{let R=fl.readFileSync(u.tmsFieldFile);u.tmsCustomFields=JSON.parse(R)}catch(R){throw new P(`failed to parse field file error: ${R.message}`)}if(u.highSpeed&&(yw("--high-speed","--turbo-mode"),u.turboMode=!0),u.skipLoadBalancer&&!u.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(u.deviceUdid&&(u.deviceName||u.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(u.resetAppData&&u.fullReset)throw new P("It is not possible to set both --reset-app-data and --full-reset capabilities to true at the same time!");if(u.resetOnSessionStartOnly&&!u.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),u.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"},M=typeof u.lightweightMode=="string"?JSON.parse(u.lightweightMode):{};u.lightweightMode=Object.assign({},R,M)}catch(R){throw new P(`failed to parse lightweightMode settings error: ${R.message}`)}else u.turboMode&&u.mode===Y.EXTENSION&&(u.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"});if(typeof u.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[u.testId].flat(),name:[u.name].flat(),label:[u.label].flat(),suites:[u.suite].flat(),suiteIds:[u.suiteId].flat(),testPlan:[u.testPlan].flat(),testPlanIds:[u.testPlanId].flat(),webpackConfig:u.webpackConfig,reportFile:u.reportFile,urls:u.urls,reportFileClassname:u.overrideReportFileClassname,reporters:u.reporters,project:u.project,host:u.host,headless:u.headless,localTmaUrl:u.localTmaUrl,useLocalChromeDriver:u.useLocalChromeDriver,chromeBinaryLocation:u.chromeBinaryLocation,useChromeLauncher:u.useChromeLauncher,port:u.port,grid:u.grid,gridId:u.gridId,disableNativeEvents:u.disableNativeEvents,saucelabs:u.saucelabs,browserstack:u.browserstack,baseUrl:u.baseUrl,branch:(u.branch==="auto-detect"?dr():u.branch)||"master",autoDetect:u.branch==="auto-detect",token:u.token,userParamsData:s,mode:u.mode,isRegressionBaselineRun:u.isRegressionBaselineRun,browser:u.browser,beforeParallel:u.beforeParallel,parallel:u.parallel,afterParallel:u.afterParallel,canary:u.canary,rerunFailedByRunId:u.rerunFailedByRunId,disableGridCheck:u.disableGridCheck,disableTimeoutRetry:u.disableTimeoutRetry,resultLabels:u.resultLabel,path:u.path,protocol:u.protocol,perfecto:u.perfecto,experitestToken:u.experitestToken,testobjectSauce:u.testobjectSauce,gridUsername:u.gridUsername,gridPassword:u.gridPassword,overrideExecutionName:u.overrideExecutionName,tmsSuppressReporting:Boolean(u.suppressTmsReporting)||Boolean(u.tmsSuppressReporting),tmsRunId:u.tmsRunId,tmsCustomFields:u.tmsCustomFields,proxyForGrid:u.proxyForGrid,retentionDays:u.setRetention,passZeroTests:Boolean(u.passZeroTests),runQuarantinedTests:Boolean(u.runQuarantinedTests),deviceName:u.deviceName,deviceUdid:u.deviceUdid,customTag:u.customTag,osVersion:u.osVersion,skipLoadBalancer:u.skipLoadBalancer,lockDevice:u.lockDevice,appId:u.appId,appiumLogLevel:u.appiumLogLevel,resetAppData:u.resetAppData,fullReset:u.fullReset,resetOnSessionStartOnly:u.resetOnSessionStartOnly,ext:u.ext,extensionLocation:[u.extensionPath||m].flat(),extensionPath:u.extensionPath,playerLocation:u.playerPath||p,playerPath:u.playerPath,playerRequirePath:u.playerRequirePath,tunnel:u.tunnel,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,externalLambdatestTunnelId:u.externalLambdatestTunnelId,externalLambdatestUseWss:u.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(u.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(u.externalLambdatestMitm),beforeTest:u.beforeTest,afterTest:u.afterTest,beforeSuite:u.beforeSuite,afterSuite:u.afterSuite,timeout:u.timeout,timeoutWasGiven:c,browserTimeout:u.browserTimeout,newBrowserWaitTimeout:u.newBrowserWaitTimeout,getBrowserTimeout:u.getBrowserTimeout,getBrowserRetries:u.getBrowserRetries,getSessionTimeout:u.getSessionTimeout,getSessionRetries:u.getSessionRetries,driverRequestTimeout:u.driverRequestTimeout,driverRequestRetries:u.driverRequestRetries,testStartTimeout:u.testStartTimeout,testConfigNames:u.testConfig,testConfigIds:u.testConfigId,overrideMappingFile:u.overrideMappingFile,disableMockNetwork:u.disableMockNetwork,codeCoverageUrlFilter:u.codeCoverageUrlFilter,collectCodeCoverage:u.collectCodeCoverage,codeCoverageReportPath:u.codeCoverageReportPath,codeCoverageSourceMapPath:u.codeCoverageSourceMapPath,codeCoverageReporter:u.codeCoverageReporter,codeCoverageInclude:u.codeCoverageInclude,executionId:u.executionId,remoteRunId:u.remoteRunId,schedulerId:u.schedulerId,source:u.source,resultId:u.resultId,installCustomExtension:u.installCustomExtension,w3cCapabilities:u.w3cCapabilities,oldCapabilities:u.oldCapabilities,chromeBlockLocation:u.chromeBlockLocation,chromeUserDataDir:u.chromeUserDataDir,retries:u.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:u.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:u.monitorPerformance,user:u.user,lightweightMode:u.lightweightMode,createPrefechedData:u.createPrefechedData,saveRCALocally:u.saveRcaLocally,exitCodeIgnoreFailingTests:u.exitCodeIgnoreFailingTests,disableSockets:u.disableSockets,intersections:{labels:u.intersectWithLabel.length?[u.intersectWithLabel].flat():void 0,suiteNames:u.intersectWithSuite.length?[u.intersectWithSuite].flat():void 0,suiteIds:u.intersectWithSuiteId.length?[u.intersectWithSuiteId].flat():void 0},downloadBrowser:u.downloadBrowser}}});var Im={};G(Im,{installAllLazyDependencies:()=>Rw,lazyRequire:()=>Ee});async function Ee(s,e={}){let t=ac(s);if(t)return t;let r;e.silent||(r=(0,Em.default)(`Installing ${s} before first usage...`).start());try{let n=await Sw(s);return r&&r.succeed(),n}catch(n){Ew.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Rm(s),i=`${s}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw r&&r.fail(l),n}}async function Sw(s){return Zr.has(s)||(Zr.set(s,Sm(s)),Zr.get(s).catch(()=>{Zr.delete(s)})),Zr.get(s)}async function Sm(s){let e=ac(s);if(e)return e;let t=Rm(s),r=`${s}@${t}`;return await fo(at(),r),zt(s)}async function Rw(){let s=Object.keys(Ra);for(let e of s)await Sm(e)}function Rm(s){let e=Object.entries(Ra).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Em,Ew,Zr,Tr=T(()=>{"use strict";Em=E(require("ora"));Vs();B();j();Gn();Gs();Ew=x("lazy-require"),Zr=new Map});var Am={};G(Am,{preloadTests:()=>nn});async function nn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ct(async()=>{let t=await ie(s.testId,r=>Rc({...e,testId:r}),{concurrency:2});return xm.keyBy(t,"testData.id")},"loadTests",Iw,[e,s.testId])()}var xm,Iw,Mo=T(()=>{"use strict";xm=E(require("lodash"));qt();ye();j();Iw=1e3*60*60*10});function Tl(){return it()}async function km(){if(!Ce)try{let s=await ae(Aw(),5e3,"The API call to NPM timed out"),e=Tl();e&&Cm.lt(e,s)&&console.log(Pm.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){xw.warn("Failed to get NPM version",{err:s})}}var Pm,Cm,xw,Aw,wl=T(()=>{"use strict";Pm=E(require("chalk")),Cm=E(require("semver"));j();le();Vs();qt();B();xw=x("npm-driver"),Aw=ct(()=>Rd("@testim/testim-cli"),"getNpmVersion")});var vl,Cw,es,Om,_m,El,Lm,Dm=T(()=>{"use strict";j();z();B();Tr();vl=x("testimNgrok"),Cw=".whitelisted-ngrok.testim.io",es="",_m=async(s,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${te()}-${s.projectData.projectId}${Cw}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await Ee("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(vl.info("replace https to http"),es=o.replace("https://","http://")):es=o,s.tunnelDiagnostics&&El(),s.baseUrl=es},El=async(s=!0)=>{try{let t=(await Ee("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===es);console.log("ngrok stats",n),vl.info("ngrok stats",{tunnel:n})}catch(e){vl.error("error collecting ngrok stats",{err:e})}s&&(Om=setTimeout(()=>El(),1e4))},Lm=async s=>{if(!es)return;clearTimeout(Om),s.tunnelDiagnostics&&await El(!1),await(await Ee("ngrok")).disconnect(es)}});var Xt,Rl,Mm,Ow,_w,Sl,No,Fo,Uo,Lw,Nm,Um,Fm=T(()=>{"use strict";Xt=E(require("os")),Rl=E(require("fs")),Mm=E(require("child_process"));j();ye();Ow="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",_w={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"}},Sl=Xt.tmpdir(),No=`${Sl}/cloudflared`,Fo=null,Uo=null,Lw=async()=>{if(await ge(No))return;let e=_w[Xt.platform()+Xt.arch()];if(!e)throw new Error(`tunnel on ${Xt.platform()+Xt.arch()} platform is not supported.`);let t=e.extract?Sl+e.path:No;await He(`${Ow}/${e.path}`,t),e.extract&&await Ze(t,Sl),await Rl.promises.chmod(No,"755")},Nm=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([zc(s.company.companyId,t),Lw()]);Fo=r._id,Uo=Mm.spawn(No,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await Kc(s.company.companyId,Fo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Rl.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Um=async s=>{let e=[];return Fo&&e.push(Jc(s.company.companyId,Fo)),Uo&&e.push(new Promise((t,r)=>{Uo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Uo.kill()})),await Promise.all(e)}});var q,jm,Mw,Nw,Uw,Bm,Bo,Il,U,Te=T(()=>{"use strict";q=E(require("rox-node"));B();j();le();jm=x("FeatureFlagsService"),Mw=!Ce&&!0&&!Ip,Nw=2e4,Uw=60*60*24,Bm=["labs","disabled","enabled"],Bo=class extends q.default.Variant{constructor(e="disabled"){super(e,Bm)}getValue(){let e=super.getValue();return Bm.includes(e)?e:(jm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Il=class{constructor(){this.flags={useNewWSCLI:new q.default.Flag,useSafariWebdriverVisibilityChecks:new q.default.Flag,useClickimVisibilityChecks:new q.default.Flag,runGetElementCodeInAut:new q.default.Flag,enableFrameSwitchOptimization:new q.default.Flag,maximumJsResultSize:new q.default.Configuration(2e3*1024),skipFileInputClicks:new q.default.Flag,errorMessageOnBadNetwork:new q.default.Flag(!0),warnOnBadNetwork:new q.default.Flag(!1),overrideAzureStorageUrl:new q.default.Flag,useJsInputCodeInSafari:new q.default.Flag,useJsInputCodeInFirefox:new q.default.Flag,autoSaveDownloadFileFireFox:new q.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new q.default.Flag(!0),experimentalPreCodeCompilation:new q.default.Flag(!0),experimentalAsyncCustomCode:new q.default.Flag,useSameBrowserForMultiTests:new Bo("labs"),highSpeedMode:new Bo,usePortedHtml5DragDrop:new q.default.Flag,testNamesToBeforeSuiteHook:new q.default.Flag,addCustomCapabilities:new q.default.Variant("{}"),LTNetworkCapabilities:new q.default.Flag,downloadToBase64:new q.default.Flag,publicGridURL:new q.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new q.default.Flag(!0),unsupportedCapsFields:new q.default.Variant("[]"),useLinkedomToParseHtml:new q.default.Flag,dontFocusOnInit:new q.default.Flag,retryOnSeleniumHubError:new q.default.Flag},q.default.register("default",this.flags)}setProjectId(e){q.default.setCustomStringProperty("projectId",e)}setProjectType(e){q.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){q.default.setCustomStringProperty("productType",e)}setCompanyId(e){q.default.setCustomStringProperty("companyId",e)}setPlanType(e){q.default.setCustomStringProperty("planType",e)}setIsPOC(e){q.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){q.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){q.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Mw)return;let e={fetchIntervalInSec:Uw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ae(q.default.setup(Sp,e),Nw).catch(t=>jm.error("failed to get feature flag status",t))}},U=new Il});var Wm,Gm,Qt,Vm,Hm,$m,Fw,Bw,jo,jw,$w,ne,$o=T(()=>{"use strict";Wm=E(require("ms")),Gm=E(require("p-retry")),Qt=E(require("os")),Vm=E(require("portfinder")),Hm=E(require("child_process"));j();Ve();ye();z();B();Oo();ce();Te();$m=x("lambdatestService"),Fw="https://downloads.lambdatest.com/tunnel/v3",Bw={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"},jo=`${Qt.tmpdir()}/LT`,jw=`${jo}/LT`,$w=(0,Wm.default)("15m"),ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===N.LAMBDATEST||e.type===N.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=Bc(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?$w:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(jw))return;let t=Bw[Qt.platform()+Qt.arch()];if(!t)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let r=`${jo}.zip`;await He(`${Fw}/${t}`,r),await Ze(r,jo)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Vm.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;ne.tunnelName=te();let a=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)a=[...a,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(i)try{let d=new URL(i);a=[...a,"--proxy-host",d.hostname],d.port&&(a=[...a,"--proxy-port",d.port]),d.username&&d.password&&(a=[...a,"--proxy-user",d.username,"--proxy-pass",d.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),ne.tunnel=Hm.spawn("./LT",a,{cwd:jo});let c="",l="";ne.tunnel.stdout.on("data",d=>{c+=d.toString()}),ne.tunnel.stderr.on("data",d=>{l+=d.toString()});try{let d=await(0,Gm.default)(()=>Ne(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});$m.info("LT tunnel info",d)}catch(d){throw $m.error("Failed to start LT tunnel",{err:d,stdoutResult:c,stderrResult:l}),d}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=ne.lambdatestConfig.CAPABILITIES[t]||{},a={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},c=[],{mode:l,canary:d,ext:m,extensionPath:p,installCustomExtension:g}=e;if(l===Y.EXTENSION&&!m){let f=il({canary:d},!0);!p&&f[t]&&(c=[...c,f[t]]),p&&Be(p)&&(c=[...c,p])}return g&&Be(g)&&(c=[...c,g]),{build:r,name:`${n} - ${o}`,platform:ne.lambdatestConfig.PLATFORM,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,resolution:ne.lambdatestConfig.RESOLUTION,timezone:ne.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:U.flags.LTNetworkCapabilities.isEnabled()}}}});var xl={};G(xl,{connect:()=>Go,disconnect:()=>Vo,serveTunneling:()=>Gw});var Wo,qm,zm,Ww,Go,Vo,Gw,Al=T(()=>{"use strict";Dm();en();Fm();Rt();Wo=E(require("ora"));B();ce();$o();qm=x("tunnel"),zm=s=>{var e;return[N.LAMBDATEST,N.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Ww=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===N.HYBRID&&s.gridData.tunnel==="cloudflare"},Go=async s=>{if(!s.tunnel)return;let e=Mt(),t;try{zm(s)?(t=(0,Wo.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):Ww(s)?(t=(0,Wo.default)("Starting testim cloudflare tunnel...").start(),await Nm(s)):(t=(0,Wo.default)("Starting testim ngrok tunnel...").start(),await _m(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw qm.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},Vo=async s=>{if(s.tunnel)try{zm(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await Um(s):await Lm(s)}catch(e){let t="catch error - failed to close tunnel";throw qm.error(t,{err:e}),new Error(t)}},Gw=async(s,e=new Promise(()=>{}))=>(await Go(s),Yr(()=>Vo(s)),await e)});function Vw(s){if(s.protocol)return s.protocol;if([N.TESTIM,N.BROWSERSTACK,N.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([N.TESTIM_ENTERPRISE,N.LAMBDATEST,N.DEVICE_FARM].includes(s.type)){let e=Km.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function Hw(s){let e=Km.exec(s);return e==null?void 0:e[3]}function qo(s){var y,v,S,b,w,I,C,k,R;let e=s&&Hw(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&Vw(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(y=s==null?void 0:s.hybrid)==null?void 0:y.tunnel,c=(v=s==null?void 0:s.external)==null?void 0:v.user,l=(S=s==null?void 0:s.external)==null?void 0:S.key,d=s==null?void 0:s.type,m=d===N.HYBRID?a&&((I=(w=(b=s.hybrid)==null?void 0:b.external)==null?void 0:w[s.hybrid.tunnel])==null?void 0:I.user):c,p=d===N.HYBRID?a&&((R=(k=(C=s.hybrid)==null?void 0:C.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:R.key):l,g=s==null?void 0:s.name,f=s&&(s._id||s.gridId),h=s==null?void 0:s.provider;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:l,type:d,name:g,provider:h,tunnelUser:m,tunnelKey:p}}async function Ym(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Je.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(jr.UNKNOWN)}if(Je.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Je.error("invalid response - get grid",{res:o}),new Error(jr.UNKNOWN);if(o.status==="success"){let i=qo(o.grid);return qw(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new Tt(jr.NOT_FOUND):o.code==="no-available-slot"?new Mr(`Failed to run test on ${r} - concurrency limit reached`):(Je.error("invalid code error response - get grid",{res:o}),new Tt(jr.UNKNOWN))}function zw(s,e,t,r,n,o){return Ym(t,e,s,n,()=>Ro(e,t,r,n,o))}function Kw(s,e,t,r,n,o,i){return Ym(t,e,s,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return c!=null&&c._id?Ro(e,t,c._id,n,o):Nc(e,t,r,n,o)})}function Xm(s){return Fc(s)}async function Qm(s,e,t){let n=(t||await Xm(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return qo(n)}async function Jw(s,e,t){let n=(t||await Xm(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return qo(n)}async function Pl(s,e){let t=on[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete on[s],!r){Je.warn("failed to find grid slot id",{projectId:e});return}Je.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Dc(i,e,r,n,o)}catch(a){Je.error("failed to release slot",{projectId:e,err:a})}}async function Yw(s){let e=Object.values(on).filter(Boolean);if(e.length!==0){Je.info("keep alive worker slots",{projectId:s,slots:e});try{await Lc(s,e)}catch(t){Je.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Xw(s){Jm=global.setInterval(Yw,1e4,s)}async function Qw(s){let e=Object.keys(on);if(e.length){Je.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>Pl(Number(t),s))}catch(t){Je.error("failed to release all slots",{err:t,projectId:s})}}}async function Zw(s){await Qw(s),clearInterval(Jm)}function ev(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function tv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function Zm(s){let t=(()=>Ho.isEmpty(s.testobjectSauce)?Ho.isEmpty(s.saucelabs)?Ho.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=ev(t,s),c=tv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function ef(s,e){let t=s.company.companyId;return await Qm(t,e.gridId,s.allGrids)}async function tf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:c}=s;if(n||i||o)return{mode:"local"};if(r)return Zm(s);let l=t==null?void 0:t.companyId;if(a)return Qm(l,a,e);if(c)return Jw(l,c,e);if(Us(s)||s.tunnelOnlyMode){Je.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new Tt("Missing host or grid configuration")}async function rf(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:d,company:m}=t,p=m==null?void 0:m.companyId;if(l||d||c)return{mode:"local"};if(n)return Zm(t);if(a)return zw(r,p,o,a,s,e);if(i)return Kw(r,p,o,i,s,e,t);throw new Tt("Missing host or grid configuration")}var Ho,Je,on,Km,Jm,qw,an,sf,ts=T(()=>{"use strict";Ho=E(require("lodash"));ye();B();j();ce();z();Je=x("grid-service"),on={},Km=/(^(https?):\/{2})?(.*)/,Jm=null;qw=(s,e,t,r,n)=>{on[s]={gridId:t,companyId:e,slotId:r,browser:n}};an={start:Xw,end:Zw};sf=async(s={},e={},t={},r={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,c=s.browser||t.browserValue,l=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!i||!a||(a===N.LAMBDATEST&&await((f=r.enableIfNeeded)==null?void 0:f.call(r,e)),a!==N.HYBRID||!o||!c||!d||!m))return e;let p=await Mc({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:c,usingTunnel:l});Je.info("handling hybrid grid",{response:p,companyId:o});let g=qo({...e,...p.connectionDetails,provider:p.provider});return p.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),p.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,g)),g}});function ln(){return zo||"master"}function nf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){zo="master";return}if(s&&!s.isArchived){zo=s.branch||s;return}zo=e?"master":void 0}var zo,Cl=T(()=>{"use strict"});var un,kl,rv,Ol,sv,Ko,Jo,Yo,Xo,Qo,Zo=T(()=>{"use strict";j();ce();un=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},kl=s=>{let{status:e}=s;return e===pe.ABORTED},rv=s=>{let{status:e}=s;return e===pe.PASSED},Ol=s=>s.runnerStatus===qa.SKIPPED,sv=s=>s.testStatus===qe.EVALUATING,Ko=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ol(t)&&(ze(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Jo=s=>Object.values(s).filter(e=>un(e)&&sv(e)).length,Yo=s=>Object.values(s).filter(un),Xo=s=>Object.values(s).filter(rv),Qo=s=>Object.values(s).filter(kl)});function nv(s){let e=s.indexOf("--token");if(e===-1&&(e=s.indexOf("--t")),e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var ei,af,ti,cf=T(()=>{"use strict";B();Zo();ei=x("debug-reporter"),af={token:void 0,userParamsData:void 0,projectData:void 0,allGrids:void 0,gridData:void 0,awsAccessKeyId:void 0,awsSecretAccessKey:void 0,runParams:void 0,perfecto:void 0,testobjectSauce:void 0},ti=class{constructor(e){this.options=e}onTestStarted(e,t){ei.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;ei.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}onTestPlanStarted(e,t,r,n,o,i,a){let c=nv(process.argv);ei.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:Object.assign({},this.options,af),args:c})}onTestPlanFinished(e,t,r,n,o){let i=Xo(e).length,a=Object.keys(e).length-i;ei.info("Test Plan Finished",{isAnonymous:o,passed:i,failed:a,testPlanName:t,options:Object.assign({},this.options,af),duration:r,executionId:n})}}});var _l,xt,pn=T(()=>{"use strict";ce();_l=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===N.DEVICE_FARM}},xt=new _l});var Dl={};G(Dl,{Reporter:()=>ov});var Zt,dn,wr,ri,lf,Ll,ov,Ml=T(()=>{"use strict";Zt=E(require("chalk")),dn=E(require("lodash"));j();ce();pn();Zo();wr={success:Zt.default.green,warn:Zt.default.yellow,error:Zt.default.red},{CLI_MODE:ri}=Lt,lf="device",Ll=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${Zt.default.underline(ot(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?pe.PASSED:pe.FAILED,n=`(${e.testId})`,o=wr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${eo(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=ot(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(wr.error("Failed runs are:")),console.log(wr.error(t.join(`
|
|
21
|
+
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=Yo(e),a=Xo(e),c=Qo(e),l=a.length,d=c.length,m=i.length,p="",g="";if(xt.isTestStatusEnabled){let S=Jo(e);p=` FAILED-EVALUATING: ${S}`,m-=S,g=` SKIPPED: ${Ko(e,this.options)}`}let f=this.buildTestPlanName(o,t),h,y=wr[m?"error":"success"],v=`PASSED: ${l} FAILED: ${m}${p} ABORTED: ${d}${g} Duration: ${eo(r)}`;f.trim()===""||f.trim()==="Anonymous"?h=`Tests completed. ${v} (Execution ID: ${n})`:h=`Test plan${f} completed ${v} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=dn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=dn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=dn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=dn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let c=p=>{p.forEach((g,f)=>{var v;let h=(v=g.testData)!=null&&v.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${ze(g,this.options)?"-quarantine":""}`,y,h)})},l=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===ri.APPIUM?lf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===ri.APPIUM?lf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===ri.APPIUM?"device":"browser";if(n)console.log(wr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(wr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===ri.APPIUM?"Appium":"Selenium";console.log(wr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},ov=Ll});var Fl={};G(Fl,{Reporter:()=>pv});function iv(s){let e=s.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function av(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 cv(s){return`${s.visitedUrlsJson||""}`}async function lv(s,e,t,r,n,o){function i(p){let g=ot(s,t,p.testId,p.resultId,r),f={$:{name:iv(p),classname:n,time:Za(p.duration),ownedBy:p.testOwnerName,ownerEmail:p.testOwnerEmail},"system-out":g};if(un(p)||kl(p)){let h=`Step Failed: ${p.failureReason||p.reason}`,y=un(p)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Ol(p)&&ze(p,o)&&xt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=av(p),f["visited-urls-json"]=cv(p)),f}function a(p){let{results:g,testPlanName:f,configName:h}=p,y=g||{},S={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:l(y),failure:d(y),timestamp:c(e)};if(xt.isTestStatusEnabled){S.skipped=Ko(y,o);let b=Jo(y);S.failure-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(p){let g=Object.keys(p).map(h=>p[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function l(p){return Object.keys(p).length}function d(p){return Yo(p).length+Qo(p).length}let m={testsuites:{testsuite:e.map(p=>a(p))}};try{return new Ul.Builder().buildObject(m)}catch(p){return uv(p)}}function uv(s){let e=new Ul.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var Ul,uf,Nl,pv,Bl=T(()=>{"use strict";Ul=E(require("xml2js"));j();uf=require("fs");pn();Zo();Nl=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 lv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await uf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};pv=Nl});var pf={};G(pf,{Reporter:()=>dv});function rs(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 jl,$l,dv,df=T(()=>{"use strict";B();jl=x("team-city-reporter");$l=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 rs(n)}onTestStarted(e,t,r,n){if(r){jl.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){jl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${rs(t)}' details='${rs(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){jl.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='${rs(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${rs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${rs(t)}']`)}},dv=$l});var mf={};G(mf,{Reporter:()=>mv});var Wl,mv,ff=T(()=>{"use strict";Wl=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},mv=Wl});var gf={};G(gf,{Reporter:()=>fv});var Gl,fv,hf=T(()=>{"use strict";j();al();Gl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ot(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Lo(t)}},fv=Gl});var ux,Vl,X,At=T(()=>{"use strict";cf();B();ux=x("reporter"),Vl=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 ti(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Ml(),Dl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(Bl(),Fl));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(df(),pf)),r.includes("console")&&Promise.resolve().then(()=>(Ml(),Dl)),r.includes("junit")&&Promise.resolve().then(()=>(Bl(),Fl)),r.includes("json")&&Promise.resolve().then(()=>(ff(),mf)),r.includes("chrome")&&Promise.resolve().then(()=>(hf(),gf))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},X=new Vl});function bf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Tf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:l,user:d,lightweightMode:m,isStartUp:p,projectType:g,appSource:f,gridType:h}){let y=bf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:yf(l,d),isStartUp:p,projectType:g,gridType:h,...["android","ios"].includes(g)&&f&&{appSource:f}},m);lt("test-run-ci",y)}function wf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,source:d,user:m,lightweightMode:p,logger:g,isStartUp:f,projectType:h,appSource:y,gridType:v}){try{let S=bf({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:yf(d,m),isStartUp:f,projectType:h,gridType:v,...["android","ios"].includes(h)&&y&&{appSource:y}},p);if(n.success){lt("test-run-ci-success",S);return}lt("test-run-ci-fail",Object.assign({},S,{failureReason:n.failureReason}))}catch(S){g.error("failed to update test end analytics",{err:S})}}function vf(s){lt("batch-run-ci",s)}var yf,Hl=T(()=>{"use strict";Xr();vo();yf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Kr&&e?"ci-with-user":Kr?"ci":e?"cli-with-user":s});var Sf,si,Rf=T(()=>{"use strict";Sf=require("istanbul-lib-report"),si=class extends Sf.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 If,xf,Af,mn,ut,Pf,ni,ql,Cf,gv,kf,Of,hv,yv,_f,bv,Tv,wv,vv,Ev,Lf,Df=T(()=>{"use strict";If=E(require("ora")),xf=E(require("moment")),Af=E(require("test-exclude")),mn=E(require("fs")),ut=E(require("path")),Pf=E(require("istanbul-reports")),ni=E(require("istanbul-lib-report"));ye();z();j();B();Tr();Rf();ql=x("test-run-status"),Cf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},gv=s=>!!Cf(s).search,kf=s=>s?Cf(s).pathname.substring(1):"",Of=(s,e)=>{let t=kf(e);return!new Af.default({relativePath:!1,include:s}).shouldInstrument(t)},hv=s=>s.substring(0,s.indexOf("?")),yv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ee("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},_f=(s,e)=>`${ut.resolve(s,kf(e))}.js`,bv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(Of(r,i))return;let c=_f(e,i);await mn.promises.mkdir(ut.parse(c).dir,{recursive:!0}),await mn.promises.writeFile(c,o.sourcesContent[a])})})},Tv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(gv(e)&&(e=hv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=ut.dirname(this.getPath(s));return ut.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},wv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=ni.createContext({dir:t,coverageMap:e,watermarks:ni.getDefaultWatermarks(),sourceFinder:a=>{try{let c=_f(r,a);return mn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new si({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Tv}),Pf.create(a,c).execute(i)}),o},vv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Ee("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Of(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},Ev=async(s,e)=>{let{mergeProcessCovs:r}=await Ee("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await $c(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Xs(c,9e4);await ie(l,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await Ec(d.sourceUrl)),o.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:o,mergedCoverages:n}},Lf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;ql.info("start js coverage process");let n=(0,If.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=ut.resolve(s.codeCoverageReportPath||"./coverage"),i=ut.resolve(o,`.js/${(0,xf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?ut.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([Ee("istanbul-lib-coverage"),Ev(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}ql.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:l.result.length});let m=c.createCoverageMap({}),p={};await ie(l.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:v}=d.get(f),S=await yv({sourceMapType:v,source:y,sourceMapDir:a});p[f]=S;let b=await vv(s,{source:y,sourceMap:S,functions:h});m.merge(b)}),await bv(s,i,p);let g=await wv(s,m,o,i);return n.succeed(),g}catch(c){let l="Failed to report coverage information";c instanceof P?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),ql.error(l,{err:c})}}});var Mf={};G(Mf,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Bt});var xe,Sv,Bt,ss=T(()=>{"use strict";j();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Sv=["ALL",...Object.values(xe)],Bt=class{constructor(){this.marks=Object.fromEntries(Sv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=te();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,so(r,50)],[`${t}_P95`,so(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Bf={};G(Bf,{initServer:()=>xv,mapFilesToLocalDrive:()=>Kl});function Kl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,oi[t.id]?{screenshot:oi[t.id]}:{})),Object.keys(ii).forEach(t=>{s.assets||={},s.assets[Ff[t]]=ii[t]}),s.assets||={},s.assets.screenshots=Object.values(oi)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function xv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ee("multer"),n=typeof t=="string"?t:Rv;await zl.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(c,l,d){let m=JSON.parse(c.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let p=fn.join(n,m.testResultId);try{await zl.promises.mkdir(p,{recursive:!0})}catch(g){return d(g,"")}return d(null,p)},filename(c,l,d){let{fileName:m}=c.body,p=JSON.parse(c.body.metadata||"{}");if(!p.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(p.stepId){let g=fn.extname(m);return d(null,`step_${p.stepId}_${p.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Uf.default)();i.post("/",o.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(oi[d.stepId]=c.file.path),d.testResultId&&Iv.includes(d.subType)&&(ii[d.subType]||=[],ii[d.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>c(d.address()));function m(p){if(p.syscall!=="listen")return l(p);switch(p.code){case"EACCES":case"EPERM":return l(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new P(`Port ${s} is already in use`));default:return l(p)}}})}var zl,Nf,fn,Uf,Rv,oi,ii,Ff,Iv,Jl=T(()=>{"use strict";zl=E(require("fs")),Nf=E(require("os")),fn=E(require("path")),Uf=E(require("express"));z();Tr();Rv=fn.join(Nf.tmpdir(),"testim/rca/"),oi={},ii={},Ff={"test-log":"consoleLogs","har-file":"networkLogs"},Iv=Object.keys(Ff)});var er,Yl,ai,jf=T(()=>{"use strict";er=E(require("lodash"));j();B();Yl=x("override-test-data-builder"),ai=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Yl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Yl.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}Yl.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return er.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),c=r[i],l=this.createNewTestItems(c,t);return r.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=te();return Object.assign({},e,{resultId:o,testData:{value:r,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function ci(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ye.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var vr,Ye,Av,Pv,Cv,kv,li,$f=T(()=>{"use strict";vr=E(require("lodash"));j();ce();ts();ye();z();B();At();en();Df();ss();Jl();le();Te();jf();pn();Ye=x("test-run-status"),Av=dr(),Pv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Cv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,kv=it();li=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 Bt;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Ns(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:zn||t.parallel||1,browser:o,gitBranch:Av,gitCommit:Pv,gitRepoUrl:Cv,runnerVersion:kv,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:i,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.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:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:d,testStatus:m,testCreatorName:p,testCreatorEmail:g,testOwnerName:f,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:S}=a,b={originalTestResultId:t,previousTestResultId:r,config:vr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},b,{testCreatorName:p,testCreatorEmail:g,testOwnerName:f,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:S}),Hc({projectId:n,runId:o,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,X.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await xo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Ye.error("failed to upload test data artifact (runner)",{err:d})}let c=vr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,yr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(ze(e,this.options))return;let n=this.exportsGlobal;try{let o=await ci(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ye.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ye.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:c,success:l}=t;if(a===qe.EVALUATING&&xt.isTestStatusEnabled){X.onTestIgnored(e,r,`test in ${qe.EVALUATING} status`);return}if(l){X.onTestPassed(o);return}X.onTestFailed(r,r.failureReason,ot(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);X.onTestIgnored(e,r,`test in ${qe.QUARANTINE}`)}monitorMemoryUsage(e){let t=ec();if(t.isOverThreshold){let r=U.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Ye.info(`using ${r} to parse html`,{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}}testEnd(e,t,r,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&Kl(i,Ye),i.resultUrl=ot(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),X.onTestFinished(i,e,o);let c=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=c,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await ci(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ye.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await yr(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 Ye.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t){let r="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=Ja;return e&&(r=n),$r(t)&&(r=o),r}calcTestRunStatus(){let{options:e,testInfoList:t}=this,r=e.company.companyId,n=t.map(o=>{var m,p,g;let i=e.browser?$s(e.browser,e.saucelabs,e.browserstack):o.runConfig,a=!U.flags.allowAppFromDeviceRuns.isEnabled()&&Fs(o.nativeApp),c=Bs(e)&&($r(o.nativeApp)||a),l=ze(o,e)||c,d={testId:o.testId,status:l?pe.SKIPPED:pe.QUEUED,name:o.name,resultId:o.resultId,testStatus:o.testStatus||qe.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...c&&{reason:this.getMobileRunSkippedReason(a,o.nativeApp)},config:Object.assign({},this.execConfig,{companyId:r,testData:((m=o.testData)==null?void 0:m.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((p=o.testData)==null?void 0:p.total)||null,testDataIndex:((g=o.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,d]});return Object.fromEntries(n)}async executionStart(e,t,r,n,o){Ye.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Yr(()=>Promise.all([an.end(t),So("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...U.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},d=await ci(i.beforeSuite,l),m=new ai(d,vr.cloneDeep(this.testInfoList),t);this.testInfoList=m.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=d;let{testInfoList:p}=this,g=[],f=[],h=[];for(let v of p){if(v.isBeforeTestPlan){g.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}f.push(v)}let y=async()=>{let v=vr.cloneDeep(this.testRunStatus);await ie(Object.keys(v),async I=>{var O;let C=v[I],k=(O=C.config)==null?void 0:O.testData,R=C.testId,M=await xo(t,R,I,k,c.defaults);M&&(delete C.config.testData,C.config.testDataUrl=M)});let S=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:r,executions:v,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:S,intersections:i.intersections},w=Ac(b);return this.executionStartedPromise=w,w.catch(I=>Ye.error(I)),w};try{await y()}catch(v){Ye.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){vr.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=rc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:p}of t)m===pe.PASSED&&n++,m===pe.SKIPPED&&o++,m===pe.FAILED&&p===qe.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await ci(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ye.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Lf(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await So("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(m){throw Ye.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await xc(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});var Wf,Pt,Xl,pt,ui=T(()=>{"use strict";B();ce();le();ye();Ve();Wf=E(require("ora")),Pt=x("mobile-grid-service"),Xl=class{constructor(){this.gridsAppIdGetter={[N.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getTdcAppPath(t),[N.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getHeadspinAppPath(t),[N.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getBrowserStackAppPath(t),[N.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===N.TESTIM_TDC||e===N.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===N.TESTIM_HEADSPIN?`${_p}/devices`:e===N.TESTIM_TDC?`${Lp}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await je({url:r,headers:n,body:o})}catch(i){throw Pt.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Ne(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw Pt.error("error while getting automation config for device",{error:o,deviceId:t}),o}}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if([N.BROWSERSTACK,N.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,c;if(t===N.TESTIM_HEADSPIN||t===N.TESTIM_TDC){let l=await Xc({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=l==null?void 0:l[0])==null?void 0:a.name)||e.device}return t===N.BROWSERSTACK?(c=e.mobile)==null?void 0:c.version.split("-")[0]:t===N.SAUCELABS?e.testobject_device_name:e.device}async updateDeviceOnRemoteTestResult(e,t,r){var y;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:c}={},company:{companyId:l=""}={},gridData:{gridId:d="",type:m=""}={}}=r,p=t.capabilities,g=await this.getDeviceNameFromSessionCaps({capabilities:p,gridType:m,projectId:a,projectType:c,companyId:l,gridId:d}),f=p.platformVersion;!f&&m===N.BROWSERSTACK&&(f=(y=p.mobile)==null?void 0:y.version.split("-")[1]);let h={name:g,model:p.deviceModel,osVersion:f,udid:p.udid,osType:p.platformName,scaleFactor:p.pixelRatio,isVirtual:!1};return await yr(a,n,o,i,"RUNNING",{device:h}),Pt.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h}),h}async getTmaDeviceDetails(e){let t=await Ne(`${Dp}/devices`),r=t==null?void 0:t.find(n=>n.udid===e);return r?{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}:{}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:c}=t;return await yr(c,n,o,i,"RUNNING",{device:a}),Pt.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await kc({appId:e,projectId:t});if(!i)throw Pt.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw Pt.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Op*60))+1)*60*1e3,Math.max(kp,t)}async getAppInfoForRemoteRun({testRunHandler:e,options:t}){let r="",n,{executionId:o,testResultId:i}=e,{appId:a,project:c,authData:{token:l=""}={},gridData:{gridId:d="",type:m="",host:p=""}={}}=t;if(a){Pt.info("getting appData by appId",{appId:a,projectId:c,testResultId:i,executionId:o});let y=await this.getMobileAppDataByAppId({appId:a,projectId:c,token:l,executionId:o,testResultId:i});r=y.appUrl,n=y.mobileApp,e.nativeApp=n}else Pt.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:i,executionId:o}),r=e.downloadableAppPublicLink||"";let g=this.gridsAppIdGetter[m]({testRunHandler:e,mobileApp:n,gridHost:p}),f=!!g&&m===N.TESTIM_TDC,h=!!g&&m===N.TESTIM_HEADSPIN;if(g&&(r=g),!g&&N.BROWSERSTACK===m){if(e.isAppFromDevice)throw new Error("The selected application from your device is not supported by the BrowserStack grid. Please choose a compatible application for testing.");let y=n||e.mobileApp,v=(0,Wf.default)("uploading app to browserstack please wait..").start();try{Pt.info("uploading app to browserstack",{appId:a,projectId:c,testResultId:e.testResultId,executionId:e.executionId});let S=await Qc({projectId:c,gridId:d,app:y,timeout:this.calculateUploadRequestTimeOut(y.fileSize)});v.succeed("app uploaded successfully to browserstack"),r=S.browserStackAppId}catch(S){throw v.fail("failed to upload app to browserstack"),Pt.error("failed to upload app to browserstack",{error:S}),new Error("failed to upload app to browserstack")}}return{appPath:r,isTdcAppIdExists:f,isHSAppIdExists:h}}},pt=new Xl});function _v(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function ru(s){return Hf.readFileSync(s,{encoding:"base64"})}function Jf(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Be(s))&&s){let r=ru(s);ns.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${tu(r)} current extension count: ${e.length}`),e.push(r)}}function Yf(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,l=r||c,d=`--load-extension=${l}`;ns.info(`adding extension: testim unpacked , path: ${l}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=eu.join(process.cwd(),`testim-headless${o}`),a=ru(i);ns.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${tu(a)} current extension count: ${e.length}`),e.push(a)}function Lv(s,e,t,r,n,o,i){var f,h;let a=t.seleniumName||t.browserValue,c=[],l=[...Kf];e.headless&&l.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":Ql.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Ql.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};Zl(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-1",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Zl(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=Ql.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(f=e.projectData)==null?void 0:f.defaults)!=null&&h.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+za.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),Jf(r,c,i),e.mode===Y.EXTENSION&&Yf(e,c,l,o,i),c.length>0&&(d.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=l;let p={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],g={MicrosoftEdge:"ms",chrome:"goog"}[a];return ne.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[p]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${g}:${p}`]=d),s}function Mv(s,e,t){let r={"pdfjs.disabled":!0};if(U.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Vf.join(","),"browser.helperApps.neverAsk.openFile":Vf.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Y.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=eu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=ru(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function Nv(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let o=(0,zf.cloneDeep)(t.sl);return t.sl.screenResolution&&(n["sauce:options"].screenResolution=t.sl.screenResolution,delete o.screenResolution),Object.assign({},o,r,n)}return Object.assign({},r,n)}return{}}function Uv(s,e,t){return dt.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,s.browserstack,{name:e})):Object.assign({},s.browserstack,{name:e})}function Fv(s){return s.perfecto?s.perfecto:{}}function Bv(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 jv(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=va(o,i)),a}function di(s,e,t,r,n,o,i,a=null){var h,y;if(r.mode==="local"){let v=[],S=[...Kf],b={};return s.headless&&S.push("--headless"),s.silentDebuggerExtensionApi&&S.push("--silent-debugger-extension-api"),s.remoteDebuggingPort!==void 0&&S.push(`--remote-debugging-port=${s.remoteDebuggingPort}`),s.chromeExtraArgs&&s.chromeExtraArgs.forEach(w=>S.push(`--${w}`)),s.chromeBinaryLocation&&(b.binary=s.chromeBinaryLocation),s.mode!=="selenium"&&Yf(s,v,S,null,a),Jf(n,v,a),{logLevel:Gf,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:S,extensions:v,...b},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=s,d=jv(s,r),m={hostname:r.host,host:r.host,port:r.port||4444,path:r.path||"/wd/hub",protocol:r.protocol||"http",logLevel:Gf,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,s.getSessionTimeout),getSessionRetries:a.getSessionRetries||s.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!dt.isEmpty(d)&&{headers:d},...s.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};Zl(r)&&(s.oldCapabilities=!1,s.w3cCapabilities=!0,m.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),s.disableNativeEvents&&(m.desiredCapabilities.nativeEvents=!1),r.user&&r.key&&(r.type==="saucelabs"&&(s.saucelabs||={},s.saucelabs.username||=r.user,s.saucelabs.accessKey||=r.key),r.type==="browserstack"&&(s.browserstack||={},s.browserstack["browserstack.user"]||=r.user,s.browserstack["browserstack.key"]||=r.key)),r.key&&r.type==="perfecto"&&(s.perfecto.securityToken=r.key);let p=Number(s.browserTimeout/1e3),g=s.browser||(t==null?void 0:t.browserValue);dt.merge(m.desiredCapabilities,Nv(s,e,t),Uv(s,e,t),Fv(s),Bv(s,g,p),a==null?void 0:a.getCapabilities(s,g,o,i,e));let f=null;switch(!s.ext&&!s.extensionPath&&((h=r.host)!=null&&h.endsWith(".testim.io"))&&!s.canary&&s.mode===Y.EXTENSION&&(g==="chrome"?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),(y=r.host)!=null&&y.endsWith(".testim.io")&&g==="edge-chromium"&&(m.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":m=Dv(m,s,t,n,r,f,a);break;case"firefox":m=Mv(m,s,a);break;case"safari":case"safari technology preview":m=_v(m,g);break;default:break}dt.merge(m.desiredCapabilities,s.seleniumCapsFileContent);try{let v={"hub.lambdatest.com":"lambdatest",[U.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},S=C=>C[r.provider]||C[m.host]||C[v[m.host]],b=C=>{var k,R;return S(C)||C[(k=m.desiredCapabilities)==null?void 0:k.browserName]||C[(R=m.desiredCapabilities)==null?void 0:R.version]||C||{}},w=JSON.parse(U.flags.addCustomCapabilities.getValue()||"{}"),I=b(b(w));Object.keys(I).length&&(ns.info(`Adding custom capabilities: ${JSON.stringify(I)}`),Object.assign(m.desiredCapabilities,I))}catch(v){ns.error("Failed to load custom capabilities",{error:v,customCapabilities:U.flags.addCustomCapabilities.getValue()})}return m.desiredCapabilities&&!m.capabilities&&(Ov(m),m.capabilities={alwaysMatch:m.desiredCapabilities,firstMatch:[{}]},delete m.desiredCapabilities),m.hostname=m.host,m}function su({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.");let r=[N.BROWSERSTACK,N.SAUCELABS,N.TESTIM_HEADSPIN,N.TESTIM_TDC];if(t.mode!=="local"&&!r.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function $v({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==N.TESTIM_TDC&&e.type!==N.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 Wv(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function Xf(s,e,t){let{fullReset:r,resetAppData:n,skipLoadBalancer:o}=e,i=s===N.TESTIM_TDC?"tdc":"headspin";return{[`${i}:capture`]:!0,...o&&{[`${i}:controlLock`]:!0},[`${i}:retryNewSessionFailure`]:!1,[`${i}:sessionTags`]:Wv(t),...!r&&!n&&{"appium:noReset":!0},...!r&&n&&{"appium:noReset":!1}}}function pi(s){return"id"in s?s.id:s.packageName}function Qf({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o,isHSAppIdExists:i,isTdcAppIdExists:a}){let{fullReset:c,resetAppData:l,resetOnSessionStartOnly:d}=t,m={"appium:app":n};switch(i&&(m={"headspin:app.id":n}),a&&(m={"tdc:app.id":n}),s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...c&&{"appium:fullReset":c,"appium:resetOnSessionStartOnly":d},...r&&{"appium:bundleId":pi(r)},...n&&m};case"android":return{...e,platformName:"Android",...c&&{"appium:fullReset":c},...!c&&l&&{"appium:autoGrantPermissions":!0},"appium:automationName":"UiAutomator2","appium:appWaitActivity":o,...r&&{"appium:appPackage":pi(r),"appium:appActivity":r.activity},...n&&m};default:throw Error(`unsupported mobile project ${s}`)}}function Zf({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,isHSAppIdExists:i}){let a=Xf(N.TESTIM_HEADSPIN,o,n);return a=Qf({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r,isHSAppIdExists:i}),a}function eg({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,isTdcAppIdExists:i}){let a=Xf(N.TESTIM_TDC,o,n);return a=Qf({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r,isTdcAppIdExists:i}),a}function Gv({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 Vv({deviceName:s,mobileConfig:e,projectType:t}){let{staticAllocation:r,dynamicAllocation:n,selectedGrid:o}=e;return s||(r!=null&&r.deviceName?r.deviceName:n!=null&&n.deviceNameRegex?n.deviceNameRegex:(o==null?void 0:o.type)===N.BROWSERSTACK&&t==="ios"?"iPhone.*":".*")}function Hv({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,p=m===N.BROWSERSTACK?"browserstack":"saucelabs",g=Gv({osVersion:c,mobileConfig:d}),f=Vv({deviceName:l,mobileConfig:d,projectType:s}),h={...m===N.BROWSERSTACK&&{os_version:g,device:f,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...m===N.SAUCELABS&&{platformVersion:g,deviceName:f,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${p}.user`]:o.user,[`${p}.key`]:o.key,[`${p}.debug`]:!0,[`${p}.networkLogs`]:!0};switch(s){case"ios":return{...h,autoAcceptAlerts:!0,platformName:"iOS",automationName:"XCUITest",...e&&{bundleId:pi(e)},...t&&{app:t}};case"android":return{...h,autoGrantPermissions:!0,platformName:"Android",automationName:"UiAutomator2",appWaitActivity:r,...e&&{appPackage:pi(e),appActivity:e.activity},...t&&{app:t}};default:throw Error(`unsupported mobile project ${s}`)}}function tg(s){return N.TESTIM_HEADSPIN===s.gridInfo.type?Zf(s):N.TESTIM_TDC===s.gridInfo.type?eg(s):Hv(s)}function rg(s){return su(s),tg(s)}function qv(s,e){var l,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,c={};return n==="dynamic"&&(!o&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),o&&(c.manufacturer=o),i&&(c.os_version=i),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}function sg(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);su({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=pt.getGridConnection(e),c=tg(s);if(e.type===N.TESTIM_HEADSPIN||e.type===N.TESTIM_TDC){let l=e.type===N.TESTIM_HEADSPIN?"headspin":"tdc",d=qv(r,o==null?void 0:o.mobile);if(!dt.isEmpty(d)){let m=Object.entries(d).map(([p,g])=>g.split(",").map(f=>f===".*"||f==="="?"":`${p}:${f}`).join(",")).join(" ").trim();c[`${l}:selector`]=m}}return{...a,desiredCapabilities:c,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function ng(s){var v,S;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,isHSAppIdExists:c,isTdcAppIdExists:l,testRunConfig:d}=s,{deviceUdid:m}=n;su({nativeAppMetadata:r,appPath:o,gridInfo:t}),$v({deviceUdid:m,gridInfo:t,testRunConfig:d});let p=m||((S=(v=d.mobile)==null?void 0:v.staticAllocation)==null?void 0:S.deviceUdid),g=await pt.getGridDirectConnection(t,p),f=t.type===N.TESTIM_TDC,h={projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,...!f&&{isHSAppIdExists:c},...f&&{isTdcAppIdExists:l},testRunConfig:d},y=f?eg(h):Zf(h);return p&&(y["appium:udid"]=p),{...g,desiredCapabilities:y,capabilities:y,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function og(s){let e=Object.assign({},s);return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],delete e.capabilities.key,delete e.capabilities.user,e}var Hf,eu,qf,dt,zf,ns,Gf,Ql,Kf,tu,Zl,Ov,Dv,Vf,gn=T(()=>{"use strict";Hf=E(require("fs")),eu=E(require("path")),qf=E(require("crypto")),dt=E(require("lodash"));j();le();B();Te();ce();$o();ui();zf=require("lodash"),ns=x("testim-desired-capabilities-builder"),Gf=qn?"debug":"silent",Ql={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Kf=["--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"],tu=(...s)=>qf.createHash("sha256").update(s.join("")).digest("hex"),Zl=s=>s.type===N.DEVICE_FARM||s.type===N.HYBRID&&s.provider==="devicefarm",Ov=s=>{var r;let{desiredCapabilities:e}=s;Object.prototype.hasOwnProperty.call(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.prototype.hasOwnProperty.call(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.prototype.hasOwnProperty.call(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.prototype.hasOwnProperty.call(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.prototype.hasOwnProperty.call(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.prototype.hasOwnProperty.call(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=U.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ns.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};Dv=dt.memoize(Lv,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(dt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return tu(i,a,c,r,l,o)}),Vf=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Me(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function ig(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 nu=T(()=>{"use strict"});function ou(s){function e(p){return p?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(p.nodeType):!1}function t(p){return p?r(p.parentNode,e):null}function r(p,g){for(let f=p;f&&f!==p.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(p,g){for(let f=p;f&&f!==p.ownerDocument;f=t(f))if(g(f))return f;return null}function o(p,g){if(!p||!g)return null;p instanceof DocumentFragment&&(p=p.host);let h=window.getComputedStyle(p).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(p);return o(y,g)}function i(p){let g=p.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(p.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(p,"stroke-width");return!!h&&parseInt(h,10)>0}return o(p,"overflow")==="hidden"?!1:Array.from(p.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(p){return o(p,"overflow")==="hidden"}function c(p){return!p||!a(p)||!p.childNodes.length?!1:Array.from(p.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function l(p){var g;return p?(g=p.parentNode)!=null&&g.host?!0:l(p.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=r(s,f=>f.tagName.toUpperCase()==="SELECT");return ou(g)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,p=>Number(o(p,"opacity"))===0),m=!!n(s,p=>o(p,"display")==="none");return!(d||m||!i(s)||c(s))}var ag=T(()=>{"use strict"});var cg,lg,os,zv,Kv,fi,ug=T(()=>{"use strict";cg=E(require("promise-queue")),lg=E(require("webdriverio"));le();Fe();j();B();Cr();ag();nu();ss();os=x("WebDriverApi"),zv=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},Kv={implicit:0,pageLoad:1,script:2},fi=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw os.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof Ia<"u"&&(e=Ia);let t=1/0;this.queue=new cg.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),L("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{os.info("requesting browser",{testResultId:r,testName:t}),L("before this.client.init"),this.client=await lg.remote(e)}),L("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,xe.GET_BROWSER)}}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){os.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Me(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Me(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Oe(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(ou,{ELEMENT:e,[Wt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Me(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(ig(e,this.isSafari(),os))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[Kv[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Me(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Oe(e)),await this.elementIdValue(Oe(e),t)}async getViewportSize(e){let t=await this.execute(zv);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async keys(e){let t=i=>Ta.hasOwnProperty(i)?[Ta[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(Array.isArray(e))for(let i of e)r=r.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:r})},o=()=>{let i=r.map(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Me(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Oe(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Me(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{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){os.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 os.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 pg={};G(pg,{doubleClick:()=>Jv});var Jv,dg=T(()=>{"use strict";Jv=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(p){function g(S,b,w){return w>S&&w<b}let f=p.pointerPosition||{},h=r.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,v=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:v}},a=function(p,g){return{screenX:0,screenY:0,clientX:p,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(p,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(p,h)},l=function(p,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(p,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},d=function(){var g;let p=document.activeElement;for(;(g=p.shadowRoot)!=null&&g.activeElement;)p=p.shadowRoot.activeElement;return p},m=function(p){let g=i(p),f=p.event;return t.includes(f)?c(f,g.x,g.y):l(f,g.x,g.y)};try{n.map(g=>m(g)).filter(Boolean).forEach(g=>r.dispatchEvent(g));let p=d();dispatchFocus(s.elementToFocusLocatedElement,p),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(p){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:p.toString(),success:!1})}}});var hn={};G(hn,{dispatchFocus:()=>Yv});function Yv(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var yn=T(()=>{"use strict"});var yg={};G(yg,{WebDriver:()=>Sr});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 Qv(r):void 0}catch(r){We.info("Error getting cdpAddress",r);return}}var is,gg,hg,We,tr,Xv,mg,Qv,rr,Zv,fg,Er,Sr,bn=T(()=>{"use strict";is=E(require("lodash"));j();Fe();gn();gg=E(require("p-retry")),hg=E(require("ua-parser-js"));Cr();B();nu();ug();z();Te();ss();We=x("webdriver"),[tr,Xv]=[0,2],{extractElementId:mg,getCdpAddressForHost:Qv}=K,rr=()=>(be(),fe(Yt)).getSessionPlayer().codeSnippets,Zv=()=>(be(),fe(Yt)).getSessionPlayer().locatorBuilderUtils,fg=()=>(be(),fe(Yt)).getSessionPlayer().utils,Er=()=>(be(),fe(Yt)).getSessionPlayer().positionUtils;Sr=class extends fi{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}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t,r,n,o,i,a,c,l=new Bt,d=!1,m=void 0){var h,y,v,S,b,w,I,C;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(y=(h=t==null?void 0:t.company)==null?void 0:h.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let p=di(t,r,n,o,i,a,c,m);p.desiredCapabilities&&delete p.desiredCapabilities.marionette,p.capabilities&&delete p.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(m==null?void 0:m.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=l;let g=d?0:1500,f=d?()=>null:()=>this.executeJS("window.focus()");try{L("before initClient in webdriver.js init");let k=await this.initClient(p,r,c);L("after initResult before getCdpAddress in init"),this.cdpUrl=await eE(k),L("after getCdpAddress in webdriver.js init"),We.info(`init new session testName: ${r}`,{sessionId:this.getSessionId(),testResultId:c}),await oe(g),U.flags.dontFocusOnInit.isEnabled()||await f(),L("after focus and delay in webdriver.js init")}catch(k){let R=JSON.stringify(is.omit(p,"capabilities.extensions","capabilities.capabilities.extensions"));We.error("failed to init webdriver",{err:k,capabilitiesAsString:R});let M=((b=(S=t==null?void 0:t.company)==null?void 0:S.activePlan)==null?void 0:b.plan)==="free";throw(w=k.stack)!=null&&w.includes("at startWebDriverSession")&&((I=k.message)!=null&&I.startsWith("Failed to create session"))&&((C=k.message)!=null&&C.includes("Timeout awaiting 'request'"))&&M?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/Invalid username or password/)?new Dr(k.message):k.message.match(/capabilit(y|ies)/)?new Kn(k.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>is.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(d=>d.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=te();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,We.warn("close unexpected alert open"),await this.alertAccept().catch(c=>We.warn("failed to click on alert",{err:c}));return}if(We.warn("err while getting testim status",{err:a}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=mg(r.value);return await this.switchToFrame({ELEMENT:n,[Wt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new Jn:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||U.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
22
|
+
var fn = ${rr().getLocatedElementCode};
|
|
23
23
|
return fn.apply(null, arguments);
|
|
24
|
-
`,t)}finally{this.seleniumPerfStats.markEnd(
|
|
25
|
-
var getLocatedElement = ${
|
|
24
|
+
`,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:o,attributeValue:i,locatedElement:a}){let c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(o,i)}await this.executeJS(`
|
|
25
|
+
var getLocatedElement = ${rr().getLocatedElementCode};
|
|
26
26
|
var setDynamicParentAttribute = ${n.toString()};
|
|
27
27
|
return setDynamicParentAttribute.apply(null, arguments)
|
|
28
|
-
`,{attributeName:
|
|
29
|
-
const getLocatedElement = ${
|
|
30
|
-
const getLocation = ${
|
|
28
|
+
`,{attributeName:Zv().DYNAMIC_PARENT_FIELD_NAME,attributeValue:r,locatedElement:t.locatedElement})}getLocatedElementRectWithPadding(t){function r(n){let o=getLocatedElement(n);if(!o)return null;let i=parseInt(window.getComputedStyle(o).paddingTop.replace("px",""),10)||0,a=parseInt(window.getComputedStyle(o).paddingLeft.replace("px",""),10)||0,c=o.getBoundingClientRect();return{top:Math.round(c.top+i),left:Math.round(c.left+a)}}return this.executeJS(`
|
|
29
|
+
const getLocatedElement = ${rr().getLocatedElementCode};
|
|
30
|
+
const getLocation = ${r.toString()};
|
|
31
31
|
return getLocation.apply(null, arguments)
|
|
32
|
-
`,t)}getElementLocationWithPadding(t){return this.getLocatedElementRectWithPadding(t)}getLocatedElementRect(t){function
|
|
33
|
-
const getLocatedElement = ${
|
|
34
|
-
const getLocation = ${
|
|
32
|
+
`,t)}getElementLocationWithPadding(t){return this.getLocatedElementRectWithPadding(t)}getLocatedElementRect(t){function r(n){let o=getLocatedElement(n);if(!o)return null;let i=o.getBoundingClientRect();return{bottom:Math.round(i.bottom),height:Math.round(i.height),x:Math.round(i.left),right:Math.round(i.right),y:Math.round(i.top),width:Math.round(i.width)}}return this.executeJS(`
|
|
33
|
+
const getLocatedElement = ${rr().getLocatedElementCode};
|
|
34
|
+
const getLocation = ${r.toString()};
|
|
35
35
|
return getLocation.apply(null, arguments)
|
|
36
|
-
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function
|
|
37
|
-
const getLocatedElement = ${
|
|
38
|
-
const extractText = ${
|
|
36
|
+
`,t)}getElementLocation(t){return this.getLocatedElementRect(t.locatedElement)}getTargetText(t){return this.getElementTextJS(t.locatedElement)}async getElementTextJS(t){function r(o,i){function a(p){var f;return(f=p.childNodes)!=null&&f.length&&Array.from(p.childNodes).filter(h=>h.nodeType===Node.ELEMENT_NODE).forEach(h=>{typeof h.tagName=="string"&&h.tagName.toLowerCase()==="title"?p.removeChild(h):a(h)}),p}function c(p){return["INPUT","TEXTAREA"].includes(p.tagName)}function l(p){var g,f,h;try{if(p.shadowRoot&&!((h=(f=Object.getOwnPropertyDescriptor((g=p.ownerDocument.defaultView)==null?void 0:g.Node.prototype,"textContent"))==null?void 0:f.get)!=null&&h.toString().includes("[native code]")))return p.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(i&&Array.prototype.some.call(p.children,y=>y.hidden)){let y=p.cloneNode(!0);return Array.prototype.filter.call(y.children,S=>S.hidden).forEach(S=>y.removeChild(S)),y.textContent.replace(/(\r\n|\n|\r)/gm,"")}return p.textContent.replace(/(\r\n|\n|\r)/gm,"")}function d(p){if(c(p))return p.value;if(p instanceof SVGElement){let g=p.cloneNode(!0);return a(g).textContent.replace(/(\r\n|\n|\r)/gm,"")}return l(p)}let m=getLocatedElement(o);return m?d(m):""}let{value:n}=await this.executeJS(`
|
|
37
|
+
const getLocatedElement = ${rr().getLocatedElementCode};
|
|
38
|
+
const extractText = ${r.toString()};
|
|
39
39
|
return extractText.apply(null, arguments)
|
|
40
|
-
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var o,i;let
|
|
41
|
-
var getLocatedElement = ${
|
|
40
|
+
`,t,this.ignoreHiddenTagsText);return n}async getHTML(t){var o,i;let r=rr().getHtmlCode(null,t),n=this.seleniumPerfStats.markStart(xe.GET_HTML);try{let{value:a}=await this.executeJS(r);return this.seleniumPerfStats.markEnd(n,xe.GET_HTML),a}catch(a){this.seleniumPerfStats.markEnd(n,xe.GET_HTML);let c=Object.assign(new Error(""),{success:!1,reason:a.toString(),errorType:"internal-error"});throw(i=(o=this.client)==null?void 0:o.requestHandler)!=null&&i.sessionID||Object.assign(c,{extraInfo:"Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"}),c}}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(t,r){class o extends Error{}function i(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}}let a=()=>(0,gg.default)(async()=>{let{value:l}=await this.windowHandleSize(),{value:d}=await this.execute(i),m=l.width-d.screenWidth,p=l.height-d.screenHeight;await this.windowHandleSize({width:t.width+m,height:t.height+p});let{value:g}=await this.execute(i);if(g.screenWidth!==t.width||g.screenHeight!==t.height)throw new o},{retries:5-1,factor:1,minTimeout:0}).catch(l=>{if(!(l instanceof o))throw l});if(typeof t!="object"||typeof t.width!="number"||typeof t.height!="number"||typeof r<"u"&&typeof r!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(typeof r>"u"?!0:r)?a():this.windowHandleSize(t)}setViewportSize(t,r){return this.setViewportSizeNEW({width:t,height:r},!0)}getBrowserMajorVersion(t){try{return parseInt(t.browser.major,10)}catch(r){return We.error("failed to get browser version",{err:r}),0}}async getBrowserAndOS(){function t(a){let c=a.match(/(opera|chrome|safari|firefox)\/?\s*(\d+)/i)||[];if(c[1]==="Chrome"&&a.match(/\bOPR\/(\d+)/)!==null)return"opera";if(c[1]==="Chrome"&&a.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";c=c[2]?[c[1],c[2]]:[a.appName,a.appVersion,"-?"];let l=a.match(/version\/(\d+)/i);return l!==null&&c.splice(1,1,l[1]),c[0].toLowerCase()}if(this.browserAndOS)return this.browserAndOS;function r(){return typeof window>"u"||!window.navigator||!window.navigator.userAgent?"unknown":window.navigator.userAgent}let{value:n}=await this.executeJS(r),o=(0,hg.default)(n),i=o.os;return this.browserAndOS={os:`${i.name} ${i.version}`,browserMajor:this.getBrowserMajorVersion(o),browser:t(n),userAgent:n,browserVersion:o.browser.version},this.browserAndOS}async getUserAgentInfo(){let{value:t}=await this.executeJS(`return ${rr().getUserAgentInfo()}`);return t}setValue(t,r){return super.setValue(t,r)}getRelativeMoveActions(t,r){let{rect:n,clickOffset:o}=t,i=Er().calculateElementMiddlePoint(n),a=o.x,c=o.y;return!fg().isWithinBounds(n.left,n.left+n.width,i.x+a)||!fg().isWithinBounds(n.top,n.top+n.height,i.y+c)?(We.warn("using element center as fallback for offset"),this.getMoveActions(0,0,r)):this.getMoveActions(a,c,r)}computeAbsoluteMovement(t){let{frameOffset:r,rect:n,clickOffset:o}=t,i=n.left+o.x+r.x,a=n.top+o.y+r.y;return{x:i,y:a}}async actWithActionsAPI(t,r,n,o){let i=this.getRelativeMoveActions(t,n),a=this.getClickActions(o,r);try{return await this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:i.concat(a)}])}catch(c){We.error("tried to use element origin but failed because of visibility, trying absolute",c);let{x:l,y:d}=this.computeAbsoluteMovement(t),m=this.getMoveActions(l,d);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:m.concat(a)}])}}doubleClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,tr,t,["pointerDown","pointerUp","pointerDown","pointerUp"])}async doubleClickWithJS(t){let[{doubleClick:r},{dispatchFocus:n}]=await Promise.all([Promise.resolve().then(()=>(dg(),pg)),Promise.resolve().then(()=>(yn(),hn))]);return this.executeCodeAsync(`
|
|
41
|
+
var getLocatedElement = ${rr().getLocatedElementCode};
|
|
42
42
|
var dispatchFocus = ${n.toString()};
|
|
43
|
-
var doubleClick = ${
|
|
43
|
+
var doubleClick = ${r.toString()};
|
|
44
44
|
var eventData = arguments[0];
|
|
45
45
|
var done = arguments[1];
|
|
46
46
|
return doubleClick.call(null, eventData, done);
|
|
47
|
-
`,t.timeout,t)}getClickActions(t=[],
|
|
48
|
-
var res = requireOrImportMethod('${
|
|
47
|
+
`,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,tr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,Xv,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(Me(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(Me(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 We.warn(`could not find element for locatedElement ${t}`),new Error("could not calculate rect");let{x:o,y:i,width:a,height:c}=n.value;return{x:r.left+o+a/2,y:r.top+i+c/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:o}=r.clickOffset;try{return await this.moveTo(t,n,o)}catch(i){if(Me(i))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw i}}getMoveActions(t=1,r=1,n="viewport",o=0){return[{type:"pointerMove",duration:o,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){We.error("tried to use element origin but failed because of visibility, trying location",n);let o=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(o)}}getDragCoordinates(t){let r=t.filter(i=>i.event==="mousemove"||i.event==="pointermove"),n=r[0].pointerPosition,o=r.at(-1).pointerPosition;return{xDiff:o.screenX-n.screenX,yDiff:o.screenY-n.screenY}}async dragWithMoveTo(t,r,n,o,i){return await this.moveTo(t,o,i),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,o,i){let a=this.getMoveActions(o,i,t,1),c=this.getClickActions(["pointerDown"],tr),l=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],tr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(d)}])}async drag(t,r,n,o,i){let{width:a,height:c}=r,l=n-a/2+1,d=o-c/2,m=this.getDragCoordinates(i),{xDiff:p,yDiff:g}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,p,g,l,d);try{return await this.dragWithMoveTo(t,p,g,l,d)}catch(f){if(Me(f))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,p,g,l,d);throw f}}getMoveRelativeSequence(t,r,n,o){let i=(p,g)=>Math.hypot(p.x-g.x,p.y-g.y),a={x:t,y:r},c={x:n,y:o},l=10,d=Math.round(i(a,c)/l),m=Array.from({length:d},()=>({x:Math.round((c.x-a.x)/d),y:Math.round((c.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,o){return this.getMoveRelativeSequence(t,r,n,o).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:o,fromX:i,fromY:a,toRect:c,toX:l,toY:d}=n,m=Er().calculateElementMiddlePoint(o),p=Er().calculateElementMiddlePoint(c),g=this.getMoveRelativeSequence(m.x+i,m.y+a,p.x+l,p.y+d);await this.moveTo(t,Math.floor(i),Math.floor(a)),await this.buttonDown();for(let f of g)await this.moveTo(null,f.x,f.y);return await this.moveTo(r,Math.round(l),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:c}=t,l=Er().calculateElementMiddlePoint(r),d=Er().calculateElementMiddlePoint(i),m=Math.floor(l.x+n),p=Math.floor(l.y+o),g=Math.floor(d.x+a),f=Math.floor(d.y+c),h=this.getMoveAbsoluteSequence(m,p,g,f),y=this.getMoveActions(m,p),v=this.getClickActions(["pointerDown"],tr),S=is.flatMap(h,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(g,f),w=this.getClickActions(["pointerUp"],tr),I=y.concat(v).concat(S).concat(b).concat(w);return this.actions([{type:"pointer",id:"mouse",actions:I}])}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(o){if(Me(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw o}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(o){if(Me(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw o}}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(o){if(Me(o))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw o}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:c}=t,l=Er().calculateElementMiddlePoint(r),d=Er().calculateElementMiddlePoint(i),m=Math.floor(l.x+n),p=Math.floor(l.y+o),g=Math.floor(d.x+a),f=Math.floor(d.y+c);await this.moveWithActionsAPI({x:m,y:p});let h=this.getClickActionList(["pointerDown"],tr);await this.actions(h),await this.moveWithActionsAPI({x:g,y:f});let y=this.getClickActionList(["pointerUp"],tr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(mg(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(o){We.error("error getting element location",{err:o})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){We.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||We.warn("failed to close session because session is undefined"),clearInterval(this.keepAliveTimer);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(Me(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var iu,au,gi,cu=T(()=>{"use strict";B();Te();ye();iu=x("lab-features-service"),au=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(iu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await jc(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){iu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=U.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:o}=this,i=n.find(c=>c.featureFlagName===e),a=i==null?void 0:i.enabled;return Boolean(o&&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 iu.error(t,{featureFlagName:e.name}),new Error(t)}},gi=new au});function tE(s){let e=/^\\\\\?\\/.test(s),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(i=>{let a=JSON.parse(i);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={},o=void 0,i=void 0){let a=Object.keys(n).map(f=>`
|
|
48
|
+
var res = requireOrImportMethod('${tE(n[f])}');
|
|
49
49
|
if (res.sync) {
|
|
50
50
|
var ${f} = res.lib;
|
|
51
51
|
} else {
|
|
52
52
|
var ${f} = await res.lib;
|
|
53
53
|
}
|
|
54
54
|
`).join(""),c=i?`
|
|
55
|
-
${
|
|
55
|
+
${wg.default.toString()}
|
|
56
56
|
var fileBuffer = dataUriToBuffer('${i}');
|
|
57
57
|
`:"var fileBuffer = null;",l=`
|
|
58
58
|
const getMessage = arguments => {
|
|
@@ -106,9 +106,9 @@ WARNING: ${r} is deprecated. ${t}
|
|
|
106
106
|
oldMethod?.apply(console, arguments);
|
|
107
107
|
};
|
|
108
108
|
});
|
|
109
|
-
`,
|
|
109
|
+
`,d=`
|
|
110
110
|
function injectCode(params, args, incomingParams, context, code) {
|
|
111
|
-
const constructWithArguments = ${
|
|
111
|
+
const constructWithArguments = ${sE.toString()}
|
|
112
112
|
|
|
113
113
|
const resolve = result => {
|
|
114
114
|
parentPort.postMessage({
|
|
@@ -169,12 +169,12 @@ WARNING: ${r} is deprecated. ${t}
|
|
|
169
169
|
});
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
|
-
`,
|
|
172
|
+
`,m=`
|
|
173
173
|
(async function() {
|
|
174
174
|
// A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
|
|
175
175
|
const __require = require;
|
|
176
176
|
const { parentPort } = require('worker_threads');
|
|
177
|
-
const requireOrImportMethod = ${
|
|
177
|
+
const requireOrImportMethod = ${rE.toString()}
|
|
178
178
|
|
|
179
179
|
// requireCode will set async to be true if needed.
|
|
180
180
|
${a}
|
|
@@ -183,7 +183,7 @@ WARNING: ${r} is deprecated. ${t}
|
|
|
183
183
|
|
|
184
184
|
${l}
|
|
185
185
|
|
|
186
|
-
const isPromise = ${
|
|
186
|
+
const isPromise = ${Da.toString()}
|
|
187
187
|
|
|
188
188
|
parentPort.once('message', input => {
|
|
189
189
|
const { incomingParams, context, code } = input;
|
|
@@ -207,78 +207,78 @@ WARNING: ${r} is deprecated. ${t}
|
|
|
207
207
|
args.push(fileBuffer);
|
|
208
208
|
}
|
|
209
209
|
|
|
210
|
-
${
|
|
210
|
+
${d}
|
|
211
211
|
|
|
212
212
|
injectCode(params, args, incomingParams, context, code);
|
|
213
213
|
});
|
|
214
214
|
})();
|
|
215
|
-
`,
|
|
216
|
-
Action required: Please allow opening a websockets connection to ${me} 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",()=>{Ei.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 s={query:{projectId:e},requestTimeout:$g,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=`${me}/${t}`,this._socket=Tu.connect(this.url,s),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let s={query:{projectId:e},requestTimeout:$g,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=`${me}/${t}`,this._socket=Tu.connect(this.url,s),this.addSocketHandlers()}emitPromise(e,t){let s={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(s[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Wg.default)(()=>ie(n(),DE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(s).length>0&&Ei.error("Bad acknowledge from socket emit",{errorneousEvents:s})}),this.emitPromiseQueue}}});var Vg={};W(Vg,{remoteStepServiceSocketIO:()=>ME});var wu,ME,Gg=T(()=>{"use strict";Si();wu=class extends rr{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}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,s){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&s(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},ME=new wu});var Hg={};W(Hg,{remoteStepService:()=>ps});var vu,Rn,Eu,ps,Ri=T(()=>{"use strict";Sn();ce();he();({REMOTE_STEP_SAVED:vu}=tt),Eu=class{async init(e){M.flags.useNewWSCLI.isEnabled()||(Rn=(await Promise.resolve().then(()=>(Gg(),Vg))).remoteStepServiceSocketIO,Rn.init(e))}joinToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?Ne.addFilter(`${e}:remoteStep`,{resultId:e},[vu]):Rn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(M.flags.useNewWSCLI.isEnabled()){Ne.listenTo(`${e}:remoteStep`,[vu],s=>s.resultId===e&&s.remoteStep&&s.remoteStep.status==="pending",s=>t(s.remoteStep));return}Rn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?(Ne.removeFilter(`${e}:remoteStep`,[vu]),Promise.resolve()):Rn.unlistenToRemoteStep(e)}},ps=new Eu});var Su,xr,qg=T(()=>{"use strict";Si();Su=class extends rr{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,s,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===s&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,s){return this.emitPromise("testResult:join",{resultId:t,testId:s})}async joinToTestResult(t,s){this.rooms[t]||this.joinRoom(t,s),await this.emitJoinRoom(t,s)}emitLeaveRoom(t,s){return this.emitPromise("testResult:leave",{resultId:t,testId:s})}leaveTestResult(t,s){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,s)):Promise.resolve()}getSocket(){return this._socket}},xr=new Su});var Kg={};W(Kg,{testResultService:()=>kt});var zg,Ru,kt,Ii=T(()=>{"use strict";zg=require("events");Sn();ce();he();qg();Ru=class extends zg.EventEmitter{init(e){if(M.flags.useNewWSCLI.isEnabled()){Ne.onConnect=()=>this.emit("socket-connected");return}xr.init(e),xr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return M.flags.useNewWSCLI.isEnabled()?Ne.addFilter(`${e}:testResult`,{resultId:e,testId:t},[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED]):xr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(M.flags.useNewWSCLI.isEnabled()){Ne.removeFilter(`${e}:testResult`,[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED]);return}await xr.leaveTestResult(e,t)}listenToTestResult(e,t,s){if(M.flags.useNewWSCLI.isEnabled()){Ne.listenTo(`${e}:testResult`,[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>s(n));return}xr.listenToTestResult(e,t,s)}getSocket(){if(!M.flags.useNewWSCLI.isEnabled())return xr.getSocket()}},kt=new Ru});var Yg,Xg,Qg,we,NE,Zg,Jg,xi,eh=T(()=>{"use strict";Yg=E(require("lodash"));B();le();Ue();Zr();xt();be();jg();Xg=E(require("p-retry")),Qg=require("url");$();Bo();os();ce();Ri();Ii();he();we=A("test-run-handler"),NE=3,Zg=20*1e3,Jg=r=>JSON.stringify(r).length<Zg,xi=class{constructor(e,t,s,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Ut;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=s.testStatus,this._testId=s.testId,this._testName=s.name,this._testResultId=s.resultId,this._baseUrl=n.baseUrl||s.baseUrl||s.testConfig.baseUrl,this._nativeApp=s.nativeApp,this._overrideTestConfigId=(c=s.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=s.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?$s(n.browser,n.saucelabs,n.browserstack):s.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get automationMode(){return"codeless"}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}getBrowserStackAppPath(e){var t;return this.isAppFromDevice?null:e?e.browserStackAppId:(t=this._nativeApp)==null?void 0:t.browserStackAppId}getSauceLabsAppPath(e,t){var s,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(s=this._nativeApp)==null?void 0:s.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getHeadspinAppPath(e){var t;return this.isAppFromDevice?null:e?e.headSpinAppId:(t=this._nativeApp)==null?void 0:t.headSpinAppId}getTdcAppPath(e){var t;return this.isAppFromDevice?null:e?e.testimTdcAppId:(t=this._nativeApp)==null?void 0:t.testimTdcAppId}get androidActivityWait(){var n;let e=this._nativeApp&&"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if((n=e==null?void 0:e.activity)!=null&&n.includes(e.id))return`${e.id}.*`;let{activity:t}=e;if(!t)return null;let s=t.split(".").pop();return t.replace(s,"*")}get isFFAllowAppFromDeviceEnabled(){return M.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return Us(this._nativeApp)}get isAppForIosVirtualDevice(){return Wr(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?to.FROM_DEVICE:to.FROM_LIBRARY}get nativeAppLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${me}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}async getNativeAppData(){let{appId:e,baseUrl:t}=this._options;if(t&&!this._nativeApp&&!e){let s=t||this.baseUrl;if(!s)return null;let[n,o]=s.split(":");return{packageName:n,activity:o}}return this._nativeApp&&!e?"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 overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var s,n;let t={tokenV3:await qt(),refreshToken:So(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Lp,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,onprem:this._options.company.onprem,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,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}};if(this._options.disableMockNetwork&&pt("user-disable-mock"),t.lightweightMode&&((s=this._options.lightweightMode)!=null&&s.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Jg(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),we.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):we.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Zg} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await nn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return we.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 o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Jg(e))return;let s=async()=>{try{return await Xc(this._options.project,this._testId,this._testResultId,e)}catch(i){return we.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await s();return await this._testRunStatus.waitForExecutionStartedFinished(),Jc(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?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)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){D("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},s=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&s.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{D("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};D("before Runtime.evaluate"),await(0,Xg.default)(async()=>{let{result:p}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!p.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),D("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return D("after Runtime.evaluate"),l.value}catch(i){throw we.error("error running test using CDP",{err:i}),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 s;try{s=new Qg.URL(e)}catch{return}let{username:n,password:o}=s;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let s=!1,n=o=>{if(!s){if(this.isRetryKeyMismatch(o)){we.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(we.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),s=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:p}}=this;try{let d=await br(a,c,p,l);n(d),s||setTimeout(i,3e3)}catch(d){we.error("failed to check if done",{err:d}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:s},branch:n}=this;try{let o=await br(e,t,s,n),i=["running","completed"];if(i.includes(o.status))return we.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw we.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(We.TEST_START_TIMEOUT_MSG)}catch(o){throw we.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(We.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await kt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(s=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){we.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),s(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||kt.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){we.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,s(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Yg.debounce(async()=>{try{let i=await br(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(we.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(we.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,s(i),!0):!1}catch(i){return we.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)kt.on("socket-connected",async()=>{try{await kt.joinToTestResult(this._testResultId,this.testId)}catch(i){we.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Bc(this._testResultId,this._options.project,this.retryKey);a?await e()||(we.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){we.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&kt.off("socket-connected",e)}}listenToRemoteStep(e){ps.listenToRemoteStep(this.testResultId,t=>{Ug(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:NE;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,s;return Boolean((s=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:s.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=te(),!((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 Ai,th=T(()=>{"use strict";eh();Ai=class{constructor(e,t,s,n,o,i){this._waitingTests=s.map(a=>new xi(e,t,a,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var FE,UE,In,Iu=T(()=>{"use strict";ss();$();FE=A("worker-utils"),UE=async(r,e,t)=>{e&&await Ll(r,t)},In=async(r,e,t,s)=>{FE.info("releasing player",{hasPlayer:Boolean(s)});try{await(s==null?void 0:s.onDone())}finally{await UE(r,e,t)}}});function GE(r,e,t,s){return{testId:r,reason:s,name:e,resultId:t,success:!1}}var Ci,oh,ih,Au,ht,rh,sh,nh,xn,jE,xu,BE,sr,$E,Pi,WE,VE,HE,st,An=T(()=>{"use strict";Ci=E(require("ms")),oh=E(require("lodash")),ih=E(require("moment")),Au=E(require("p-retry"));B();Ue();ss();be();$();Iu();Ct();qo();he();Ri();Ii();He();ce();z();ht=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:rh,TEST_START_TIMEOUT_MSG:sh,TEST_COMPLETE_TIMEOUT_MSG:nh}=We,{SETUP_TIMEOUT:xn,NETWORK_ERROR:jE,GRID_ERROR:xu,BROWSER_CLOSED:BE,SELENIUM_ERROR:sr,UNKNOWN_ERROR:$E,MOBILE_SESSION_ERROR:Pi}=Ms,WE=(0,Ci.default)("1s"),VE=1;HE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],st=class{constructor(e,t,s,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=s;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=st.getWorkerId();this.lambdatestService=new oe;this.isCodeMode=t.files&&t.files.length>0,this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return VE++}async getGridSlot(e,t){let s=await af(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,s),s}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return J.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Cs(!0)}async getBrowserOnce(e,t,s,n){throw new Cs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),ht.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Ke({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice,s=e.isAppForIosVirtualDevice;if(t||s){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:s}};return this.onTestIgnored(this.id,o),o}}setSessionTimeout(){var e;return this.options.mode===Q.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===N.BROWSERSTACK?Math.max((0,Ci.default)("600s"),this.options.getSessionTimeout):Math.max((0,Ci.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let s=(o=this.userData)==null?void 0:o.projectId,n;try{D("before getSlotOnce retries");let i=0,a=await(0,Au.default)(async()=>{let p=Date.now();try{return await ie(this.getSlotOnce(e),this.options.getBrowserTimeout,We.GET_BROWSER_TIMEOUT_MSG)}catch(d){let m={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw d instanceof Nr?ht.info("could not get grid slot due to concurrency issue",m):ht.error("error getting grid slot",{error:d,...m}),i++,await se(this.options.getBrowserTimeout-(Date.now()-p)),d}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});D("after getSlotOnce retries"),D("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,Au.default)(async()=>{let p=Date.now(),d=this.initPlayer(e);try{a=await cf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let m=this.setSessionTimeout();D("before getBrowserOnce");let g=await ie(this.getBrowserOnce(e,t,d,a),m,We.GET_BROWSER_TIMEOUT_MSG);return D("after getBrowserOnce"),J.onGetBrowserSuccess(this.id,s),d||g}catch(m){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===Q.APPIUM?"device":"browser";throw ht.error(`error getting ${f} from grid`,{error:m,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),J.onGetBrowserFailure(this.id,s,++l),d.onDone(),!(m instanceof vt)&&this.options.mode!==Q.APPIUM&&await se(this.options.getBrowserTimeout-(Date.now()-p)),m}},{retries:c-1,minTimeout:0,factor:1}),D("after getBrowserOnce retries")}catch(i){throw await In(this.id,this.releaseSlotOnTestFinished,s,n),[vt,Mr].some(a=>i instanceof a)?i:i instanceof Et?new cr(i,xu):new cr(i,sr)}return n}async runTest(e,t,s){var p;D("inside runTest");let n=(p=this.userData)==null?void 0:p.projectId,o=this.handleQuarantine(e);if(o)return o;let i=js(this.options)&&this.handleMobileTest(e);if(i)return i;D("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,l)}finally{await In(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var m,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var L,F;if(Ke(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice)return e();let v=h.sessionId,S=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof cr,w=y&&(S(sh)||S(nh)),O=M.flags.retryOnSeleniumHubError.isEnabled()&&!!f.reason&&h.isSeleniumHubNoMatchSessionError(f.reason)&&!h.ignoreSeleniumHubError,j=w&&h.hasMoreTimeoutRetries(),R=h.hasMoreRetries()&&!b&&!w,I=!f.success&&(R||j||O);try{let G=h.retryKey;f.testRetryKey=G;let Y=h.getAppSource;if(await this.onTestCompleted(this.id,this.testId,f,v,I,Y),this.executionQueue.hasMoreTests()&&!((L=this.options.lightweightMode)!=null&&L.general)&&await se(WE),await this.runTestCleanup(),I){if(j&&await h.startNewTimeoutRetry(),O){ht.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:h.testId,retryReason:f.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let X=(F=this.options.projectData)==null?void 0:F.projectId,de=h.testResultId,yt=h.testId;await Po(X,de,yt,{show:!1}),h.decreaseSeleniumHubRetry(),h.decreaseRetryCount(),await h.startNewRetry()}return R&&!O&&!j&&await h.startNewRetry(),ht.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:w,testRetryKey:G,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await p(h,I)}return await e()}catch(G){if(G instanceof $t)return;ht.error("failed to process test result",{error:G}),e();return}},s=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
217
|
-
Please make sure the CLI has stable access to the internet. ${
|
|
218
|
-
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:sr,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(f.message)?{errorType:sr,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(f.message)?{errorType:sr,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(f.message)?{errorType:sr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:$E,reason:v}},i=async(f,h)=>{var w;let y=await Ya();!y&&M.flags.warnOnBadNetwork.isEnabled()&&console.warn(s()),ht.warn("error on run",{err:f});let v=(w=this.userData)==null?void 0:w.projectId,{errorType:S,reason:b}=this.options.mode===Q.APPIUM?n(f):o(f,y);Po(v,this.testResultId,this.testId,{status:Ds.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:h.retryKey,setupStepResult:{status:Ds.COMPLETED,success:!1,reason:b,errorType:S}},h.remoteRunId),await t(GE(this.testId,this.testName,this.testResultId,b),h,f)},a=async(f,h)=>{var w;let y=this.testId,v=this.testResultId,S=(w=this.userData)==null?void 0:w.projectId,b=this.branch;if(!y||!v||!S||!b)return ht.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let x=await br(y,v,S,b);if(ht.warn("Test failed. Got results via API",{err:f,testResult:oh.default.omit(x,HE)}),x&&x.status===Ds.COMPLETED)return await t(x,h);throw f}catch(x){return x!==f&&ht.error("Failed to fetch test results from server",{testId:y,resultId:v,projectId:S,branch:b,err:x}),i(f,h)}},c=this.options.disableSockets||((m=this.options.lightweightMode)==null?void 0:m.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),p=async(f,h)=>{try{await Promise.all([!l&&ps.joinToRemoteStep(this.testResultId),!c&&kt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Q.APPIUM&&f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),v=await t(y,f);return D("After onRunComplete"),v}catch(y){return a(y,f)}finally{l||ps.unlistenToRemoteStep(this.testResultId)}},d=this.executionQueue.getNext();return d?(this.testId=d.testId,this.testName=d.testName,this.testResultId=d.testResultId,this.overrideTestConfigId=d.overrideTestConfigId,this.testRunConfig=d.runConfig,this.branch=d.branch,p(d)):this.onQueueCompleted()}}});var Pu,ah,ds,Cu=T(()=>{"use strict";B();Pu=E(require("p-retry"));B();$();z();ah=A("window-utils"),ds=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function s(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(s,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(s){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:s.x,top:s.y,behavior:"instant"}):window.scrollTo(s.x,s.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 s=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return ah.warn("selenium navigation failed. retrying to navigate",{err:o}),await se(1500),s(n-1);throw!o.seleniumStack&&i&&ah.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([s(),se(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),se(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 s=document.body,n=document.documentElement,o=Math.max(s.scrollHeight,s.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(s.scrollWidth,s.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await se(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 s;if(typeof location<"u")s=location;else if(typeof window<"u"&&typeof window.location<"u")s=window.location;else return!1;return s.href!=="chrome-error://chromewebdata/"&&s.href!=="safari-resource:/ErrorPage.html"&&s.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&s.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new vt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Pu.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Pu.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var ku,ms,Ou=T(()=>{"use strict";$();ku=A("cookies-utils"),ms=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(s){throw ku.error("failed to set cookie",{err:s}),s}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw ku.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw ku.error("failed to remove cookie",{err:t}),t}}}});var _u,ki,ch=T(()=>{"use strict";_u=E(require("p-retry")),ki=class{constructor(e,t,s={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=s;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,s=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([s,this.driver.takeScreenshot()]),[o,i]=await(0,_u.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,s=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,_u.default)(o,{retries:t,minTimeout:s,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}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 lh(r,e){let t=e.image||e,s=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 o=r.offset||{top:0,left:0};if(o.top*=s,o.left*=s,!r.elementRect)return qE.warn("missing elementRect",ph.omit(r,"image")),{};let{elementRect:i}=r,a=await fs.default.read(Buffer.from(n[1],"base64")),c=i.left*s+o.left*s,l=i.top*s+o.top*s,p=i.width*s,d=i.height*s;c<0&&(p+=c,p=p<0?0:p,c=0),l<0&&(d+=l,d=d<0?0:d,l=0);let m=a.bitmap.width,g=a.bitmap.height;if(c+p>m&&(p=m-c),l+d>g&&(d=g-l),d<=0||p<=0)throw new Lu("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,p,d).getBase64Async(fs.default.MIME_PNG)}}async function zE(r,e){let t=await fs.default.read(r.width,r.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await fs.default.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,l=>{if(l){c(l);return}a()})})}return await t.getBase64Async(fs.default.MIME_PNG)}function KE(r,e){return zE(r,e)}async function JE(){}async function YE(r){function e(o){let i=r[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await JE(r[o]);return{key:o,url:i}}let s=await ae(Object.keys(r).filter(e),t),n=Object.fromEntries(s.map(o=>[o.key,o.url]));return Object.assign(r,n)}function uh(r,e){return e||=1,r||={left:0,top:0,width:0,height:0},{left:e*Math.round(r.left),top:e*Math.round(r.top),width:e*Math.round(r.width),height:e*Math.round(r.height),pixelRatio:e}}var ph,fs,qE,Lu,Oi,dh=T(()=>{"use strict";ph=E(require("lodash"));B();fs=E(require("jimp"));$();qE=A("image-capture-utils"),Lu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Oi=class{constructor(e,t,s){this.windowUtils=t;this.screenshotUtils=s}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(),s=await lh(e,t);return Object.assign(s,{screenImage:t.image,absoluteScreenHighlight:uh(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return YE({screenImage:t.image,absoluteScreenHighlight:uh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:s}=this,n=()=>se(250),o=Boolean(e);async function i(m,g){o?await t.scrollToPositionWithoutAnimation(m):await t.scrollToPosition(m),await n();let f=await s.takeScreenshot(),h=await lh({elementRect:g},f);return{position:{left:m.x+g.left,top:m.y+g.top},size:{width:g.width,height:g.height},image:h.elementImage}}async function a(m){let g=[];for(let f of m){let h=await i(f.scrollPos,f.cropData);g.push(h)}return g}function c(m,g){let f=Math.max(m.width,g.width),h=g.width,y=Math.max(m.height,g.height),v=g.height,S=Array.from({length:Math.ceil(f/h)},(w,x)=>({scrollX:Math.min(x*h,f-h),cropX:x*h-Math.min(x*h,f-h),cropW:h-(x*h-Math.min(x*h,f-h))})),b=Array.from({length:Math.ceil(y/v)},(w,x)=>({scrollY:Math.min(x*v,y-v),cropY:x*v-Math.min(x*v,y-v),cropH:v-(x*v-Math.min(x*v,y-v))}));return S.flatMap(w=>b.map(x=>({scrollPos:{x:w.scrollX,y:x.scrollY},cropData:{top:x.cropY,left:w.cropX,width:w.cropW,height:x.cropH}})))}async function l(m,g){let f=await t.getCurrentScrollPosition(),h=c(m,g),y=await a(h);return await t.scrollToPosition(f),KE(m,y)}let[p,d]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(p,d)}}});var mh,fh,_i,Li,gh=T(()=>{"use strict";mh=E(require("p-retry")),fh=E(require("semver"));B();$();Cu();ch();dh();Te();_i=A("tab-service"),Li=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(s=>!t[s].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(s=>{let n=this.getTabInfo(e,s);return`tabId=${s}, 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,s,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),_i.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${s}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,s,n)}addOpenerStepId(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s}addOpenerStep(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=s.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let s=this.getAllTabInfos(e);Object.keys(s).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,s,n,o={}){let i=await this.getTabDetails(t,e,o),a=te();function c(l){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!l.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:s,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,s,n,o={}){let i=await this.buildTabInfo(e,t,s,n,o),a=new ds(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Oi(t,a,new ki(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let s=this.sessionTabs[e].tabInfos[t];return this._utils[s.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(s=>this._utils[s].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 s=this.getAllTabInfos(e),n=Object.keys(s).map(i=>s[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,s){let n=s.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,s,n){let{urlUtils:o}=ee(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),l=n(a),p=s.map(d=>o.urlBreaker(d)).map(d=>n(d)).filter(d=>d===c);return c===l&&p.length===1}isSameTab(e,t,s){let{tabMatcher:n}=ee();if(n){let l=this.getAllTabInfos(e),p=Object.keys(l).map(d=>l[d]);return n.isSameTab(p,t,s)}if(t.isMain&&s.isMain||t.openerStepId&&s.openerStepId&&t.openerStepId===s.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(l=>o[l].url);if(this.exactUrlMatch(t,s,i))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,s,i,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,s,i,c)||t.order===s.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(s=>t[s]).find(s=>s.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(s=>t[s].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(s=>this.removeTabInfo(e,s))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(s=>!t[s].isMain).forEach(s=>this.removeTabInfo(e,s)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:s=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||s)return this.driver.switchTab(e)}async getTabDetails(e,t,s={}){try{if(await this.switchTab(e,t,s),s.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");s.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){_i.error("failed to get url or title",{err:o})}}catch(n){_i.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(s=>!this.getAllTabIds(e).includes(s))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await se(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 s=this.getAllTabInfos(e);if(Object.keys(s).find(i=>s[i].openerStepId===t))return;if(this.pendingTabs[e]){_i.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,mh.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=fh.lt(e._version||e.version,"1.2.0"),s=!!e.parameterValues,n=s&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!s||n)}async getTabIdByTabInfo(e,t){var a,c;let{tabMatcher:s,commonConstants:n}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((a=t.useCurrentTab)!=null&&a.call(t)){let l=await this.driver.getCurrentTabId();if(l)return l;let p=this.getMainTabId(e);if(p)return p;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o);let i;if(s){let l=this.getAllTabIds(e).map(p=>Object.assign({},this.getTabInfo(e,p),{tabId:p})).filter(p=>!p.isClosed);i=s.matchTabs(t,l)}else{let l=t.tabInfo;l?i=this.getAllTabIds(e).find(p=>{let d=this.getTabInfo(e,p);return this.isSameTab(e,d,l)}):i=this.getMainTabId(e)}if(!i)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===i)return i;try{return await this.switchTab(i,e),Object.assign(this.sessionTabs[e],{currentTab:i}),i}catch(l){let p=["no such window","no window found","the window could not be found"];if(l.message&&p.some(d=>l.message.toLowerCase().includes(d)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[i].isClosed=!0,this.getTabIdByTabInfo(e,t);throw l}}}});var Du,Di,Mu=T(()=>{"use strict";Du=class{select(){return console.log(`
|
|
215
|
+
`,p=[],g=new vg.Worker(m,{eval:!0});try{return await ae(new Promise(f=>{g.on("message",h=>{if(h.action==="finish"){let{data:y}=h,v=Object.assign({},y,{tstConsoleLogs:p});mt.debug("Run code worker response",{messageWithLogs:v,transactionId:s}),f(v)}else h.action==="progress"&&p.push(h.data)}).on("error",h=>{h.message==="malformed data: URI"?mt.error("Run code worker error",{err:h,transactionId:s,fileDataUrl:i}):mt.error("Run code worker error",{err:h,transactionId:s}),f({tstConsoleLogs:p,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{mt.debug("Run code worker has been terminated",{transactionId:s})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(f){if(!(f instanceof re))throw f;return mt.warn("timeout to run code",{transactionId:s,err:f}),{tstConsoleLogs:p,status:"failed",result:{resultValue:f==null?void 0:f.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{g==null||g.terminate()}}async function oE(s){try{await bg.promises.rm(s,{recursive:!0,force:!0})}catch(e){mt.warn("failed to remove install npm packages folder",{err:e})}}function Eg(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function as(s,e,t,r,n,o){let i=Eg(n,e,s,t),{data:a}=await iE(i,r,o);return a}async function cs(s,e,t,r,n,o,i,a,c,l){var f;let d=Object.fromEntries(((f=t.nodePackageParams)==null?void 0:f.map(h=>[h.paramName,h.testimPackageLocalLocation]))||[]),m=Eg(i,n,e,o);if(l){let h=await Xs(l);h&&(c=h)}Buffer.isBuffer(c)&&(mt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let p="data:,";c==="data:"&&(mt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=p);let g=await nE(m,t,r,s,d,a,c);return Object.assign({},g,{nodeVersion:process.version})}async function iE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Sg(),o=Tn.join(n,`/${s}`),i=global.proxyUri;async function a(){let c="";try{if(c=await xd(o,r,i,t),mt.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(d=>{let m=Id(o,d.packageName);return{...d,packageFullName:`${d.packageName}@${m}`,packageLocalLocation:Tn.resolve(o,"node_modules",d.packageName)}}),installFolder:o}}catch(l){throw mt.warn("npm package install failed",{transactionId:s,err:l}),l}}try{return await ae(a(),t)}catch(c){throw c instanceof re&&mt.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Sg(){return Tn.join(Tg.tmpdir(),"/testim_local_packages")}function Rg(){let s=Sg();return oE(s)}var bg,Tg,Tn,wg,vg,mt,Rr=T(()=>{"use strict";bg=E(require("fs")),Tg=E(require("os")),Tn=E(require("path"));j();Vs();wg=E(require("data-uri-to-buffer")),vg=require("worker_threads");z();B();ye();mt=x("cli-service")});var sr={};G(sr,{run:()=>cE});function aE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=U.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var cE,Ig=T(()=>{"use strict";Rr();z();Te();cE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:d,fileDataUrl:m,s3filepath:p}=e.data;try{let g=await cs(r,n,o,i,a,c,l,d,m,p);return g&&aE({result:g.result,tstConsoleLogs:g.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:g,success:!0}}catch(g){throw g instanceof re?new Error("Timeout while running action"):g}}});var lu={};G(lu,{run:()=>lE});var lE,xg=T(()=>{"use strict";Rr();z();lE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await as(t,r,n,i,o,a),success:!0}}catch(c){if(c instanceof wt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof re)return{success:!1,code:"timeout"};throw c}}});async function Pg(s,e,t,r){try{return await Gc(s,e,t,r)}catch{hi.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function pE(s,e,t,r,n){return hi.info("finished to run remote step",{stepId:t,sessionId:n}),await Pg(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Ag(s,e,t,r,n){return hi.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Pg(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Cg(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o}=s,i=t.type,a=e.getSessionId(),c=t.id;hi.info("start play remote step",{stepType:i,stepId:c,sessionId:a});let l=uE[i];if(!l)return await Ag(n,r,c,`Failed to find step type ${i}`,a);try{let d=await l.run(e,t,o);return await pE(n,r,c,d,a)}catch(d){return await Ag(n,r,c,d.message,a)}}var hi,uE,kg=T(()=>{"use strict";Ig();ye();xg();B();hi=x("step-playback"),uE={"cli-validation-code-step":sr,"cli-wait-for-code-step":sr,"cli-action-code-step":sr,"cli-api-code-step":sr,"cli-condition-step":sr,"cli-download-code-step":sr,"node-package":lu}});var uu,Og,Ir,mE,pu,ft,yi=T(()=>{"use strict";j();Rt();uu=E(require("ws")),Og=require("events");B();le();Ir=x("socket-ng-service"),mE=5e3,pu=class extends Og.EventEmitter{constructor(){super(...arguments);this.clientId=te();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Ir.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),mE)}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){Ir.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(Tp);return Kt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new uu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Ir.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Ir.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===uu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Ir.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){Ir.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Ir.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let o=i=>{r(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,r,n,o){function i(c){n(c)&&o(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=i.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,o=!1){return new Promise(i=>{let a=te(),c={query:r,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",l=>l.id===a,i),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(r)?r:[r];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},ft=new pu});var Lg,du,fE,gE,hE,_g,bi,us,mu=T(()=>{"use strict";Lg=E(require("p-retry")),du=E(require("socket.io-client"));le();j();B();fE=50,gE=10,hE=5e3,_g=10*1e3,bi=x("base socket service"),us=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);bi.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{}bi.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===gE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=fE)throw new Error(`Can't connect to Testim Servers.
|
|
216
|
+
Action required: Please allow opening a websockets connection to ${me} 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",()=>{bi.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:_g,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=`${me}/${t}`,this._socket=du.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:_g,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=`${me}/${t}`,this._socket=du.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Lg.default)(()=>ae(n(),hE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&bi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Dg={};G(Dg,{remoteStepServiceSocketIO:()=>yE});var fu,yE,Mg=T(()=>{"use strict";mu();fu=class extends us{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}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.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},yE=new fu});var Ng={};G(Ng,{remoteStepService:()=>ps});var gu,wn,hu,ps,Ti=T(()=>{"use strict";yi();ce();Te();({REMOTE_STEP_SAVED:gu}=St),hu=class{async init(e){U.flags.useNewWSCLI.isEnabled()||(wn=(await Promise.resolve().then(()=>(Mg(),Dg))).remoteStepServiceSocketIO,wn.init(e))}joinToRemoteStep(e){return U.flags.useNewWSCLI.isEnabled()?ft.addFilter(`${e}:remoteStep`,{resultId:e},[gu]):wn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(U.flags.useNewWSCLI.isEnabled()){ft.listenTo(`${e}:remoteStep`,[gu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}wn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return U.flags.useNewWSCLI.isEnabled()?(ft.removeFilter(`${e}:remoteStep`,[gu]),Promise.resolve()):wn.unlistenToRemoteStep(e)}},ps=new hu});var yu,xr,Ug=T(()=>{"use strict";mu();yu=class extends us{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,r,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[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.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},xr=new yu});var Bg={};G(Bg,{testResultService:()=>Ct});var Fg,bu,Ct,wi=T(()=>{"use strict";Fg=require("events");yi();ce();Te();Ug();bu=class extends Fg.EventEmitter{init(e){if(U.flags.useNewWSCLI.isEnabled()){ft.onConnect=()=>this.emit("socket-connected");return}xr.init(e),xr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return U.flags.useNewWSCLI.isEnabled()?ft.addFilter(`${e}:testResult`,{resultId:e,testId:t},[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED]):xr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(U.flags.useNewWSCLI.isEnabled()){ft.removeFilter(`${e}:testResult`,[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED]);return}await xr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(U.flags.useNewWSCLI.isEnabled()){ft.listenTo(`${e}:testResult`,[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}xr.listenToTestResult(e,t,r)}getSocket(){if(!U.flags.useNewWSCLI.isEnabled())return xr.getSocket()}},Ct=new bu});var $g,Wg,Gg,we,bE,Vg,jg,vi,Hg=T(()=>{"use strict";$g=E(require("lodash"));j();le();Fe();Xr();Rt();ye();kg();Wg=E(require("p-retry")),Gg=require("url");B();Mo();ss();ce();Ti();wi();Te();we=x("test-run-handler"),bE=3,Vg=20*1e3,jg=s=>JSON.stringify(s).length<Vg,vi=class{constructor(e,t,r,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Bt;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;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._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?$s(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}getBrowserStackAppPath(e){var t;return this.isAppFromDevice?null:e?e.browserStackAppId:(t=this._nativeApp)==null?void 0:t.browserStackAppId}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}getHeadspinAppPath(e){var t;return this.isAppFromDevice?null:e?e.headSpinAppId:(t=this._nativeApp)==null?void 0:t.headSpinAppId}getTdcAppPath(e){var t;return this.isAppFromDevice?null:e?e.testimTdcAppId:(t=this._nativeApp)==null?void 0:t.testimTdcAppId}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 isFFAllowAppFromDeviceEnabled(){return U.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return Fs(this._nativeApp)}get isAppForIosVirtualDevice(){return $r(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Zn.FROM_DEVICE:Zn.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${me}/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 overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Kt(),refreshToken:wo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:xp,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,onprem:this._options.company.onprem,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,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}};if(this._options.disableMockNetwork&<("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=jg(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),we.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):we.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Vg} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await nn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return we.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 o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&jg(e))return;let r=async()=>{try{return await Vc(this._options.project,this._testId,this._testResultId,e)}catch(i){return we.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Wc(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?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)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){L("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&r.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{L("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};L("before Runtime.evaluate"),await(0,Wg.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),L("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return L("after Runtime.evaluate"),l.value}catch(i){throw we.error("error running test using CDP",{err:i}),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 Gg.URL(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){we.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(we.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:d}}=this;try{let m=await br(a,c,d,l);n(m),r||setTimeout(i,3e3)}catch(m){we.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Ct.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await br(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return we.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw we.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error($e.TEST_START_TIMEOUT_MSG)}catch(o){throw we.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error($e.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Ct.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){we.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Ct.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){we.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=$g.debounce(async()=>{try{let i=await br(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(we.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(we.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return we.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Ct.on("socket-connected",async()=>{try{await Ct.joinToTestResult(this._testResultId,this.testId)}catch(i){we.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await _c(this._testResultId,this._options.project,this.retryKey);a?await e()||(we.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){we.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Ct.off("socket-connected",e)}}listenToRemoteStep(e){ps.listenToRemoteStep(this.testResultId,t=>{Cg(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:bE;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=te(),!((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 Ei,qg=T(()=>{"use strict";Hg();Ei=class{constructor(e,t,r,n,o,i){this._waitingTests=r.map(a=>new vi(e,t,a,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var TE,wE,vn,Tu=T(()=>{"use strict";ts();B();TE=x("worker-utils"),wE=async(s,e,t)=>{e&&await Pl(s,t)},vn=async(s,e,t,r)=>{TE.info("releasing player",{hasPlayer:Boolean(r)});try{await(r==null?void 0:r.onDone())}finally{await wE(s,e,t)}}});function xE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Ri,Yg,Xg,vu,gt,zg,Kg,Jg,En,vE,wu,EE,nr,SE,Si,RE,IE,AE,tt,Sn=T(()=>{"use strict";Ri=E(require("ms")),Yg=E(require("lodash")),Xg=E(require("moment")),vu=E(require("p-retry"));j();Fe();ts();ye();B();Tu();At();$o();Te();Ti();wi();Ve();ce();z();gt=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:zg,TEST_START_TIMEOUT_MSG:Kg,TEST_COMPLETE_TIMEOUT_MSG:Jg}=$e,{SETUP_TIMEOUT:En,NETWORK_ERROR:vE,GRID_ERROR:wu,BROWSER_CLOSED:EE,SELENIUM_ERROR:nr,UNKNOWN_ERROR:SE,MOBILE_SESSION_ERROR:Si}=Ms,RE=(0,Ri.default)("1s"),IE=1;AE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],tt=class{constructor(e,t,r,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=tt.getWorkerId();this.lambdatestService=new ne;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return IE++}async getGridSlot(e,t){let r=await rf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return X.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Cs(!0)}async getBrowserOnce(e,t,r,n){throw new Cs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),gt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!ze({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}setSessionTimeout(){var e;return this.options.mode===Y.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===N.BROWSERSTACK?Math.max((0,Ri.default)("600s"),this.options.getSessionTimeout):Math.max((0,Ri.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{L("before getSlotOnce retries");let i=0,a=await(0,vu.default)(async()=>{let d=Date.now();try{return await ae(this.getSlotOnce(e),this.options.getBrowserTimeout,$e.GET_BROWSER_TIMEOUT_MSG)}catch(m){let p={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw m instanceof Mr?gt.info("could not get grid slot due to concurrency issue",p):gt.error("error getting grid slot",{error:m,...p}),i++,await oe(this.options.getBrowserTimeout-(Date.now()-d)),m}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});L("after getSlotOnce retries"),L("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,vu.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{a=await sf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let p=this.setSessionTimeout();L("before getBrowserOnce");let g=await ae(this.getBrowserOnce(e,t,m,a),p,$e.GET_BROWSER_TIMEOUT_MSG);return L("after getBrowserOnce"),X.onGetBrowserSuccess(this.id,r),m||g}catch(p){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===Y.APPIUM?"device":"browser";throw gt.error(`error getting ${f} from grid`,{error:p,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),X.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(p instanceof bt)&&this.options.mode!==Y.APPIUM&&await oe(this.options.getBrowserTimeout-(Date.now()-d)),p}},{retries:c-1,minTimeout:0,factor:1}),L("after getBrowserOnce retries")}catch(i){throw await vn(this.id,this.releaseSlotOnTestFinished,r,n),[bt,Dr].some(a=>i instanceof a)?i:i instanceof Tt?new lr(i,wu):new lr(i,nr)}return n}async runTest(e,t,r){var d;L("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Bs(this.options)&&this.handleMobileTest(e);if(i)return i;L("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,l)}finally{await vn(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var p,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var D,$;if(ze(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice)return e();let v=h.sessionId,S=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof lr,w=y&&(S(Kg)||S(Jg)),k=U.flags.retryOnSeleniumHubError.isEnabled()&&!!f.reason&&h.isSeleniumHubNoMatchSessionError(f.reason)&&!h.ignoreSeleniumHubError,R=w&&h.hasMoreTimeoutRetries(),M=h.hasMoreRetries()&&!b&&!w,O=!f.success&&(M||R||k);try{let V=h.retryKey;f.testRetryKey=V;let J=h.getAppSource;if(await this.onTestCompleted(this.id,this.testId,f,v,O,J),this.executionQueue.hasMoreTests()&&!((D=this.options.lightweightMode)!=null&&D.general)&&await oe(RE),await this.runTestCleanup(),O){if(R&&await h.startNewTimeoutRetry(),k){gt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:h.testId,retryReason:f.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let Q=($=this.options.projectData)==null?void 0:$.projectId,de=h.testResultId,$t=h.testId;await Io(Q,de,$t,{show:!1}),h.decreaseSeleniumHubRetry(),h.decreaseRetryCount(),await h.startNewRetry()}return M&&!k&&!R&&await h.startNewRetry(),gt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:w,testRetryKey:V,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await d(h,O)}return await e()}catch(V){if(V instanceof Gt)return;gt.error("failed to process test result",{error:V}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
217
|
+
Please make sure the CLI has stable access to the internet. ${Ga()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:v,TIMEOUT_ERROR:S,SAUCELABS_APP_IS_NOT_INSTALLED:b}=Ya,w=f instanceof Error?f.message:f;return w.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),w.includes(zg)||w.includes(S)?{errorType:En,reason:"timeout while getting device"}:w.includes(y)||w.includes(b)?{errorType:Si,reason:"app doesn't exist on device"}:w.includes(v)?{errorType:Si,reason:"app never started, check app permission or app activity"}:w.includes(h)?{errorType:Si,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Si,reason:w}},o=(f,h)=>{let y=this.options.mode===Y.APPIUM?"device":"browser";if(!h&&U.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:vE,reason:r()};let v=f instanceof Error?f.message:f;if(v.includes(zg))return{errorType:En,reason:`Test couldn't get ${y}`};if(v.includes(Kg))return{errorType:En,reason:"Test couldn't be started"};if(v.includes(Jg)){if(!this.testRunTimeout)return{errorType:En,reason:"Test timeout reached: test is too long"};let S=Xg.default.duration(this.testRunTimeout,"milliseconds"),b=Math.floor(S.asMinutes()),w=S.seconds(),I=b>0?` ${b} min`:"",C=w>0?` ${w} sec`:"";return{errorType:En,reason:`Test timeout reached (timeout:${I}${C}): test is too long`}}if(f instanceof lr&&f.type){if(f.type===wu)return{errorType:wu,reason:`Test couldn't get ${y} from grid - ${f.message}`};if(f.type===nr)return{errorType:nr,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===EE?{errorType:nr,reason:`Session terminated, this is often caused to connection
|
|
218
|
+
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:nr,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(f.message)?{errorType:nr,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(f.message)?{errorType:nr,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(f.message)?{errorType:nr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:SE,reason:v}},i=async(f,h)=>{var w;let y=await Wa();!y&&U.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),gt.warn("error on run",{err:f});let v=(w=this.userData)==null?void 0:w.projectId,{errorType:S,reason:b}=this.options.mode===Y.APPIUM?n(f):o(f,y);Io(v,this.testResultId,this.testId,{status:Ds.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:h.retryKey,setupStepResult:{status:Ds.COMPLETED,success:!1,reason:b,errorType:S}},h.remoteRunId),await t(xE(this.testId,this.testName,this.testResultId,b),h,f)},a=async(f,h)=>{var w;let y=this.testId,v=this.testResultId,S=(w=this.userData)==null?void 0:w.projectId,b=this.branch;if(!y||!v||!S||!b)return gt.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let I=await br(y,v,S,b);if(gt.warn("Test failed. Got results via API",{err:f,testResult:Yg.default.omit(I,AE)}),I&&I.status===Ds.COMPLETED)return await t(I,h);throw f}catch(I){return I!==f&>.error("Failed to fetch test results from server",{testId:y,resultId:v,projectId:S,branch:b,err:I}),i(f,h)}},c=this.options.disableSockets||((p=this.options.lightweightMode)==null?void 0:p.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),d=async(f,h)=>{try{await Promise.all([!l&&ps.joinToRemoteStep(this.testResultId),!c&&Ct.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Y.APPIUM&&f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),v=await t(y,f);return L("After onRunComplete"),v}catch(y){return a(y,f)}finally{l||ps.unlistenToRemoteStep(this.testResultId)}},m=this.executionQueue.getNext();return m?(this.testId=m.testId,this.testName=m.testName,this.testResultId=m.testResultId,this.overrideTestConfigId=m.overrideTestConfigId,this.testRunConfig=m.runConfig,this.branch=m.branch,d(m)):this.onQueueCompleted()}}});var Eu,Qg,ds,Su=T(()=>{"use strict";j();Eu=E(require("p-retry"));j();B();z();Qg=x("window-utils"),ds=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(o,i){let a=document.elementFromPoint(o,i);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(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return Qg.warn("selenium navigation failed. retrying to navigate",{err:o}),await oe(1500),r(n-1);throw!o.seleniumStack&&i&&Qg.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),oe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),oe(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,o=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await oe(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"&&typeof window.location<"u")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 bt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Eu.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Eu.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var Ru,ms,Iu=T(()=>{"use strict";B();Ru=x("cookies-utils"),ms=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 Ru.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Ru.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Ru.error("failed to remove cookie",{err:t}),t}}}});var xu,Ii,Zg=T(()=>{"use strict";xu=E(require("p-retry")),Ii=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()]),[o,i]=await(0,xu.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,xu.default)(o,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}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 eh(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 o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return PE.warn("missing elementRect",rh.omit(s,"image")),{};let{elementRect:i}=s,a=await fs.default.read(Buffer.from(n[1],"base64")),c=i.left*r+o.left*r,l=i.top*r+o.top*r,d=i.width*r,m=i.height*r;c<0&&(d+=c,d=d<0?0:d,c=0),l<0&&(m+=l,m=m<0?0:m,l=0);let p=a.bitmap.width,g=a.bitmap.height;if(c+d>p&&(d=p-c),l+m>g&&(m=g-l),m<=0||d<=0)throw new Au("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,d,m).getBase64Async(fs.default.MIME_PNG)}}async function CE(s,e){let t=await fs.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await fs.default.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,l=>{if(l){c(l);return}a()})})}return await t.getBase64Async(fs.default.MIME_PNG)}function kE(s,e){return CE(s,e)}async function OE(){}async function _E(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await OE(s[o]);return{key:o,url:i}}let r=await ie(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function th(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 rh,fs,PE,Au,xi,sh=T(()=>{"use strict";rh=E(require("lodash"));j();fs=E(require("jimp"));B();PE=x("image-capture-utils"),Au=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};xi=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 eh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:th(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 _E({screenImage:t.image,absoluteScreenHighlight:th(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=()=>oe(250),o=Boolean(e);async function i(p,g){o?await t.scrollToPositionWithoutAnimation(p):await t.scrollToPosition(p),await n();let f=await r.takeScreenshot(),h=await eh({elementRect:g},f);return{position:{left:p.x+g.left,top:p.y+g.top},size:{width:g.width,height:g.height},image:h.elementImage}}async function a(p){let g=[];for(let f of p){let h=await i(f.scrollPos,f.cropData);g.push(h)}return g}function c(p,g){let f=Math.max(p.width,g.width),h=g.width,y=Math.max(p.height,g.height),v=g.height,S=Array.from({length:Math.ceil(f/h)},(w,I)=>({scrollX:Math.min(I*h,f-h),cropX:I*h-Math.min(I*h,f-h),cropW:h-(I*h-Math.min(I*h,f-h))})),b=Array.from({length:Math.ceil(y/v)},(w,I)=>({scrollY:Math.min(I*v,y-v),cropY:I*v-Math.min(I*v,y-v),cropH:v-(I*v-Math.min(I*v,y-v))}));return S.flatMap(w=>b.map(I=>({scrollPos:{x:w.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:w.cropX,width:w.cropW,height:I.cropH}})))}async function l(p,g){let f=await t.getCurrentScrollPosition(),h=c(p,g),y=await a(h);return await t.scrollToPosition(f),kE(p,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var nh,oh,Ai,Pi,ih=T(()=>{"use strict";nh=E(require("p-retry")),oh=E(require("semver"));j();B();Su();Zg();sh();be();Ai=x("tab-service"),Pi=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),Ai.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,o={}){let i=await this.getTabDetails(t,e,o),a=te();function c(l){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!l.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new ds(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new xi(t,a,new Ii(t,this.driver,{takeScreenshots:o.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(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===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:o}=ee(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),l=n(a),d=r.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===c);return c===l&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=ee();if(n){let l=this.getAllTabInfos(e),d=Object.keys(l).map(m=>l[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(l=>o[l].url);if(this.exactUrlMatch(t,r,i))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,i,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Ai.error("failed to get url or title",{err:o})}}catch(n){Ai.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 oe(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(i=>r[i].openerStepId===t))return;if(this.pendingTabs[e]){Ai.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,nh.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=oh.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var a,c;let{tabMatcher:r,commonConstants:n}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((a=t.useCurrentTab)!=null&&a.call(t)){let l=await this.driver.getCurrentTabId();if(l)return l;let d=this.getMainTabId(e);if(d)return d;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o);let i;if(r){let l=this.getAllTabIds(e).map(d=>Object.assign({},this.getTabInfo(e,d),{tabId:d})).filter(d=>!d.isClosed);i=r.matchTabs(t,l)}else{let l=t.tabInfo;l?i=this.getAllTabIds(e).find(d=>{let m=this.getTabInfo(e,d);return this.isSameTab(e,m,l)}):i=this.getMainTabId(e)}if(!i)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===i)return i;try{return await this.switchTab(i,e),Object.assign(this.sessionTabs[e],{currentTab:i}),i}catch(l){let d=["no such window","no window found","the window could not be found"];if(l.message&&d.some(m=>l.message.toLowerCase().includes(m)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[i].isClosed=!0,this.getTabIdByTabInfo(e,t);throw l}}}});var Pu,Ci,Cu=T(()=>{"use strict";Pu=class{select(){return console.log(`
|
|
219
219
|
internal error - cant use port selector in selenium!!!!
|
|
220
|
-
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},
|
|
220
|
+
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Ci=new Pu});var gs,ku=T(()=>{"use strict";Iu();be();gs=class{constructor(e,t){this.driver=e;this._abortedSteps=[];this.cookieUtils=t||new ms(this.driver)}get sessionPlayerInit(){return ee()}getTimeStamp(){return Date.now()}getTestimId(e){if(!e)return;let{locatorBuilderUtils:t}=this.sessionPlayerInit,r=t.TESTIM_ID_FIELD_NAME;return t.isEmptyResult(e)?t.EMPTY_RESULT_ID:e.getAttribute(r)}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async restoreNativeAlerts(){}executeOverloadNativeAlertsInFrame(){}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,o=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-o.x,y:e.y-o.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=`return ${this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t)}`,{value:n}=await this.driver.executeJS(r);return n}}});function ch(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=ah(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,o){let{frameOffset:i,locatedElement:a}=r,{locatorBuilderUtils:c}=ee();if(c.isEmptyResult(a)){let p="got empty result in frame result, not rejected from locate element player";throw LE.error(p),new Error(p)}let l=await s.switchToLocatedFrame(a),d=ah(l.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:l.value,frameLocateResultUrl:m}}async locate(r,n,o,i,a,c){let l=new this.LocateElementPlayer(i);r.targetId=`frameLocator_${n}`;let d=await l.locate(r,o,r.targetId);d.isVisible=!0;let m=await l.handleLocateResult(d,c,r).catch(()=>{throw new Error("")}),{locatedElement:p}=i.data[r.targetId],f=(await s.getElementLocationWithPadding(p)).value||{top:0,left:0};m.frameOffset={top:o.frameOffset.top+f.top,left:o.frameOffset.left+f.left},l.addFrameDataToContext&&l.addFrameDataToContext(m.targetId,m.locateResult);let h=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=h,h}async findFrame(r,n,o,i){let a=U.flags.enableFrameSwitchOptimization.isEnabled(),l=o.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=l&&l.stepId===r.id&&l.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(v=>v.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let v=n.slice(y+1),S=0;for(let b of v)S++,this.currentFrameHandler=await this.locate(b,S,this.currentFrameHandler,o,i,r);return this.currentFrameHandler}}let p=await i.getTopFrameHandler();p.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===p?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=p;let f=0,h=p;for(let y of n)f++,h=await this.locate(y,f,h,o,i,r);return h}}return e}var LE,DE,ah,lh=T(()=>{"use strict";B();Te();be();Cr();LE=x("frame-locator"),DE="ELEMENT",ah=s=>s?s[DE]||s[Wt]:null});var ki,Ou=T(()=>{"use strict";le();ki=()=>{try{if(bp)return!1;if(require("inspector").url())return!0}catch{}return!1}});var W,ue=T(()=>{"use strict";be();W=class{constructor(e,t,r,n={},o=void 0,i=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=o;this.locateElementPlayer=i;this.exportsTest=a;this.frameId=0}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return ee()}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 NE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:U.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?U.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function UE(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 uh.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,o,i,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:d,positionUtils:m}=ee();if(NE(n,d,m,s))return s.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let f=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),h=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,f,!1,n),y;try{y=await s.execute(`return ${h}`)}catch(I){throw Ar.error("failed to execute getVisibilityCode",{err:I}),I}let{value:v}=y||{},S=v.elementVisibilityInfo||ME,[b,w]=v.elementsFromPointResults||[null,null];return d.checkElementVisibility(S,n,w,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=ee();await s.execute(r(t))}}}var uh,Ar,ME,Rn,ph=T(()=>{"use strict";ue();B();Te();be();uh=require("linkedom"),Ar=x("locate-step-action"),ME={opacity:1,clientRects:{}};Rn=class extends W{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return UE(e)}static getFrameIdByTestimFrameId(){throw Ar.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw Ar.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw Ar.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw Ar.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw Ar.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw Ar.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var dh={};G(dh,{scroll:()=>FE});var FE,mh=T(()=>{"use strict";FE=function(s,e,t,r,n,o,i,a){function c(S,b){if(!b)return{success:!1};elementScrollTo(b,S.x,S.y);let w=b.scrollLeft,I=b.scrollTop;return{success:Math.abs(I-S.y)<1&&Math.abs(w-S.x)<1,actualX:w,actualY:I}}function l(S,b){if(!t)return{x:n,y:o};let w=getLocatedElement(b);if(r&&!w)return{x:S.scrollWidth,y:S.scrollHeight};if(!w)throw new Error("could not find target element");let I=w.getBoundingClientRect(),C=0,k=0,R=Math.max(window.innerHeight-(I.height+10),0),M=Math.max(window.innerWidth-(I.width+10),0);return C=a?S.scrollTop+I.top-Math.min(o,R):S.scrollTop,k=i?S.scrollLeft+I.left-Math.min(n,M):S.scrollLeft,{x:Math.round(k),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 p={top:m.scrollTop,left:m.scrollLeft},g=l(m,e),f=c(g,m);d&&!document.scrollingElement&&!f.success&&p.top===m.scrollTop&&p.left===m.scrollLeft&&(m=document.body,g=l(m,e),f=c(g,m));let h=f.actualX,y=f.actualY,v=getLocatedElement(e);if(t&&r&&!v)return{success:!1,expectedPosition:g};if(t){if(!v)throw new Error("could not find target to scroll to");let S=v.getBoundingClientRect();h=S.left,y=S.top}return{success:f.success,actualX:h,actualY:y}}});var Oi,fh=T(()=>{"use strict";ue();Oi=class extends W{getFailureString(e,t,r,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${r}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:o}}=this.sessionPlayerInit,i=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(m,p,g){m.scrollTo(p,g)}:function(m,p,g){m.scrollTop=g,m.scrollLeft=p},{scroll:l}=await Promise.resolve().then(()=>(mh(),dh)),d=`
|
|
221
221
|
const getLocatedElement = ${n.getLocatedElementCode};
|
|
222
222
|
const elementScrollTo = ${c.toString()};
|
|
223
223
|
const scroll = ${l.toString()};
|
|
224
224
|
return scroll.apply(null, arguments)
|
|
225
|
-
`;try{let d=await this.driver.executeJS(p,s,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(d!=null&&d.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:m,actualX:g,actualY:f}=d.value;return m?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,g,f)}}}catch{return{errorType:o.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,s=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,s):this.scrollOnElement(t,s)}}});var Rh,Ih=T(()=>{"use strict";Rh=function(r){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 s={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(r.fromLocatedElement),o=getLocatedElement(r.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:s}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var xh,Ah=T(()=>{"use strict";xh=function(r,e){let t=typeof MouseEvent=="function",s=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(I){e({status:"done",result:I,success:!0})}function a(I){I||={},e({status:"failed",result:I,success:!1,keep:!0})}function c(I){return I!=null&&I.toLowerCase?(I=I.toLowerCase(),I==="text"?"text/plain":I==="url"?"text/uri-list":I):I}function l(){try{return new DataTransfer}catch{return{data:{},setData(L,F){o[c(L)]=F},getData(L){return o[c(L)]}}}}let p=["drag","dragstart","dragend"],d=["pointerup","pointerdown","pointermove"],m=p.concat(["drop","dragenter","dragover"]);function g(I){let L=I;for(;L&&L!==document.documentElement;){if(L.draggable)return L;L=L.parentElement}return null}function f(I,L,F){let G=L.element,{dispatchDragEventsOnClosestDraggable:Y}=F;if(p.includes(I.type)&&Y){if(!G&&L.lastDraggedElement)return L.lastDraggedElement;let X=g(G);if(X)return L.lastDraggedElement=X,X}return G}function h(I,L,F){function G(bt,Cr,C){return C>bt&&C<Cr}let Y=I.pointerPosition||{};if(L)return{x:Y.originX||0,y:Y.originY||0};let X=F.getBoundingClientRect(),de=Y.originX&&G(X.left,X.left+X.width,Y.originX)?Y.originX:X.left+X.width/2,yt=Y.originY&&G(X.top,X.top+X.height,Y.originY)?Y.originY:X.top+X.height/2;return{x:de,y:yt}}function y(I,L,F){let G=(L==null?void 0:L.modifiers)||{},Y=h(I,F.isDrag,F.element),X=(L==null?void 0:L.button)||0,de=I.event;return d.includes(de)?S(de,G,Y.x,Y.y,X):m.includes(de)?w(de,G,Y.x,Y.y):b(de,G,Y.x,Y.y,X)}function v(I,L,F){return{screenX:0,screenY:0,clientX:L,clientY:F,ctrlKey:Boolean(I.ctrl),altKey:Boolean(I.alt),shiftKey:Boolean(I.shift),metaKey:Boolean(I.meta),bubbles:!0,cancelable:!0,composed:!0}}function S(I,L,F,G,Y){if(n){let de=v(L,F,G);return de.pointerType="mouse",de.isPrimary=!0,new window.PointerEvent(I,de)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(I,!0,!0,document.defaultView,1,0,0,F,G,Boolean(L.ctrl),Boolean(L.alt),Boolean(L.shift),Boolean(L.meta),Y,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(I,L,F,G,Y){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(I,!0,!0,document.defaultView,1,0,0,F,G,Boolean(L.ctrl),Boolean(L.alt),Boolean(L.shift),Boolean(L.meta),Y,document.body?document.body.parentNode:document.documentElement),X}function w(I,L,F,G){if(I==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!s){let de=document.createEvent("CustomEvent");return de.initCustomEvent(I,!0,!0,null),Object.assign(de,{dataTransfer:window.TSTA.dataTransfer}),de}let Y=v(L,F,G),X=new window.DragEvent(I,Y);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function x(I,L,F){let G=f(I,L,F);G==null||G.dispatchEvent(I)}function k(I,L){function F(){return I.event==="click"&&L.isDrag&&!L.allEventsOnSameElement}return F()}function O(I,L,F){if(F){let G=Math.min(F.timeStamp-L.timeStamp,40);setTimeout(()=>{j(I)},G)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function j(I){let L,F=I.events[I.eventIndex],G=I.events[++I.eventIndex];try{I.element=getLocatedElement(F.locatedElement),L=y(F,r,I)}catch(Y){return a(`exception in get event in drag step:${Y.message}`)}if(k(F,I))return O(I,F,G);if(L)try{x(L,I,F)}catch(Y){return a(`exception in executeEvent in drag step:${Y.message}`)}else return a(`cannot execute event ${F.event}`);O(I,F,G)}let R={eventIndex:0,allEventsOnSameElement:r.allEventsOnSameElement,events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement};setTimeout(()=>{try{j(R)}catch(I){a(I)}},0)}});var Ph={};W(Ph,{doClick:()=>nS});var nS,Ch=T(()=>{"use strict";nS=(r,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function s(b,w){var O;function x(j){function R(){return o(j).find(F=>[...F.classList||[]].includes("Select-control"))}function I(){let F=R();return F?F.querySelector("input"):null}let L=I();L==null||L.focus()}let k=(O=b.quirks)==null?void 0:O.isReactSelect;w.type==="mousedown"&&k&&x(b.element)}function n(b,w){var k;let x=(k=b.quirks)==null?void 0:k.isCKEditorFrame;w.type==="click"&&x&&document.body.focus()}function o(b){let w=[];for(;b!=null&&b.parentNode;)w.push(b),b=b.parentNode;return w}function i(b){let w={status:"done",result:b,success:!0,...S.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(w)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),b.dispatchEvent(w)}function l(b){let w={},x=b.getBoundingClientRect(),k=x.left+x.width/2,O=x.top+x.height/2,I=g("mousemove",w,k,O,0);b.dispatchEvent(I)}function p(b,w){function x(I,L,F){return F>I&&F<L}let k=b.pointerPosition||{},O=w.getBoundingClientRect(),j=k.originX&&x(O.left,O.left+O.width,k.originX)?k.originX:O.left+O.width/2,R=k.originY&&x(O.top,O.top+O.height,k.originY)?k.originY:O.top+O.height/2;return{x:j,y:R}}function d(b,w,x){return{screenX:0,screenY:0,clientX:w,clientY:x,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,w,x,k){if(!window.PointerEvent)return;let O=d(w,x,k);return O.pointerType="mouse",O.isPrimary=!0,new window.PointerEvent(b,O)}function g(b,w,x,k,O){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,x,k,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),O,document.body?document.body.parentNode:document.documentElement),j}function f(b,w){let x=["pointerup","pointerdown","pointermove"],k=w.modifiers||{},O=p(b,w.element),j=w.button||0,R=b.event;return x.includes(R)?m(R,k,O.x,O.y):g(R,k,O.x,O.y,j)}function h(){var w;let b=document.activeElement;for(;(w=b.shadowRoot)!=null&&w.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(w=>{try{return f(w,b)}catch{return}}).filter(Boolean).forEach(w=>{b.element.dispatchEvent(w),s(b,w),n(b,w)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let S={element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,quirks:r.quirks,modifiers:r.modifiers,button:r.button};if(!S.element){a("element not found");return}c(S.element),l(S.element);try{y(S);let b=h(),w=S.quirks,x=w==null?void 0:w.isReactSelect,k=w==null?void 0:w.isCKEditorFrame;!x&&!k&&dispatchFocus(r.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var kh={};W(kh,{doDragPath:()=>oS});var oS,Oh=T(()=>{"use strict";oS=function(r,e){let t=typeof Event=="function",s=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(b){e({status:"done",result:b,success:!0})}function i(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),b.dispatchEvent(w)}function c(b){let w={},x=b.getBoundingClientRect(),k=x.left+x.width/2,O=x.top+x.height/2,I=m("mousemove",w,k,O,0);b.dispatchEvent(I)}function l(b,w){function x(I,L,F){return F>I&&F<L}let k=b.pointerPosition||{};if(S.isDrag)return{x:k.originX||0,y:k.originY||0};let O=w.getBoundingClientRect(),j=k.originX&&x(O.left,O.left+O.width,k.originX)?k.originX:O.left+O.width/2,R=k.originY&&x(O.top,O.top+O.height,k.originY)?k.originY:O.top+O.height/2;return{x:j,y:R}}function p(b,w,x){return{screenX:0,screenY:0,clientX:w,clientY:x,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function d(b,w,x,k,O){if(s){let R=p(w,x,k);return R.pointerType="mouse",R.isPrimary=!0,new window.PointerEvent(b,R)}let j=document.createEvent("PointerEvent");return j.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,x,k,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),O,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),j}function m(b,w,x,k,O){let j=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return j.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,x,k,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),O,document.body?document.body.parentNode:document.documentElement),j}function g(b,w){let x=["pointerup","pointerdown","pointermove"],k=w.modifiers||{},O=l(b,w.element),j=w.button||0,R=b.event;return x.includes(R)?d(R,k,O.x,O.y,j):m(R,k,O.x,O.y,j)}function f(b,w){function x(){return b.event==="click"&&w.isDrag&&!w.allEventsOnSameElement}return x()}function h(b,w,x){try{let k=g(w.events[b],w);f(k,w)||w.element.dispatchEvent(k)}catch{}if(b+1===w.events.length)x();else{let k=Math.min(w.events[b+1].timeStamp-w.events[b].timeStamp,n);setTimeout(()=>{h(b+1,w,x)},k)}}function y(b,w){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w()})}let S={eventIndex:0,element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,quirks:r.quirks,isDoubleClick:r.isDoubleClick,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement,allEventsOnSameElement:r.allEventsOnSameElement};if(!S.element){i("element not found");return}a(S.element),c(S.element),y(S,()=>{o()})}});var Cn,Ui,_h=T(()=>{"use strict";Cn=E(require("lodash"));ue();Ih();he();Ah();Ui=class extends V{getDnDRectsAndOffsets(e,t,s,n){let o=this.stepActionUtils.getClickOffset(s,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.x,fromY:o.y,toRect:t.rectWithoutFrameOffset,toX:i.x,toY:i.y}}async clickJs(){var p;let{step:e,context:t}=this,s=this.getTarget(),n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return{success:!1,reason:"Malformed step: missing recorded events"};let i={isRoot:s.isRoot,locatedElement:s.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Ch(),Ph)),Promise.resolve().then(()=>(wn(),Tn))]),l=`
|
|
225
|
+
`;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:g,actualY:f}=m.value;return p?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,g,f)}}}catch{return{errorType:o.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 gh,hh=T(()=>{"use strict";gh=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,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),o=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var yh,bh=T(()=>{"use strict";yh=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(O){e({status:"done",result:O,success:!0})}function a(O){O||={},e({status:"failed",result:O,success:!1,keep:!0})}function c(O){return O!=null&&O.toLowerCase?(O=O.toLowerCase(),O==="text"?"text/plain":O==="url"?"text/uri-list":O):O}function l(){try{return new DataTransfer}catch{return{data:{},setData(D,$){o[c(D)]=$},getData(D){return o[c(D)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],p=d.concat(["drop","dragenter","dragover"]);function g(O){let D=O;for(;D&&D!==document.documentElement;){if(D.draggable)return D;D=D.parentElement}return null}function f(O,D,$){let V=D.element,{dispatchDragEventsOnClosestDraggable:J}=$;if(d.includes(O.type)&&J){if(!V&&D.lastDraggedElement)return D.lastDraggedElement;let Q=g(V);if(Q)return D.lastDraggedElement=Q,Q}return V}function h(O,D,$){function V(ht,Pr,A){return A>ht&&A<Pr}let J=O.pointerPosition||{};if(D)return{x:J.originX||0,y:J.originY||0};let Q=$.getBoundingClientRect(),de=J.originX&&V(Q.left,Q.left+Q.width,J.originX)?J.originX:Q.left+Q.width/2,$t=J.originY&&V(Q.top,Q.top+Q.height,J.originY)?J.originY:Q.top+Q.height/2;return{x:de,y:$t}}function y(O,D,$){let V=(D==null?void 0:D.modifiers)||{},J=h(O,$.isDrag,$.element),Q=(D==null?void 0:D.button)||0,de=O.event;return m.includes(de)?S(de,V,J.x,J.y,Q):p.includes(de)?w(de,V,J.x,J.y):b(de,V,J.x,J.y,Q)}function v(O,D,$){return{screenX:0,screenY:0,clientX:D,clientY:$,ctrlKey:Boolean(O.ctrl),altKey:Boolean(O.alt),shiftKey:Boolean(O.shift),metaKey:Boolean(O.meta),bubbles:!0,cancelable:!0,composed:!0}}function S(O,D,$,V,J){if(n){let de=v(D,$,V);return de.pointerType="mouse",de.isPrimary=!0,new window.PointerEvent(O,de)}let Q=document.createEvent("PointerEvent");return Q.initPointerEvent(O,!0,!0,document.defaultView,1,0,0,$,V,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),J,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),Q}function b(O,D,$,V,J){let Q=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return Q.initMouseEvent(O,!0,!0,document.defaultView,1,0,0,$,V,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),J,document.body?document.body.parentNode:document.documentElement),Q}function w(O,D,$,V){if(O==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let de=document.createEvent("CustomEvent");return de.initCustomEvent(O,!0,!0,null),Object.assign(de,{dataTransfer:window.TSTA.dataTransfer}),de}let J=v(D,$,V),Q=new window.DragEvent(O,J);return Object.defineProperties(Q,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),Q}function I(O,D,$){let V=f(O,D,$);V==null||V.dispatchEvent(O)}function C(O,D){function $(){return O.event==="click"&&D.isDrag&&!D.allEventsOnSameElement}return $()}function k(O,D,$){if($){let V=Math.min($.timeStamp-D.timeStamp,40);setTimeout(()=>{R(O)},V)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function R(O){let D,$=O.events[O.eventIndex],V=O.events[++O.eventIndex];try{O.element=getLocatedElement($.locatedElement),D=y($,s,O)}catch(J){return a(`exception in get event in drag step:${J.message}`)}if(C($,O))return k(O,$,V);if(D)try{I(D,O,$)}catch(J){return a(`exception in executeEvent in drag step:${J.message}`)}else return a(`cannot execute event ${$.event}`);k(O,$,V)}let M={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(M)}catch(O){a(O)}},0)}});var Th={};G(Th,{doClick:()=>BE});var BE,wh=T(()=>{"use strict";BE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,w){var k;function I(R){function M(){return o(R).find($=>[...$.classList||[]].includes("Select-control"))}function O(){let $=M();return $?$.querySelector("input"):null}let D=O();D==null||D.focus()}let C=(k=b.quirks)==null?void 0:k.isReactSelect;w.type==="mousedown"&&C&&I(b.element)}function n(b,w){var C;let I=(C=b.quirks)==null?void 0:C.isCKEditorFrame;w.type==="click"&&I&&document.body.focus()}function o(b){let w=[];for(;b!=null&&b.parentNode;)w.push(b),b=b.parentNode;return w}function i(b){let w={status:"done",result:b,success:!0,...S.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(w)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),b.dispatchEvent(w)}function l(b){let w={},I=b.getBoundingClientRect(),C=I.left+I.width/2,k=I.top+I.height/2,O=g("mousemove",w,C,k,0);b.dispatchEvent(O)}function d(b,w){function I(O,D,$){return $>O&&$<D}let C=b.pointerPosition||{},k=w.getBoundingClientRect(),R=C.originX&&I(k.left,k.left+k.width,C.originX)?C.originX:k.left+k.width/2,M=C.originY&&I(k.top,k.top+k.height,C.originY)?C.originY:k.top+k.height/2;return{x:R,y:M}}function m(b,w,I){return{screenX:0,screenY:0,clientX:w,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function p(b,w,I,C){if(!window.PointerEvent)return;let k=m(w,I,C);return k.pointerType="mouse",k.isPrimary=!0,new window.PointerEvent(b,k)}function g(b,w,I,C,k){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),k,document.body?document.body.parentNode:document.documentElement),R}function f(b,w){let I=["pointerup","pointerdown","pointermove"],C=w.modifiers||{},k=d(b,w.element),R=w.button||0,M=b.event;return I.includes(M)?p(M,C,k.x,k.y):g(M,C,k.x,k.y,R)}function h(){var w;let b=document.activeElement;for(;(w=b.shadowRoot)!=null&&w.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(w=>{try{return f(w,b)}catch{return}}).filter(Boolean).forEach(w=>{b.element.dispatchEvent(w),r(b,w),n(b,w)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let S={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!S.element){a("element not found");return}c(S.element),l(S.element);try{y(S);let b=h(),w=S.quirks,I=w==null?void 0:w.isReactSelect,C=w==null?void 0:w.isCKEditorFrame;!I&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var vh={};G(vh,{doDragPath:()=>jE});var jE,Eh=T(()=>{"use strict";jE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(b){e({status:"done",result:b,success:!0})}function i(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let w=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");w.initEvent("mouseover",!0,!0),b.dispatchEvent(w)}function c(b){let w={},I=b.getBoundingClientRect(),C=I.left+I.width/2,k=I.top+I.height/2,O=p("mousemove",w,C,k,0);b.dispatchEvent(O)}function l(b,w){function I(O,D,$){return $>O&&$<D}let C=b.pointerPosition||{};if(S.isDrag)return{x:C.originX||0,y:C.originY||0};let k=w.getBoundingClientRect(),R=C.originX&&I(k.left,k.left+k.width,C.originX)?C.originX:k.left+k.width/2,M=C.originY&&I(k.top,k.top+k.height,C.originY)?C.originY:k.top+k.height/2;return{x:R,y:M}}function d(b,w,I){return{screenX:0,screenY:0,clientX:w,clientY:I,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,w,I,C,k){if(r){let M=d(w,I,C);return M.pointerType="mouse",M.isPrimary=!0,new window.PointerEvent(b,M)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),k,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function p(b,w,I,C,k){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(w.ctrl),Boolean(w.alt),Boolean(w.shift),Boolean(w.meta),k,document.body?document.body.parentNode:document.documentElement),R}function g(b,w){let I=["pointerup","pointerdown","pointermove"],C=w.modifiers||{},k=l(b,w.element),R=w.button||0,M=b.event;return I.includes(M)?m(M,C,k.x,k.y,R):p(M,C,k.x,k.y,R)}function f(b,w){function I(){return b.event==="click"&&w.isDrag&&!w.allEventsOnSameElement}return I()}function h(b,w,I){try{let C=g(w.events[b],w);f(C,w)||w.element.dispatchEvent(C)}catch{}if(b+1===w.events.length)I();else{let C=Math.min(w.events[b+1].timeStamp-w.events[b].timeStamp,n);setTimeout(()=>{h(b+1,w,I)},C)}}function y(b,w){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w()})}let S={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(!S.element){i("element not found");return}a(S.element),c(S.element),y(S,()=>{o()})}});var In,_i,Sh=T(()=>{"use strict";In=E(require("lodash"));ue();hh();Te();bh();_i=class extends W{getDnDRectsAndOffsets(e,t,r,n){let o=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.x,fromY:o.y,toRect:t.rectWithoutFrameOffset,toX:i.x,toY:i.y}}async clickJs(){var d;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return{success:!1,reason:"Malformed step: missing recorded events"};let i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(wh(),Th)),Promise.resolve().then(()=>(yn(),hn))]),l=`
|
|
226
226
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
227
227
|
var dispatchFocus = ${c.toString()};
|
|
228
228
|
var doClick = ${a.toString()};
|
|
229
229
|
var eventData = arguments[0];
|
|
230
230
|
var done = arguments[1];
|
|
231
231
|
return doClick.call(null, eventData, done);
|
|
232
|
-
`;try{return(
|
|
232
|
+
`;try{return(d=(await this.driver.executeCodeAsync(l,n,i)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(m){return{success:!1,reason:m.message,exception:m}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.getTarget().rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),o=this.isWithinBounds(r.top,r.top+r.height,e.originY),i=n?0:r.left+r.width/2-e.originX,a=o?0:r.top+r.height/2-e.originY;return{xOffset:i,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=In.cloneDeep(e);return r.event=t,r}fixAbsoluteDragEventSequence(){let{events:e=[],allEventsOnSameElement:t,isHTML5Drag:r,toElement:n}=this.step,o=e.find(l=>["mousedown","pointerdown"].includes(l.event));if(o){let l=e.indexOf(o);e.splice(l,0,this.generateEventOfType(o,"mouseover"))}let{recordPointerMoveEvents:i=!1}=this.context.project.defaults||{},a=e.find(l=>l.event==="mouseup")||i&&e.find(l=>l.event==="pointerup"),c=Number(In.findLastIndex(e,l=>l.event==="mousemove")||i&&In.findLastIndex(e,l=>l.event==="pointermove"));a&&c>0&&!t&&e.splice(c+1,0,this.generateEventOfType(a,"mouseover")),r&&!n&&(this.step.events=this.addDragendIfNeeded(e)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var d,m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3;if(!((d=e.events)!=null&&d.length))return{success:!1,reason:"Malformed step: missing recorded events"};this.fixAbsoluteDragEventSequence();let o=e.events,i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},[{doDragPath:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Eh(),vh)),Promise.resolve().then(()=>(yn(),hn))]),l=`
|
|
233
233
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
234
234
|
var dispatchFocus = ${c.toString()};
|
|
235
235
|
var doDragPath = ${a.toString()};
|
|
236
236
|
return doDragPath.apply(null, arguments);
|
|
237
|
-
`;try{return(
|
|
237
|
+
`;try{return(m=(await this.driver.executeCodeAsync(l,n,i)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(p){return{success:!1,reason:p.message,exception:p}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:n,rect:o}=e,i={frameOffset:{x:o.left-n.left,y:o.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};if(U.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return{keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"};if(this.step.isDoubleClick){let d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,i)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(U.flags.usePortedHtml5DragDrop.isEnabled()){let f=this.generateHTML5DragEventSequence(),h=this.context.data.timeToPlayStep+3e3,y=this.getTarget(),v={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:f,eventData:{modifiers:this.step.modifiers,button:this.step.button},quirks:this.step.quirks,isDrag:this.step.isDrag,useRecordedMousedown:this.step.useRecordedMousedown,allEventsOnSameElement:this.step.allEventsOnSameElement,elementToFocusLocatedElement:y.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:y.locatedElement,isRoot:y.isRoot},S=`
|
|
238
238
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
239
|
-
var dnd = ${
|
|
239
|
+
var dnd = ${yh.toString()};
|
|
240
240
|
var eventData = arguments[0];
|
|
241
241
|
var done = arguments[1];
|
|
242
242
|
return dnd.call(null, eventData, done);
|
|
243
|
-
`;return this.driver.executeCodeAsync(S,h,v)}let
|
|
243
|
+
`;return this.driver.executeCodeAsync(S,h,v)}let p=`
|
|
244
244
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
245
|
-
var dnd = ${
|
|
245
|
+
var dnd = ${gh.toString()};
|
|
246
246
|
var eventData = arguments[0];
|
|
247
247
|
return dnd.call(null, eventData);
|
|
248
|
-
`,g={fromLocatedElement:t,toLocatedElement:
|
|
248
|
+
`,g={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(p,g)}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 c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(r,i):this.driver.leftClick(r,i)}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=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>Object.assign(o,{locatedElement:n(o)?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 xn,Rh=T(()=>{"use strict";ue();xn=class extends W{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:o}}=this,i=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(i),{evaluatedText:c}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Ih,$E,Li,xh=T(()=>{"use strict";Ih=E(require("lodash"));ue();B();$E=x("evaluate-expression-step-action"),Li=class extends W{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{$E.info("runner running incoming params evaluation");let o=t.incomingParams||{};Ih.isEmpty(o)&&(o=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,i.concat([l]))(...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(o){let{stepResult:i}=this.sessionPlayerInit.commonConstants;throw{errorType:i.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:o.toString()},success:!1}}}}});var Ah={};G(Ah,{setText:()=>WE});var WE,Ph=T(()=>{"use strict";WE=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(){$t()},window.addEventListener("unload",window.__unloadNavigator);let o=new Set(["keydown","keyup","keypress"]),i=15;function a(A){try{if(!t)return;let _=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return A.eventData&&(_.data=A.eventData.data),_}catch{}}function c(A){try{let _=document.createEvent("TextEvent");_.data=A.eventData.data;let F=1,H=A.eventData.locale||"en-US";return _.initTextEvent("textInput",!0,!0,window,A.eventData.data,F,H),_}catch{}}function l(A){return a(A)||c(A)}function d(A,_,F){try{return new KeyboardEvent(A,{bubbles:!0,cancelable:!0,location:_.location||0,key:_.key||"",ctrlKey:Boolean(F.ctrl),shiftKey:Boolean(F.shift),altKey:Boolean(F.alt),metaKey:Boolean(F.meta)})}catch{}}function m(A,_,F){try{let H=document.createEvent("KeyboardEvent");return H.initKeyEvent(A,!0,!0,null,Boolean(F.ctrl),Boolean(F.alt),Boolean(F.shift),Boolean(F.meta),_.key||"",0),H}catch{}}function p(A,_,F){try{let H=document.createEvent("Events");return H.initEvent(A,!0,!0),Object.assign(H,{altKey:Boolean(F.alt),ctrlKey:Boolean(F.ctrl),metaKey:Boolean(F.meta),shiftKey:Boolean(F.shift),keyCode:_.key||""}),H}catch{}}function g(A,_,F){return d(A,_,F)||m(A,_,F)||p(A,_,F)}function f(A){if(!o.has(A.event))return null;let _=A.eventData,F=_.modifiers||{},H=g(A.event,_,F);return Object.defineProperties(H,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(H,{_keyCode_:_.keyCode,_charCode_:_.charCode||0}),H}function h(A){return A.event==="textInput"?l(A):f(A)}function y(A,_){return(()=>{var H;return A.event==="textInput"&&!((H=_.quirks)!=null&&H.isAuth0Form)})()}function v(A,_){return A.event==="keyup"&&_.event==="keydown"?i:0}function S(A,_){let F=v(A,_);return Math.min(_.timeStamp-A.timeStamp,F)}function b(A){let _=Object.getOwnPropertyDescriptor(A,"value");if(!_)return;let F=A.value;A.value=`${F}#`,_.configurable&&delete A.value,A.value=F;let H=document.createEvent("HTMLEvents");H.initEvent("input",!0,!1),A.dispatchEvent(H),Object.defineProperty(A,"value",_)}function w(A){if(V(A.element))try{if(b(A.element),t)A.element.dispatchEvent(new Event("change"));else{let _=document.createEvent("HTMLEvents");_.initEvent("change",!1,!0),A.element.dispatchEvent(_)}}catch{}}function I(A,_,F){F?setTimeout(()=>{$(A)},S(_,F)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),w(A),$t())}function C(A,_){return(A==="change"||A==="blur")&&_.element.tagName==="OPTION"}function k(A,_,F){return C(A.type,_)?_.element.parentElement:F.locatedElement?getLocatedElement(F.locatedElement):_.element}function R(A,_){let F=A.firstChild,H;for(;F;){if(F.nodeType===3){if(_.offset--<=0)return F}else if(F.nodeType===1&&(H=R(F,_),H))return H;F=F.nextSibling}return null}function M(A,_){if(!(!A||!_)){if(!isNaN(_.start))Object.assign(A,{selectionStart:_.start,selectionEnd:_.end});else if(!isNaN(_.nodeOffset)){let F;if(A.firstChild?F=R(A,{offset:_.nodeOffset}):F=A,F){let H=window.getSelection(),st=document.createRange();try{H.removeAllRanges(),st.setStart(F,_.textOffset),st.setEnd(F,_.textOffset),H.addRange(st)}catch{}}}}}function O(A,_){return A==="submit"&&Boolean(_.action)}function D(A,_,F){if(_.isFocusable&&_.isSelectable(A)&&A.type!=="submit")try{M(_.element,F.eventData.selection)}catch{}let H=k(A,_,F);if(!H)throw new Error("could not find element");O(A.type,H)?H.submit():H.dispatchEvent(A)}function $(A){let _,F=A.events[A.eventIndex],H=A.events[++A.eventIndex];try{_=h(F)}catch(st){return ht(`exception in get event in text step:${st.message}`)}if(y(F,A))return I(A,F,H);if(_)try{D(_,A,F)}catch(st){return ht(`exception in executeEvent in text step:${st.message}`)}else if(A.noEventExecuter)A.noEventExecuter(A,F);else return ht(`cannot execute event ${F.event}`);I(A,F,H)}function V(A){let _=A.tagName;return _==="INPUT"||_==="TEXTAREA"}function J(A){return A.getAttribute?Boolean(A.getAttribute("contenteditable")==="true"):!1}function Q(A,_){if(V(A.element)){A.element.value=_.eventData.text;let F=document.createEvent("Event");F.initEvent("input",!0,!1),A.element.dispatchEvent(F)}else A.isContentEditable&&(A.element.innerHTML=_.eventData.text)}function de(){var _;let A=document.activeElement;for(;(_=A.shadowRoot)!=null&&_.activeElement;)A=A.shadowRoot.activeElement;return A}function $t(A){let _={status:"done",result:A,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(_)}function ht(A){A||="";let _={status:"failed",result:A,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(_)}try{let A=V(n.element);n.isContentEditable=J(n.element),!A&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=A||n.isContentEditable,n.isSelectable=_=>_.type!=="keyup",n.noEventExecuter=Q}catch(A){ht(`exception in set text step:${A.message}`);return}let Pr=de();dispatchFocus(s.elementToFocusLocatedElement,Pr),$(n)}});var Di,Ch=T(()=>{"use strict";ue();j();Di=class extends W{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Oe(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var f;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:o}=this,i=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:c}=o.codeSnippets;if(i.isDraftEditor&&c)return this.driver.executeJS(c(i.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let l={eventType:t,events:e,quirks:r,locatedElement:i.locatedElement,isRoot:i.isRoot,elementToFocusLocatedElement:i.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(Ph(),Ah)),Promise.resolve().then(()=>(yn(),hn))]),p=`
|
|
249
249
|
var getLocatedElement = ${o.codeSnippets.getLocatedElementCode};
|
|
250
|
-
var dispatchFocus = ${
|
|
251
|
-
var setText = ${
|
|
250
|
+
var dispatchFocus = ${m};
|
|
251
|
+
var setText = ${d.toString()};
|
|
252
252
|
var eventData = arguments[0];
|
|
253
253
|
var done = arguments[1];
|
|
254
254
|
return setText.call(null, eventData, done);
|
|
255
|
-
`,g=await this.driver.executeCodeAsync(
|
|
255
|
+
`,g=await this.driver.executeCodeAsync(p,a,l);return{success:Boolean((f=g.value)==null?void 0:f.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Oe(t.seleniumElement),e[r]),r<e.length-1&&await oe(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(Oe(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 kh={};G(kh,{runCode:()=>GE});var GE,Oh=T(()=>{"use strict";GE=function(s,e){var d;function t(m,p){let g=`data-testim-${m}`,f="Native sessionStorage is not available";function h(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(h))throw new Error(f);let y=JSON.parse(window.sessionStorage.getItem(g)||"{}"),v=Object.assign({},y,p);window.sessionStorage.setItem(g,JSON.stringify(v))}catch(y){let v=y.message.toLowerCase().includes("quota"),S=y.message===f;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||v||S){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let w=JSON.parse(b.getAttribute(g)||"{}"),I=Object.assign({},w,p);if(b.setAttribute(g,JSON.stringify(I)),v||S)try{window.sessionStorage.removeItem(g)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(p=>p!=null&&p.locatedElement?getLocatedElement(p.locatedElement):p):m.directParams.map(p=>p.selector?document.querySelector(p.selector):p.value).concat(m.otherParams)}function n(m,p){function g(){return m.apply(null,p)}return g.prototype=m.prototype,new g}let o={},i={},a={},c=s.functionParams,l=s.transactionId;try{let m=r(s);m.push(o,i,a);let p=((d=s.function)==null?void 0:d.params)||c,f=(e||n(Function,p)).apply(null,m);typeof Promise<"u"&&f instanceof Promise?(t(l,{type:"promise"}),f.then(h=>{t(l,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})},h=>{t(l,{status:"failed",success:!1,result:{resultValue:h.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:f,exports:o,exportsTest:i,exportsGlobal:a}})}catch(m){t(l,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}}});var Mi,_u,or,Ni=T(()=>{"use strict";Mi=E(require("lodash"));j();ue();B();Te();_u=x("base-js-step-action"),or=class extends W{isExceedingMaxResultSize(t,r){var n;try{let o=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,i=U.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>i;return o?a:(a&&_u.warn(`js result size exceeded ${i}, 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(o){if(o.message.includes("sessionStorage")||o.message.includes("The operation is insecure")){let i=document.head.querySelector("#testim-storage-backup");return i?i.getAttribute(n):"{}"}throw o}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],o=[t.context,...r.as.functionArguments];return n.push(t.code),o.forEach(i=>{Mi.isObject(i)&&to(i,"seleniumElement",Mi.isEqual)}),{function:{params:n,args:o},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:o=""}}=this,i=r.config.retryTimeout,a=r.data.timeToPlayStep-i,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(p){_u.warn("failed to get js status",{err:p}),l={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((l==null?void 0:l.value)||"{}")}catch{_u.warn("non object value",{selRes:l}),d={status:"exception"}}let m=n.abortedSteps.find(p=>p.id===o);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-i<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=i,await oe(i),c()):{success:!0})};return c()}async executeInAut(t){let r=U.flags.experimentalPreCodeCompilation.isEnabled(),n=U.flags.experimentalAsyncCustomCode.isEnabled(),o=this.constructJSFunParams(t),i=o.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=o.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
|
|
256
256
|
${t.code}
|
|
257
|
-
};`:`function(${
|
|
257
|
+
};`:`function(${m.join(",")}) {
|
|
258
258
|
${t.code}
|
|
259
|
-
};`,o.function.params.pop()}let{codeSnippets:c}=this.sessionPlayerInit,{runCode:l}=await Promise.resolve().then(()=>(
|
|
259
|
+
};`,o.function.params.pop()}let{codeSnippets:c}=this.sessionPlayerInit,{runCode:l}=await Promise.resolve().then(()=>(Oh(),kh)),d=`
|
|
260
260
|
${i?`var getLocatedElement = ${c.getLocatedElementCode};`:";"}
|
|
261
261
|
var runCode = ${l.toString()};
|
|
262
262
|
var eventData = arguments[0];
|
|
263
263
|
var funcToRun = ${a};
|
|
264
264
|
return runCode.call(null, eventData, funcToRun);
|
|
265
|
-
`;if(!
|
|
265
|
+
`;if(!r)return this.driver.executeJS(d,o);try{return await this.driver.executeJS(d,o)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:o={},tstConsoleLogs:i,nodeVersion:a,navigateToDifferentDomain:c}=t;o.exports&&(n.data.exports=o.exports);let l={nodeVersion:a,tstConsoleLogs:i,data:n.data};return this.isFailedResult(o.resultValue)?Object.assign(l,{success:!1,errorType:r.JS_ASSERTION_FAILED}):this.isExceedingMaxResultSize({result:o,tstConsoleLogs:i},n)?Object.assign(l,{success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}):Object.assign(l,{success:!0,exportsTest:o.exportsTest,exportsGlobal:o.exportsGlobal,...c&&{navigateToDifferentDomain:c}}),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 Object.assign({},t,{errorType:r.STOPPED});let{result:o={},tstConsoleLogs:i}=t;return{tstConsoleLogs:i,data:n.data,exportsGlobal:o.exportsGlobal,exportsTest:o.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:o.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),o={transactionId:`${r.testResultId}:${t.id}`,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(o);let i=await this.checkStatus(o.transactionId);return this.checkCodeResponse(i)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var jt,_h=T(()=>{"use strict";Ni();jt=class extends or{isFailedResult(e){return e===!1}}});var hs,Lh=T(()=>{"use strict";Ni();hs=class extends or{isFailedResult(e){return!e}}});var VE,Ui,Dh=T(()=>{"use strict";ue();j();VE={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"},Ui=class extends W{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Oe(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(VE[t]),this.setWithValueApi(e)}}});var Mh={};G(Mh,{selectOption:()=>HE});function HE(s,e){function t(r,n){let o=Element.prototype.matches,i=o&&isNativeFunction(o)?o:document.createElement(r.tagName).__proto__.matches;do{if(i.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(i=>{let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}).forEach(i=>{if(e){n.dispatchEvent(i);return}r.dispatchEvent(i)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var Nh=T(()=>{"use strict"});var Fi,Uh=T(()=>{"use strict";ue();j();Te();Fi=class extends W{async performAction(){var p,g;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((p=this.step.element)==null?void 0:p.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(Oe(t))}catch(f){if(!f.message.includes("Cannot check the displayedness of a non-Element argument"))throw f}let{selectOption:c}=await Promise.resolve().then(()=>(Nh(),Mh)),l=U.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
|
|
266
266
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
267
267
|
const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
|
|
268
268
|
const selectOption = ${c.toString()};
|
|
269
269
|
return selectOption.apply(null, arguments);
|
|
270
|
-
`;return(g=(await this.driver.executeJS(
|
|
270
|
+
`;return(g=(await this.driver.executeJS(d,r,l)).value)!=null&&g.success?{success:!0}:{success:!1}}}});var Bi,Fh=T(()=>{"use strict";ue();Bi=class extends W{async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var qE,ji,Bh=T(()=>{"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(){}}),ji=class extends W{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:o,height:i}=n,a=o/2,c=i/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:m,y:p}=l;this.sessionPlayerInit.utils.isWithinTargetRect(qE(i,o,0,0),m,p)&&(a=m,c=p)}let d={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,d),{success:!0}}}});var jh={};G(jh,{wheel:()=>zE});var zE,$h=T(()=>{"use strict";zE=function(s,e){function r(a,c){function l(f,h,y){return y>f&&y<h}let d=a.pointerPosition||{},m=c.getBoundingClientRect(),p=d.originX&&l(m.left,m.left+m.width,d.originX)?d.originX:m.left+m.width/2,g=d.originY&&l(m.top,m.top+m.height,d.originY)?d.originY:m.top+m.height/2;return{x:p,y:g}}function n(a,c,l){let d=r(a,l),m=(c==null?void 0:c.modifiers)||{},p={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",p)}function o(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),d=n(l,s.eventData,c),m=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(d),setTimeout(()=>{o(a,c)},m)}let i=getLocatedElement(s.locatedElement);o(s.events,i)}});var $i,Wh=T(()=>{"use strict";ue();$i=class extends W{async performAction(){var m;let{step:e,context:t}=this,{events:r,modifiers:n,button:o}=e;if(!(r!=null&&r.length))return;let i={events:r,eventData:{modifiers:n,button:o},locatedElement:this.getTarget().locatedElement},a=t.data.timeToPlayStep+3e3,{wheel:c}=await Promise.resolve().then(()=>($h(),jh)),l=`
|
|
271
271
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
272
272
|
var wheel = ${c.toString()};
|
|
273
273
|
var eventData = arguments[0];
|
|
274
274
|
var done = arguments[1];
|
|
275
275
|
return wheel.call(null, eventData, done);
|
|
276
|
-
`;return{success:((
|
|
276
|
+
`;return{success:((m=(await this.driver.executeCodeAsync(l,a,i)).value)==null?void 0:m.state)==="success"}}}});var Gh={};G(Gh,{downloadFileAndFireDropEvent:()=>KE});var KE,Vh=T(()=>{"use strict";KE=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let i=-1,a=0,c=[],l={endWithCallback:void 0,waitOn(){let d=++i;return function(m){d in c||(c[d]=m,a++,e.length===a&&l.endWithCallback(c))}},endWith(d){l.endWithCallback=d}};return l}function n(i,a,c){let l=new XMLHttpRequest;l.open("GET",i),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let o=r();e.forEach(i=>{n(i.url,i.name,o.waitOn())}),o.endWith(i=>{let a=createDropEvent(i);t.dispatchEvent(a)})}});var JE,Wi,Hh=T(()=>{"use strict";ue();B();Te();JE=x("drop-file-step-action"),Wi=class extends W{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,o=this.getTarget(),i=U.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrl(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,i,JE),{downloadFileAndFireDropEvent:c}=await Promise.resolve().then(()=>(Vh(),Gh)),l=`
|
|
277
277
|
const getLocatedElement = ${e.getLocatedElementCode};
|
|
278
278
|
const createDropEvent = ${e.createDropEvent.toString()};
|
|
279
279
|
const downloadFileAndFireDropEvent = ${c.toString()};
|
|
280
280
|
return downloadFileAndFireDropEvent.apply(null, arguments)
|
|
281
|
-
`;return await this.driver.executeJS(l,o.locatedElement,a)}}});function
|
|
281
|
+
`;return await this.driver.executeJS(l,o.locatedElement,a)}}});function Kh(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
|
|
282
282
|
var input = getLocatedElement(locatedElement);
|
|
283
283
|
if(input) {
|
|
284
284
|
function parents(element, _elements) {
|
|
@@ -307,20 +307,20 @@ Please make sure the CLI has stable access to the internet. ${Xa()?"(Internal: n
|
|
|
307
307
|
})
|
|
308
308
|
|
|
309
309
|
forceStyle(input, 'visibility', 'visible');
|
|
310
|
-
forceStyle(input, 'width', '${
|
|
311
|
-
forceStyle(input, 'max-width', '${
|
|
312
|
-
forceStyle(input, 'height', '${
|
|
313
|
-
forceStyle(input, 'max-height', '${
|
|
310
|
+
forceStyle(input, 'width', '${s.width}');
|
|
311
|
+
forceStyle(input, 'max-width', '${s.width}');
|
|
312
|
+
forceStyle(input, 'height', '${s.height}');
|
|
313
|
+
forceStyle(input, 'max-height', '${s.height}');
|
|
314
314
|
forceStyle(input, 'z-index', 100000000);
|
|
315
315
|
forceStyle(input, 'opacity', 1);
|
|
316
|
-
forceStyle(input, 'top', '${
|
|
317
|
-
forceStyle(input, 'left', '${
|
|
316
|
+
forceStyle(input, 'top', '${s.top}');
|
|
317
|
+
forceStyle(input, 'left', '${s.left}');
|
|
318
318
|
forceStyle(input, 'position', 'fixed');
|
|
319
319
|
forceStyle(input, 'pointer-events', 'all');
|
|
320
320
|
input.removeAttribute("disabled");
|
|
321
321
|
input.focus();
|
|
322
322
|
}
|
|
323
|
-
}`}async function
|
|
323
|
+
}`}async function XE(s,e){let t=null;try{t=(await $a(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=`${qh.tmpdir()}/${e}`;return await zh.promises.writeFile(r,t),r}function QE(s){return ie(s,e=>XE(e.url,e.name))}function ZE(s,e){return e(s)}async function Jh(s,e){let t=await QE(s),r=await ie(t,n=>ZE(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}var qh,zh,YE,Yh=T(()=>{"use strict";qh=E(require("os"));Ve();zh=require("fs");j();B();YE=x("input-file-utils")});function tS(){return`async function downloadAndUpload(locatedElement, fileUrls) {
|
|
324
324
|
const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
|
|
325
325
|
const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
|
|
326
326
|
const attachTo = document.body || document.documentElement;
|
|
@@ -397,18 +397,19 @@ Please make sure the CLI has stable access to the internet. ${Xa()?"(Internal: n
|
|
|
397
397
|
element.dispatchEvent(new Event("change", { bubbles: true }));
|
|
398
398
|
}
|
|
399
399
|
element.removeEventListener("change", changeFiredHandler, true);
|
|
400
|
-
}`}var
|
|
400
|
+
}`}var Gi,Vi,Xh=T(()=>{"use strict";Yh();ue();B();j();Te();Gi=x("input-file-step-action"),Vi=class extends W{constructor(){super(...arguments);this.uploadFile=t=>this.driver.uploadFile(t)}forceInputToBeVisible(t,r){Gi.info("workaround - stepaction - move element to visible position");let n=`
|
|
401
401
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
402
|
-
var getVisibleElement = ${
|
|
402
|
+
var getVisibleElement = ${Kh(r)};
|
|
403
403
|
return getVisibleElement.apply(null, arguments);
|
|
404
|
-
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let
|
|
404
|
+
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw Gi.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",p="is not reachable by keyboard",g=n?n.message:"";if(g===d||g.startsWith(m)||g.startsWith(o)||g.startsWith(i)||g.startsWith(a)||g.includes(p)||g.includes(c)||g.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw Gi.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Oe(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=U.flags.overrideAzureStorageUrl.isEnabled(),n=U.flags.useJsInputCodeInSafari.isEnabled(),o=U.flags.useJsInputCodeInFirefox.isEnabled(),i=U.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:a,context:c,step:l,stepActionUtils:d,driver:m}=this,p=await a.utils.addTokenToFileUrl(c.project.id,l.fileUrls,d.testimServicesApi,r,Gi),g=m.isSafari()&&(n||p.length>1),f=m.isFirefox()&&(o||p.length>1);if(i&&(p=await Promise.all(p.map(async({name:y,url:v})=>{let S=await _t(v);return{name:y,url:`data:${S.type};base64,${Buffer.from(S.body).toString("base64")}`}}))),g||f){await this.driver.executeJS(`
|
|
405
405
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
406
|
-
const downloadAndUploadFile = ${
|
|
407
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,m);return}let h=await ny(m,this.uploadFile);await this.uploadFilesAndForceVisibility(h,t)}}});var Xi,Qi,ay=T(()=>{"use strict";Xi=require("url");ue();Qi=class extends V{async updateBaseUrl(e){let t=new Xi.URL(e),s=new Xi.URL(this.context.recordedBaseUrl),n=new Xi.URL(this.context.baseUrl);return t.host===s.host&&s.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 Zi,cy=T(()=>{"use strict";ue();B();Zi=class extends V{async performAction(){await se(this.step.durationMS||0)}}});var ea,ly=T(()=>{"use strict";ue();ea=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var On,uy=T(()=>{"use strict";ue();On=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:s}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(s,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:s}=this.sessionPlayerInit;return typeof s=="function"&&s.length===2?s(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:s}=this,n={id:t.id,url:s.apiUrl,method:t.method,headers:s.apiHeaders,body:s.apiBody,timeout:s.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:s.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ta,py=T(()=>{"use strict";ue();ta=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var dy,my,ju,Bu,fy=T(()=>{"use strict";dy=E(require("@applitools/spec-driver-webdriverio")),my=require("@applitools/eyes-sdk-core");Hn();Te();ju=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=vp["@applitools/eyes-sdk-core"]||"N/A";this.sdk=(0,my.makeSDK)({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:dy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,s,n){let{EyeSdkBuilder:o}=ee(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(s,n),i}},Bu=new ju});var hy,gy,_n,yy=T(()=>{"use strict";hy=E(require("lodash"));ue();$();fy();gy=A("pixel-validation-step-action"),_n=class extends V{async performAction(){var d,m;let{shouldUseVisualGrid:t,applitoolsSdkConfig:s,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((m=s.batch)==null?void 0:m.id)||o,c=await Bu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},p;try{let g=await c.openEyes({driver:this.driver.client,config:s,logger:n}),h={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};hy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),gy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:h}),p={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){gy.error("Applitools SDK step failed",{err:g,info:g.info}),p={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Bu.handleApplitoolsSdkResult(this.context,p,this.step)}}});var ys,$u=T(()=>{"use strict";Rr();z();Wi();ys=class extends nr{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,s=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!s)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:p}=t,d={config:t.config,data:t.data},m=t.data.timeToPlayStep,g=await ls(o,i,a,d,c,l,p,m);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof re?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,by=T(()=>{"use strict";$u();or=class extends ys{isFailedResult(e){return e===!1}}});var ra,Ty=T(()=>{"use strict";$u();ra=class extends ys{isFailedResult(e){return!e}}});var sa,wy=T(()=>{"use strict";Rr();ue();z();sa=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:s,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await cs(e,s,n,t,o,i),success:!0}}catch(a){return a instanceof St?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof re?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var bs,vy=T(()=>{"use strict";ue();bs=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}}});var Ee,Ey=T(()=>{"use strict";ue();Ee=class extends V{async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var na,Sy=T(()=>{"use strict";ue();na=class extends V{async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});function vS(r,e){Object.keys(r).forEach(t=>{e.registerStepAction(t,r[t])})}function oa(r,e){vS(ES,e),e.registerLocateStepActionUtils(Pn.getUtils(r))}var ES,Wu=T(()=>{"use strict";wh();Sh();_h();Lh();Mh();Uh();$h();Wh();Vh();qh();zh();Kh();Xh();ey();iy();ay();cy();ly();uy();py();yy();by();Ty();wy();vy();Ey();Sy();ES={locate:Pn,scroll:Fi,mouse:Ui,submit:Hi,text:Bi,"special-key":Vi,"user-code":jt,"validation-code-step":jt,"wait-for-code-step":jt,"action-code-step":jt,"condition-step":hs,"skip-code-step":hs,"element-code-step":hs,"evaluate-expression":ji,"text-validation":kn,"wait-for-text-validation":kn,"select-option":Gi,"drop-file":Ki,"input-file":Yi,hover:qi,navigation:Qi,wheel:zi,sleep:Zi,refresh:ea,"api-validation":On,"api-action":On,"api-code-step":jt,"extract-text":ta,"simple-ui-verification":_n,"wait-for-simple-ui-verification":_n,"cli-validation-download-file":bs,"cli-wait-for-download-file":bs,"network-validation-step":bs,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":ra,"node-package":sa,"email-code-step":jt,"cli-email-code-step":or,"sfdc-recorded-step":na,"sfdc-step-login":Ee,"sfdc-step-loginas":Ee,"sfdc-step-logout":Ee,"sfdc-step-sobjectcreate":Ee,"sfdc-step-sobjectdelete":Ee,"sfdc-step-findrecord":Ee,"sfdc-step-quickaction":Ee,"sfdc-step-sobjectedit":Ee,"sfdc-step-sobjectvalidate":Ee,"sfdc-step-launchapp":Ee,"sfdc-step-wait-for-page-load":Ee,"sfdc-step-closeconsoletabs":Ee,"sfdc-step-relatedlistaction":Ee,"sfdc-step-permission-validation":Ee,"sfdc-step-quotelineeditor":Ee}});var Ry,SS,Ts,Vu=T(()=>{"use strict";Ry=["simple-ui-verification","wait-for-simple-ui-verification"],SS=[...Ry,"custom-validation","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-quotelineeditor"],Ts=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 s=Date.now();this.currentRetryStart=s,this.lastUpdateTime=s}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let s=this.getTotalStepRunTime(e),n=SS.includes(e.stepType)?[s]:t(s);this.resetStepVariables(s,n),e.context.data.maxTotalStepTime=s}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let s=e.context.config.stepTimeout;return Ry.includes(e.stepType)&&(s=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(s=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:s}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let s=Date.now()-e.startTimestamp;return t-s}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,s=e.step.type,n=3e4;return s==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var xy={};W(xy,{SeleniumTestPlayer:()=>Ln});var Iy,Ln,Gu=T(()=>{"use strict";B();Iy=require("@applitools/eyes-sdk-core");vn();z();Ou();gh();Mu();Nu();bh();Fu();Te();Wu();Vu();Ln=class{constructor(e,t,s,n,o,i=void 0,a=void 0){this.id=e;this.playbackTimeoutCalculator=new Ts(Mi());let{SessionPlayer:c,commonConstants:l,StepActionFactory:p}=ee();this.driver=o??new Sr;let d=new gs(this.driver);this.stepActionFactory=new p(d),oa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Li(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=yh(this.driver);this.sessionPlayer=new c(e,{tabService:this.tabService,cookieUtils:new ms(this.driver),FrameLocator:m,portSelector:Di,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,PlaybackManagerFactory:n??"codeless",makeSDK:Iy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),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=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var s,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ie((s=this.driver)==null?void 0:s.end(),t)}catch(o){o instanceof re&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},s=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(s);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Ay={};W(Ay,{WorkerSelenium:()=>Hu});function IS(r){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))r.playbackManager.on(t,()=>D(`Got event ${t}`))}var ia,RS,Hu,Py=T(()=>{"use strict";B();Ue();An();$();Ct();Bo();ce();Cu();z();Gu();Te();ia=A("worker-selenium"),RS=1e9,Hu=class extends st{initPlayer(t){return new Ln(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){D("in WorkerSelenium getBrowserOnce"),J.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ds(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,s,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),D("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),D("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,RS),await this.windowUtils.validatePageIsAvailable(),D("in WorkerSelenium after navigate")}catch(l){let p=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof vt||p||d?new vt(`Page '${c}' is not available`):(ia.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,s){var d;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=s,c=n||"runner";J.onWaitToTestComplete(this.id,this.isCodeMode),IS(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await nn(this.options))[this.testId]);let p=async()=>ie(new Promise((m,g)=>{a.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,m,!1,this.overrideTestConfigId,this.branch,!1,t.remoteRunId,void 0,void 0,l).catch(g)}),this.testRunTimeout,We.TEST_COMPLETE_TIMEOUT_MSG).catch(m=>{var g;throw m instanceof re&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),m}).then(async m=>{await o.drain(),m.stepsResults=null,m.resultId=this.testResultId,i.isAlive()||(ia.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.gridIssues="could not validate grid is alive");let g=i.maxKeepAliveGap();g>=3e4&&(ia.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.keepAliveIssue=g);let h={...m,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),D("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,s),D("right after super.runTestOnce in workerSelenium");let m=await p();return D("right after runSeleniumTest"),m}catch(m){throw ia.error("failed to run test once",{err:m}),m}}}});var aa,Cy=T(()=>{"use strict";aa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var qu,ca,ky=T(()=>{"use strict";$();qu=A("mobile-frame-locator-mock"),ca=class{foundFrameCallback(){return qu.info("foundFrameCallback-mock invoked"),{}}locate(){return qu.info("locate-mock invoked"),{}}async findFrame(){return qu.info("findFrame-mock invoked"),{}}}});var xS,Oy,AS,ws,zu=T(()=>{"use strict";xS=E(require("webdriverio")),Oy=require("@applitools/eyes-sdk-core");Cy();Mu();$();Nu();Fu();Te();Wu();ky();Vu();AS=A("appium-test-player"),ws=class{constructor(e,t,s,n,o=xS,i=void 0,a=void 0){this.id=e;this.driver=o;let{SessionPlayer:c,commonConstants:l,StepActionFactory:p,MobileLocateElementPlayer:d}=ee(),m=new gs(this.driver);this.stepActionFactory=new p(m),oa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ts(Mi()),this.sessionPlayer=new c(e,{tabService:new aa,cookieUtils:void 0,FrameLocator:ca,portSelector:Di,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,PlaybackManagerFactory:n,makeSDK:Oy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){}async onDone(){var e,t,s;try{await((s=(t=(e=this.driver)==null?void 0:e.activeSessions)==null?void 0:t.get(this.id))==null?void 0:s.deleteSession())}catch(n){AS.error("error while deleting appium session",{error:n})}finally{let{commonConstants:n}=ee();this.sessionPlayer.playbackManager.off(n.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e,t,s;return(s=(t=(e=this.driver)==null?void 0:e.activeSessions)==null?void 0:t.get(this.id))==null?void 0:s.sessionId}}});async function PS(r){return await $e(`${r}/api/status`)}async function _y(r,e){return await $e(`${r}/api/devices/${e}/status`)}async function Ly(r){let e="";try{(await PS(r)).fsmState!=="Ready"&&(e="TMA is not ready")}catch{e="It seems that the TMA agent is offline."}if(e)throw new Error(e)}var Dy=T(()=>{"use strict";He()});var Ny={};W(Ny,{WorkerLocalTma:()=>Xu});var My,Dn,la,Ku,Ju,Yu,Xu,Fy=T(()=>{"use strict";My=E(require("jsdom"));He();Dn=E(require("semver"));yn();An();B();$();Ct();zu();Te();hi();Dy();la=A("worker-appium"),Ku=class extends Error{},Ju=class extends Error{},Yu=class extends Error{},Xu=class extends st{constructor(){super(...arguments);this.baseDevicePath=(t,s)=>`${t}/api/devices/${s}`}initPlayer(t){return new ws(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:s}=ee(),n=new My.JSDOM("").window.DOMParser,o=new s(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}getAppId(t){if(this.options.appId)return this.options.appId;if(t!=null&&t.mobileApp&&"appId"in t.mobileApp)return t.mobileApp.appId;throw new Error("Could not determine app id. Try to specify the app ID or select an app from the app library in the test")}async getBrowserOnce(t,s,n,o){var O;if(J.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:c}=this.options;await Ly(i);let{project:l,authData:{token:p=""}={}}=this.options,{driver:d}=n,m=c.type,g=await t.getNativeAppData(),f=m==="android"?t.androidActivityWait:null,h=t.nativeAppLink,y=!1,v=this.getAppId(t),{mobileApp:S,appUrl:b}=await nu({appId:v,projectId:l,token:p});if(!S.appMetadata)throw new Error("App metadata is missing");this.options.appId&&(h=b);let[{appInstalled:w,version:x},k]=await Promise.all([this.getAppStateFromDevice(i,a,S.appMetadata.id),_y(i,a)]).catch(j=>{throw this.handleDeviceNotFoundError(j),j});if(w){let[j,R]=[Dn.coerce(x),Dn.coerce(S.appMetadata.version)];j&&R&&(y=!k.isVirtual&&Dn.cmp(j,"!==",R))}else await this.installApp(i,a,h);try{let j={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(O=this.options.projectData)==null?void 0:O.name}-${this.options.project}`},R=dg({projectType:m,nativeApp:g,appPath:h,androidActivityWait:f,sessionTags:j,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),I={capabilities:{udid:a,...R}},L=await this.requestNewAppiumSessionFromTma(i,I,S.appMetadata);if(this.sessionData=L,y){let G=this.initAndGetAppiumAPI(n);await G.removeApp(S.appMetadata.id),await this.installApp(i,a,h),await G.activateApp({[m==="ios"?"appId":"bundleId"]:S.appMetadata.id})}let F=await d.attach({sessionId:L.sessionId,capabilities:R});d.activeSessions||=new Map,d.activeSessions.set(this.id,F),await gi(t,F,this.options),la.info(`init new appium session testName: ${this.testName}`,{sessionId:F.sessionId,testResultId:this.testResultId,nativeApp:g})}catch(j){throw la.error("failed to start application",{err:j}),j}}async requestNewAppiumSessionFromTma(t,s,n){var o,i;try{let a=await Be({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:s,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local"}}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new Yu(c):a}}async getAppStateFromDevice(t,s,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,s)}/${o}`,c=(await $e(i)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,s,n){var o,i;try{let a=await _t(n);await Ls(`${this.baseDevicePath(t,s)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Ju(l,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let s=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof s=="string"&&(s!=null&&s.startsWith("Ensure that the requested device")))throw new Ku(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,s){let{manifestVersion:n,localAssetService:o}=ee(),{sessionPlayer:i}=s,a=n||"runner";J.onWaitToTestComplete(this.id,this.isCodeMode),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData=this.sessionData,this.initAndGetAppiumAPI(s),o.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,m)=>{i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,d,!1,this.overrideTestConfigId,this.branch,void 0,t.remoteRunId,void 0,void 0,void 0).catch(m)});return await o.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw la.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,s),await c()}catch(l){throw la.error("failed to run test once",{err:l}),l}}}});var jy={};W(jy,{WorkerAppium:()=>Qu});var Uy,ua,Qu,By=T(()=>{"use strict";Uy=E(require("jsdom"));yn();An();$();Ct();zu();Te();hi();ce();ua=A("worker-appium"),Qu=class extends st{initPlayer(e){return new ws(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){var m;J.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=s,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,{appPath:l,isTdcAppIdExists:p,isHSAppIdExists:d}=await Qf({testRunHandler:e,options:this.options});try{let g={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(m=this.options.projectData)==null?void 0:m.name}-${this.options.project}`},f={projectType:i,nativeApp:a,appPath:l,androidActivityWait:c,sessionTags:g,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,isHSAppIdExists:d,isTdcAppIdExists:p},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Jf(n,this.options.deviceUdid),h=await fg(f)):h=mg(f);let y=await o.remote(h);o.activeSessions||=new Map,o.activeSessions.set(this.id,y),await gi(e,y,this.options),ua.info(`init new appium session testName: ${this.testName}`,{sessionId:y.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(g){throw ua.error("failed to start application",{err:g}),g}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:s,type:n}=this.options.gridData;return n===N.TESTIM_HEADSPIN||n===N.TESTIM_TDC?`https://${e}:${t}/v0/${s}/wd/hub`:`https://${e}:${t}/wd/hub`}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:s,directConnectPort:n,directConnectPath:o}=e;if(t&&s&&n&&o)return`${t}://${s}:${n}${o}`}async runTestOnce(e,t){var f;let{manifestVersion:s,AppiumApi:n,localAssetService:o}=ee(),{sessionPlayer:i}=t,a=t.driver,c=s||"runner",l=a.activeSessions.get(this.id);J.onWaitToTestComplete(this.id,this.isCodeMode),i.playbackManager.executionId=e.executionId,i.playbackManager.executionName=e.executionName;let p;if(this.options.skipLoadBalancer){let{protocol:h,hostname:y,port:v,path:S}=await su(this.options.gridData,this.options.deviceUdid);p=`${h}://${y}:${v}${S}`}else p=this.getDirectAddressConnection(l.capabilities)||this.getServerAddressFromGrid();let d=new Uy.JSDOM("").window.DOMParser,m=l.capabilities;i.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:l.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(f=this.options.company)==null?void 0:f.companyId},i.playbackManager.appiumApi=new n(p,l.sessionId,d),o.initialize({serverUrl:this.options.localRCASaver});let g=async()=>{try{let h=await new Promise((v,S)=>{i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,v,!1,this.overrideTestConfigId,this.branch,void 0,e.remoteRunId,void 0,void 0,void 0).catch(S)});return await o.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...e.seleniumPerfStats.getStats()}}catch(h){throw ua.error("error while running appium tests",{err:h}),h}};try{return await super.runTestOnce(e,t),await g()}catch(h){throw ua.error("failed to run test once",{err:h}),h}}}});var pa,$y=T(()=>{"use strict";B();vn();z();pa=class{constructor(e){this.id=e;this.driver=new Sr}async onDone(){try{await ie(this.driver.end(),12e4)}catch(t){t instanceof re&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Wy,da,Vy=T(()=>{"use strict";Wy=E(require("ws"));B();da=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 Wy.default(this._cdpUrl,{timeout:e}),s=Wt(o=>{t.once("open",o)}),n=Wt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([s,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),s=this._cdpCallbacks.get(t.id);s&&(this._cdpCallbacks.delete(t.id),t.error?s.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?s.reject(new Error(t.result.exceptionDetails.exception.description)):s.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,s){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return s&&Object.assign(a,{sessionId:s}),n.send(JSON.stringify(a)),i}}});var fa,Zu,ma,Gy=T(()=>{"use strict";B();fa=E(require("chrome-launcher"));yn();Vy();en();Zu=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new da}async init(e,t,s,n,o,i,a,c,l,p){var f,h,y,v;let d=yi(e,t,s,n,o,i,a),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((v=(y=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:v.args)??[],...fa.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await fa.launch({chromeFlags:m,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await fr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),Qr(()=>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}},ma=class{constructor(e){this.id=e;this.sessionId=te();this.driver=new Zu(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var qy={};W(qy,{WorkerExtension:()=>Mn});function CS(r){return r instanceof Error&&"type"in r&&typeof r.type=="string"}function Hy(r){return CS(r)?r:new Error(r)}var nt,Mn,ep=T(()=>{"use strict";Ue();z();An();B();$();Ct();ce();$y();Gy();nt=A("worker-ext"),Mn=class extends st{initPlayer(){return this.options.useChromeLauncher?new ma(this.id):new pa(this.id)}async _getBrowserOnce(e,t,s,n){var i;let{driver:o}=s;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw nt.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,s,n){return J.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,s,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,s){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:s}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:s,executionId:n,testId:o}=this;D("WorkerExtension runTestOnce");let i=async p=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ie(e.runTestUsingCDP(p.cdpTestRunner),d,We.TEST_START_TIMEOUT_MSG)}catch(m){if(!(m instanceof re))throw m;return nt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:s}),await e.checkViaRestAPIIfTestStarted()}},a=async(p,d,m)=>{try{let g=await p.url(d);return m.driverUrlFinished=!0,g}catch(g){throw nt.error("error from driver.url",{err:g,testResultId:s,executionId:n,testId:o,url:d,urlLength:d.length}),g}},c=async p=>{let d=await e.onStarted(this.options.testStartTimeout);return p.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(D("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){J.onWaitToTestStart(this.id),J.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw nt.warn("failed to run test via CDP",{err:f}),f}}let{driver:d}=t,m={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();J.onWaitToTestStart(this.id);try{await ie(Promise.all([a(t.driver,f,m),c(m)]),this.options.testStartTimeout,We.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof re))throw v;nt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:s,executionId:n,testId:o,...m}),await e.checkViaRestAPIIfTestStarted()}J.onWaitToTestComplete(this.id,this.isCodeMode);let h=new AbortController,y=v=>{e.onCompletedCleanup(),nt.warn("on browser closed error detected",{err:v,testResultId:s,executionId:n,testId:o}),d.unregisterToClosedBrowser(y),v.type=Ms.BROWSER_CLOSED,h.abort(v)};d.registerToClosedBrowser(y);try{let v=ie(e.onCompleted(),this.testRunTimeout,We.TEST_COMPLETE_TIMEOUT_MSG),S=await Va(v,h.signal);d.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(x){nt.error("Could not update the grid about the test status",{err:x})}d.isAlive()||(nt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=d.maxKeepAliveGap();return b>=3e4&&(nt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(v){throw nt.warn("timeout wait until test completed",{err:v,testResultId:s,executionId:n,testId:o}),Hy(v)}finally{d.unregisterToClosedBrowser(y)}}catch(f){throw nt.warn("failed to start url",{err:f}),Hy(f)}};t.driver.start();try{return await super.runTestOnce(e,t),D("WorkerExtension super.runTestOnce"),await l()}catch(p){throw nt.error("failed to run test",{err:p,testId:e.testId,resultId:e.testResultId}),p}}}});var zy={};W(zy,{WorkerExtensionSingleBrowser:()=>tp});var kS,OS,tp,Ky=T(()=>{"use strict";Ue();B();$();Iu();Ct();ep();kS=A("base-worker"),OS=500,tp=class extends Mn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await In(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,s,n,o){return J.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,s,n,o)}async getTestPlayer(t,s){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(kS.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,s)),this.testPlayer}async runTest(t,s,n){let o=this.handleQuarantine(t);if(o)return o;D("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,s);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 se(OS)}}});function _S(r,e){e===0?r():setTimeout(r,e*Op)}var rp,ga,Jy=T(()=>{"use strict";vn();B();le();Ue();Xl();xt();gu();z();$();ce();th();rp=A("parallel-worker-manager"),ga=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Q.SELENIUM:return(Py(),fe(Ay)).WorkerSelenium;case Q.APPIUM:return e.localTmaUrl?(Fy(),fe(Ny)).WorkerLocalTma:(By(),fe(jy)).WorkerAppium;default:return wi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Ky(),fe(zy)).WorkerExtensionSingleBrowser:(ep(),fe(qy)).WorkerExtension}}createWorkers(e,t,...s){let n=s[0],o=this.getWorkerType(n),i=()=>{try{return D("before new Worker",n.mode),new o(t,...s)}finally{D("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,s,n,o,i,a,c,l){if(e&&e.length===0)return;let p=!1,d=0,m=g=>new Promise(f=>{var bt,Cr,C,_,U,H,ot;let h=o.project,y=new Ai(s,n,e,o,i,t),v={},S=e.length,b=((bt=o.company)==null?void 0:bt.ucid)||"",w=(Cr=o.company)==null?void 0:Cr.companyId,x=(C=o.company)==null?void 0:C.name,k=o.source||"cli",O=o.user,j=(_=o.company)==null?void 0:_.planType,R=(U=o.company)==null?void 0:U.isStartUp,I=(H=o.projectData)==null?void 0:H.name,L=(ot=o.projectData)==null?void 0:ot.type,F=o.lightweightMode,G=pr(o),Y=(Tt,it,ye,Ra,Nn,Ia)=>(d++,Sf({executionId:s,projectId:h,testId:it,resultId:ye,ucid:b,companyId:w,companyName:x,projectName:I,companyPlan:j,sessionType:G,source:k,user:O,lightweightMode:F,isStartUp:R,projectType:L,appSource:Ia}),t.testStartAndReport(Tt,s,ye,Ra,Nn)),X=async(Tt,it,ye,Ra,Nn,Ia)=>{var fp,gp,hp;d--;let Qe={...(F==null?void 0:F.onlyTestIdsNoSuite)&&{show:!0},...ye.seleniumStats&&{seleniumStats:ye.seleniumStats},...ye.gridIssues&&{gridIssues:ye.gridIssues},...ye.keepAliveIssue&&{keepAliveIssue:ye.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ye.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ye.seleniumPerfMarks),delete ye.seleniumPerfMarks),o.grid||o.gridId?(Qe.gridName=o.grid||((fp=o.gridData)==null?void 0:fp.name),Qe.gridType=(gp=o.gridData)==null?void 0:gp.type,Qe.gridProvider=(hp=o.gridData)==null?void 0:hp.provider):o.localTmaUrl?(Qe.gridName="local-tma-from-options",Qe.gridType="local-tma"):o.useLocalChromeDriver?(Qe.gridName="local-chrome-driver-from-options",Qe.gridType="local-chrome"):o.useChromeLauncher?(Qe.gridName="chrome-launcher-from-options",Qe.gridType="local-chrome"):o.browserstack?Qe.gridName="browserstack-from-options":o.saucelabs&&(Qe.gridName="saucelabs-from-options"),await t.testEndAndReport(Tt,ye,s,Ra,Nn,Qe).catch(Hb=>rp.error("testEndAndReport threw an error",{err:Hb})),Nn)return;v[ye.resultId]=ye,Rf({executionId:s,projectId:h,testId:it,resultId:ye.resultId,result:ye,ucid:b,companyId:w,companyName:x,projectName:I,companyPlan:j,sessionType:G,source:k,user:O,lightweightMode:F,logger:rp,isStartUp:R,projectType:L,appSource:Ia}),l&&!ye.success&&(y.stop(),p=!0),(Object.keys(v).length===S||p&&d===0)&&f(v)},de=(Tt,it)=>{v[it.resultId]=it,t.onTestIgnored(Tt,it.resultId),d--,(Object.keys(v).length===S||p&&d===0)&&f(v)},yt=(Tt,it)=>t.onGridSlot(Tt,it);o.userData={loginData:Object.assign({},Mt(),{refreshToken:So(),authData:Mt(),token:g}),projectId:o.project,company:o.company,servicesUrl:me},D("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,s,Y,X,yt,de).forEach((Tt,it)=>{D("before schedule worker.run after createWorkers"),_S(()=>{D("right before worker.run"),Tt.run()},it)})});try{let g=await qt(),f=await m(g);if(p)throw new $t;return f}catch(g){throw rp.error("failed running parallel workers",{executionId:s,err:g}),g}}}});var ha,Yy=T(()=>{"use strict";Si();ha=class extends rr{init(e){return super.initNewSocket(e,"real-data")}emitJoinRoom(e,t){this._socket.emit("testResult:listen",{query:`projectId=${t}&runId=${e}`})}joinToTestResultsByRunId(e,t){this.joinRoom(e,t),this.emitJoinRoom(e,t)}stopListenToTestResultsByRunId(e){this.leaveRoom(e),this._socket.emit("testResult:listen:stop",{})}listenToTestResultsByRunId(e){function t(s){e(s.data)}this._socket.on("testResult:changes",t.bind(this))}}});var sp,np,ya,Xy=T(()=>{"use strict";Sn();ce();he();Yy();({TEST_RESULT_CREATED:sp,TEST_RESULT_UPDATED:np}=tt),ya=class{constructor(){M.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new ha)}init(e){return M.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled())return Ne.addFilter(e,{runId:e},[np,sp],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(M.flags.useNewWSCLI.isEnabled()){Ne.removeFilter(e,[np,sp]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled()){Ne.listenTo(e,[np,sp],s=>s.runId===e,s=>t(s));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function Zy(r,e){var t;return(t=r.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&r.testId?{tests:[r.testId.map(n=>({testId:n,testConfig:{},resultId:te()}))]}:await Fc({projectId:r.project,labels:r.label,testIds:r.testId,testNames:r.name,testConfigNames:r.testConfigNames,suiteNames:r.suites,suiteIds:r.suiteIds,branch:e,rerunFailedByRunId:r.rerunFailedByRunId,testConfigIds:r.testConfigIds,intersections:r.intersections})}function op(r){let e=Object.keys(r).length,t=Object.keys(r).reduce((s,n)=>s+(r[n].success===!0?1:0),0);return e===t}async function ip(r,e){let t=r.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],s=Qy.difference(Ns(r,e),t);if(s.length>0)throw pt("invalid-config-run",{browser:s.join(", "),mode:"runner"}),new P(`browser type <${s}> is not supported in ${r.mode} mode.`);return e}var Qy,eb=T(()=>{"use strict";Qy=E(require("lodash"));B();Zr();be();z()});var Pr,tb,ap,ba,LS,Ta,rb=T(()=>{"use strict";Pr=E(require("lodash"));B();$();le();ce();Ue();ss();Dl();Xl();be();xt();Ct();Hf();z();Jy();Xy();eb();({testRunStatus:tb,CLI_MODE:ap}=Lt),ba=A("test-plan-runner"),LS=1e3*60*5,Ta=class{constructor(e){this.startTime=Date.now();this.workerManager=new ga(e)}async runTestAllPhases(e,t,s,n,o,i,a,c){let l={},p=Mt(),d=async()=>{let y=o.beforeParallel||1,v=!0,S=await this.workerManager.runTests(e,c,i,a,o,n,p,y,v);Object.assign(l,S)},m=async()=>{let y=Jn||o.parallel,v=!1;D("right before this.workerManager.runTests");let S=await this.workerManager.runTests(t,c,i,a,o,n,p,y,v);D("right after this.workerManager.runTests"),Object.assign(l,S)},g=async()=>{let y=o.afterParallel||1,v=!1,S=await this.workerManager.runTests(s,c,i,a,o,n,p,y,v);Object.assign(l,S)},f=pr(o);If({executionId:i,projectId:o.project,sessionType:f}),D("right before runBeforeTests");try{return await d(),D("right before runTestPlanTests"),await m(),D("right after runTestPlanTests"),await g(),l}catch(y){if(ba.error("error running test plan",{err:y}),y instanceof $t)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw y}finally{await h()}async function h(){var v,S,b,w;if((v=o.lightweightMode)!=null&&v.disablePixelValidation)return;if(o.mode===ap.SELENIUM){let[{getSessionPlayer:x},{makeSDK:k}]=await Promise.all([Promise.resolve().then(()=>(Te(),Kt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:O}=x();await O.closeBatch(i,k);return}let y;try{if(!((w=(b=(S=o.company)==null?void 0:S.activePlan)==null?void 0:b.premiumFeatures)!=null&&w.applitools)||(y=await Zc(o.project),Pr.default.isEmpty(y)||!i))return;let{runKey:x,url:k}=y;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:k,apiKey:x}})}catch{}}}async initRealDataService(e){let t=new ya;return await t.init(e),t}async listenToTestCreatedInFile(e,t,s,n){let o={};e.joinToTestResultsByRunId(s,t);let i=!0;return await new Promise(c=>{let l=p=>{i=!1,c(p)};e.listenToTestResultsByRunId(s,p=>{let d=p.id;if(!n.getTestResult(d)){let f=o[d],h=Pr.default.merge({},f,p,{resultId:d});if(o[d]=h,!f||f.status!==p.status){let v=(n.getTestResult(h.parentResultId)||{workerId:1}).workerId;[tb.RUNNING].includes(p.status)&&J.onTestStarted(h,v),[tb.COMPLETED].includes(p.status)&&(h.duration=h.endTime-h.startTime||0,J.onTestFinished(h,v))}}let m=!Object.values(o).some(f=>["QUEUED","RUNNING"].includes(f.runnerStatus)),g=!Object.values(n.getAllTestResults()).some(f=>["QUEUED","RUNNING"].includes(f.status));if(m&&g)return l(Object.values(o));if(g&&!m)return se(1e4).then(()=>{i&&l(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,s){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,s)}async runTestPlan(e,t,s,n,o,i,a,c){var k,O,j;let l=te(),p=n.project;Ua(l),e.forEach(R=>Object.assign(R,{isBeforeTestPlan:!0})),s.forEach(R=>Object.assign(R,{isAfterTestPlan:!0}));let d=[...e,...t,...s],m=new fi(d,n,i,a),g=Pr.default.chain(d).map(R=>{var I;return((I=R.overrideTestConfig)==null?void 0:I.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=n.files.length>0,y=(k=n.lightweightMode)!=null&&k.onlyTestIdsNoSuite?[]:d.map(R=>R.name),v=(O=n.lightweightMode)!=null&&O.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:s}:m.executionStart(l,p,this.startTime,o,y),S;h&&(S=this.initRealDataServiceAndListenToTestsCreatedInFile(p,l,m)),D("before testListInfoPromise");let b=await v;(j=n.lightweightMode)!=null&&j.onlyTestIdsNoSuite||J.onTestPlanStarted(b.beforeTests,b.tests,b.afterTests,o,l,c,f,h),D("before runTestAllPhases");let w=await this.runTestAllPhases(b.beforeTests,b.tests,b.afterTests,a,n,l,o||"All Tests",m),x=await ie(S,LS).catch(async()=>{var I;ba.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:p,executionId:l});let R=await Xs(p,"testResult",`runId=${l}&sort=runOrder`);return Pr.default.chain(((I=R==null?void 0:R.data)==null?void 0:I.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return D("before executionEnd"),await m.executionEnd(l),D("after executionEnd"),{results:w,executionId:l,testPlanName:o,configName:f,childTestResults:x}}async runTestPlans(e,t){ba.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function s(p){return Pr.default.flattenDeep(Object.values(p)).reduce((d,m)=>d.concat(m.beforeTests,m.tests,m.afterTests),[])}let n={},o={},i=e.project,a=await Nc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==ap.APPIUM&&await ip(e,s(l)),await ae(c,async p=>{var f;let d=p.testPlanId;n[d]={};let m=Object.assign({},e);m.baseUrl||=p.startUrl,m.appId||=((f=p.mobileApp)==null?void 0:f.appId)||void 0,m.gridId||=p.gridId,e.grid&&delete m.gridId,m.gridData=await nf(e,p);let g=m.overrideExecutionName||p.name;return await ae(l[d],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,m,g,d,t),v=e.files.length>0;J.onTestPlanFinished(y.results,p.name,this.startTime,y.executionId,!1,v,y.childTestResults),n[d][y.executionId]=y.results;let S=Object.keys(n[d]).map(k=>({executionId:k,status:op(n[d][k])})),b=Object.keys(n[d]).map(k=>n[d][k]).reduce((k,O)=>Object.assign(k,O),{}),w=op(b);Object.assign(o,b);let x=w?S[0].executionId:S.find(k=>!k.status).executionId;return await Lc(i,d,{success:w,executions:S,executionId:x}),y})})}async runAnonymousTestPlan(e,t){var a;ba.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),D("before getSuite");let s=await Zy(e,t);if(D("after getSuite"),!((a=s==null?void 0:s.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in s&&s.branch||t;let n=s;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return D("Right before validateConfig + runAnonymousTestPlan tests map"),await ae(s.tests,async c=>{if(e.resultId){let d=c[0];d.resultId=e.resultId,c=[d]}e.mode!==ap.APPIUM&&await ip(e,c),D("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);D("right after runTestPlan");let p=e.files.length>0;return await J.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i,p,l.childTestResults),l})}async run(e){let t=ln(),s=[];Fs(e)?s=await this.runTestPlans(e,t):s=await this.runAnonymousTestPlan(e,t);let n=Pr.default.flattenDeep(s);return D("right before onAllTestPlansFinished"),await J.onAllTestPlansFinished(n),D("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var ib={};W(ib,{init:()=>QS,run:()=>YS});async function MS(r){let e=r.project,t=await jc(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"),tn(r.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ps}function NS(r,e){var i,a,c,l,p,d;let t=no(e.activePlan),s=r.parallel;if(t==="free"&&s>nb)throw new P(`The free plan allows only ${nb} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let m=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(r.tunnel&&!m)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.runInTurboMode;if(r.lightweightMode&&!g)throw new P("Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted")}let n=r.retentionDays;if(!n)return;let o=(d=(p=e.activePlan)==null?void 0:p.premiumFeatures)==null?void 0:d.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function FS(r){var e;if(!((e=r.lightweightMode)!=null&&e.disableQuotaBlocking))try{await MS(r)}catch(t){if([P,Ps].some(s=>t instanceof s))throw t;DS.error("could not validate cli account",{err:t})}}function US(r){let e=Mt();return dm({userId:e.uid,name:e.uid,traits:{projectId:r,company:{id:r,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function jS(r,{disableResults:e=!1,disableRemoteStep:t=!1}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Ne.connect(r);if(!t){let{remoteStepService:s}=await Promise.resolve().then(()=>(Ri(),Hg));await s.init(r)}if(!e){let{testResultService:s}=await Promise.resolve().then(()=>(Ii(),Kg));s.init(r)}}function BS(r,e){let{branch:t,autoDetect:s}=r;if(lf(e,s),!e&&!s)throw new P(`branch ${t} does not exist, run aborted.`)}async function $S(r){let{project:e}=r,t=ln();ob.get(r,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(r.sfdcCredential=await Oc({projectId:e,branch:t}))}function WS(r,e){let{onprem:t,id:s,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:d,extensionPath:m,ext:g,playerPath:f}=r;if([Q.SELENIUM].includes(d)&&!f)throw new P("in selenium on prem mode --player-path must be provided");if(d==="extension"&&!m&&!g)throw new P("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),p=no(a);p==="free"&&(r.newBrowserWaitTimeout=r.newBrowserWaitTimeout<sb?sb:r.newBrowserWaitTimeout),M.setCompanyId(s),M.setIsPOC(c),M.setIsStartUp(l),M.setPlanType(p),Pt.setPlanType(p),r.company={ucid:"",companyId:s,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:p,isPOC:c,isStartUp:l,activePlan:a}}function VS(r,e){if(Or){r.editorUrl=Or;return}r.editorUrl=e.editorUrl}function GS(r,e){r.allGrids=e}function HS(r,e){r.authData=e}function qS(r,e){let{id:t,name:s,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),r.projectData={projectId:t,type:n,name:s,defaults:o}}async function zS(r){r.gridData=await of(r)}async function KS(r){let{project:e}=r,t={projectId:e};r.overrideMappingFile&&(pt("user-override-file",t),r.mockNetworkRules=await em(r.overrideMappingFile))}async function JS(r,e){D("in runner.js runRunner");let{project:t,remoteRunId:s,useLocalChromeDriver:n,useChromeLauncher:o}=r;s||(r.source=n||o?"cli-local":"cli"),await Dm(),D("in runner.js after checkNpmVersion"),await FS(r),D("in runRunner before tunnel.connect"),await Ko(r),D("in runRunner after tunnel.connect");let a=await new Ta(e).run(r);return D("before tunnel.disconnect"),await Jo(r),await an.end(t),D("after tunnel.disconnect and gridService.keepAlive.end"),a}function XS(r){var e;Pt.shouldShowFreeGridRunWarning((e=r.gridData)==null?void 0:e.type)&&console.log(`
|
|
406
|
+
const downloadAndUploadFile = ${tS()};
|
|
407
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,p);return}let h=await Jh(p,this.uploadFile);await this.uploadFilesAndForceVisibility(h,t)}}});var Hi,qi,Qh=T(()=>{"use strict";Hi=require("url");ue();qi=class extends W{async updateBaseUrl(e){let t=new Hi.URL(e),r=new Hi.URL(this.context.recordedBaseUrl),n=new Hi.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 zi,Zh=T(()=>{"use strict";ue();j();zi=class extends W{async performAction(){await oe(this.step.durationMS||0)}}});var Ki,ey=T(()=>{"use strict";ue();Ki=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var An,ty=T(()=>{"use strict";ue();An=class extends W{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ji,ry=T(()=>{"use strict";ue();Ji=class extends W{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var sy,Lu,Du,ny=T(()=>{"use strict";sy=E(require("@applitools/spec-driver-webdriverio"));Gn();be();Lu=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=fp["@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:sy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=ee(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Du=new Lu});var iy,oy,Pn,ay=T(()=>{"use strict";iy=E(require("lodash"));ue();B();ny();oy=x("pixel-validation-step-action"),Pn=class extends W{async performAction(){var m,p;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((p=r.batch)==null?void 0:p.id)||o,c=await Du.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},d;try{let g=await c.openEyes({driver:this.driver.client,config:r,logger:n}),h={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};iy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),oy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:h}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){oy.error("Applitools SDK step failed",{err:g,info:g.info}),d={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Du.handleApplitoolsSdkResult(this.context,d,this.step)}}});var ys,Mu=T(()=>{"use strict";Rr();z();Ni();ys=class extends or{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:d}=t,m={config:t.config,data:t.data},p=t.data.timeToPlayStep,g=await cs(o,i,a,m,c,l,d,p);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof re?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ir,cy=T(()=>{"use strict";Mu();ir=class extends ys{isFailedResult(e){return e===!1}}});var Yi,ly=T(()=>{"use strict";Mu();Yi=class extends ys{isFailedResult(e){return!e}}});var Xi,uy=T(()=>{"use strict";Rr();ue();z();Xi=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await as(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof wt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof re?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var bs,py=T(()=>{"use strict";ue();bs=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}}});var ve,dy=T(()=>{"use strict";ue();ve=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Qi,my=T(()=>{"use strict";ue();Qi=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Zi,fy=T(()=>{"use strict";ue();Zi=class extends W{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function rS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ea(s,e){rS(sS,e),e.registerLocateStepActionUtils(Rn.getUtils(s))}var sS,Nu=T(()=>{"use strict";ph();fh();Sh();Rh();xh();Ch();_h();Lh();Dh();Uh();Fh();Bh();Wh();Hh();Xh();Qh();Zh();ey();ty();ry();ay();cy();ly();uy();py();dy();my();fy();sS={locate:Rn,scroll:Oi,mouse:_i,submit:Bi,text:Di,"special-key":Ui,"user-code":jt,"validation-code-step":jt,"wait-for-code-step":jt,"action-code-step":jt,"condition-step":hs,"skip-code-step":hs,"element-code-step":hs,"evaluate-expression":Li,"text-validation":xn,"wait-for-text-validation":xn,"select-option":Fi,"drop-file":Wi,"input-file":Vi,hover:ji,navigation:qi,wheel:$i,sleep:zi,refresh:Ki,"api-validation":An,"api-action":An,"api-code-step":jt,"extract-text":Ji,"simple-ui-verification":Pn,"wait-for-simple-ui-verification":Pn,"cli-validation-download-file":bs,"cli-wait-for-download-file":bs,"network-validation-step":bs,"cli-validation-code-step":ir,"cli-wait-for-code-step":ir,"cli-action-code-step":ir,"cli-api-code-step":ir,"cli-condition-step":Yi,"node-package":Xi,"email-code-step":jt,"cli-email-code-step":ir,"sfdc-internal-test-step":Zi,"sfdc-recorded-step":Qi,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve}});var gy,nS,Ts,Uu=T(()=>{"use strict";gy=["simple-ui-verification","wait-for-simple-ui-verification"],nS=[...gy,"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"],Ts=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=nS.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 gy.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 yy={};G(yy,{SeleniumTestPlayer:()=>Cn});var hy,Cn,Fu=T(()=>{"use strict";j();hy=require("@applitools/eyes-sdk-core");bn();z();Iu();ih();Cu();ku();lh();Ou();be();Nu();Uu();Cn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Ts(ki());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Sr;let d=new gs(this.driver);this.stepActionFactory=new l(d),ea(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Pi(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=ch(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ms(this.driver),FrameLocator:m,portSelector:Ci,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:hy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ae((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof re&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var by={};G(by,{WorkerSelenium:()=>Bu});function iS(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>L(`Got event ${t}`))}var ta,oS,Bu,Ty=T(()=>{"use strict";j();Fe();Sn();B();At();Mo();ce();Su();z();Fu();be();ta=x("worker-selenium"),oS=1e9,Bu=class extends tt{initPlayer(t){return new Cn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){L("in WorkerSelenium getBrowserOnce"),X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ds(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,r,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),L("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),L("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,oS),await this.windowUtils.validatePageIsAvailable(),L("in WorkerSelenium after navigate")}catch(l){let d=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=l.message&&l.message==="invalid argument";throw l instanceof bt||d||m?new bt(`Page '${c}' is not available`):(ta.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),iS(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let l=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(l=(await nn(this.options))[this.testId]);let d=async()=>ae(new Promise((p,g)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:p,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(g)}),this.testRunTimeout,$e.TEST_COMPLETE_TIMEOUT_MSG).catch(p=>{var g;throw p instanceof re&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),p}).then(async p=>{await o.drain(),p.stepsResults=null,p.resultId=this.testResultId,i.isAlive()||(ta.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),p.gridIssues="could not validate grid is alive");let g=i.maxKeepAliveGap();g>=3e4&&(ta.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),p.keepAliveIssue=g);let h={...p,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),L("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),L("right after super.runTestOnce in workerSelenium");let p=await d();return L("right after runSeleniumTest"),p}catch(p){throw ta.error("failed to run test once",{err:p}),p}}}});var ra,wy=T(()=>{"use strict";ra=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var ju,sa,vy=T(()=>{"use strict";B();ju=x("mobile-frame-locator-mock"),sa=class{foundFrameCallback(){return ju.info("foundFrameCallback-mock invoked"),{}}locate(){return ju.info("locate-mock invoked"),{}}async findFrame(){return ju.info("findFrame-mock invoked"),{}}}});var aS,Sy,Ey,ws,$u=T(()=>{"use strict";aS=E(require("webdriverio")),Sy=require("@applitools/eyes-sdk-core");wy();Cu();B();ku();Ou();be();Nu();vy();Uu();Ey=x("appium-test-player"),ws=class{constructor(e,t,r,n=aS,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new gs(this.driver);this.stepActionFactory=new l(m),ea(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ts(ki()),this.sessionPlayer=new a(e,{tabService:new ra,cookieUtils:void 0,FrameLocator:sa,portSelector:Ci,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Sy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{await(n==null?void 0:n.endSession()),Ey.info("appium session deleted",o)}catch(i){Ey.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=ee();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function cS(s){return await Ne(`${s}/api/status`)}async function Ry(s,e){return await Ne(`${s}/api/devices/${e}/status`)}async function Iy(s){let e="";try{(await cS(s)).fsmState!=="Ready"&&(e="TMA is not ready")}catch{e="It seems that the TMA agent is offline."}if(e)throw new Error(e)}var xy=T(()=>{"use strict";Ve()});var Py={};G(Py,{WorkerLocalTma:()=>Hu});var Ay,kn,na,Wu,Gu,Vu,Hu,Cy=T(()=>{"use strict";Ay=E(require("jsdom"));Ve();kn=E(require("semver"));gn();Sn();j();B();At();$u();be();xy();ui();na=x("worker-appium"),Wu=class extends Error{},Gu=class extends Error{},Vu=class extends Error{},Hu=class extends tt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new ws(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=ee(),n=new Ay.JSDOM("").window.DOMParser,o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}checkIfUpgradeIsNeeded(t,r,n){if(n)return!1;let[o,i]=[kn.coerce(t),kn.coerce(r)];return!o||!i?!1:kn.cmp(o,"!==",i)}async getBrowserOnce(t,r,n,o){var C;if(X.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:c}=this.options;await Iy(i);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=n,p=c.type,g=!1,f=this.options.appId;if(f){let{executionId:k,testResultId:R}=t,{mobileApp:M}=await pt.getMobileAppDataByAppId({appId:f,projectId:l,token:d,executionId:k,testResultId:R});t.nativeApp=M}let h=p==="android"?t.androidActivityWait:null,y=t.nativeAppMetadata,v=t.downloadableAppPublicLink,S=t.appPackageNameOrBundleId;if(!y)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!S)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:b,version:w},I]=await Promise.all([this.getAppStateFromDevice(i,a,S),Ry(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!b&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!b&&v&&await this.installApp(i,a,v),b&&(!t.isAppFromDevice||f)&&(g=this.checkIfUpgradeIsNeeded(w,y.version,I.isVirtual));try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(C=this.options.projectData)==null?void 0:C.name}-${this.options.project}`},R=rg({projectType:p,nativeAppMetadata:y,appPath:v,androidActivityWait:h,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),M={capabilities:{udid:a,...R}},O=await this.requestNewAppiumSessionFromTma(i,M,y);if(this.sessionData=O,g){let $=this.initAndGetAppiumAPI(n);await $.removeApp(S),await this.installApp(i,a,v),await $.activateApp({[p==="ios"?"appId":"bundleId"]:S})}let D=await m.attach({sessionId:O.sessionId,capabilities:R});this.device=await pt.updateTmaDeviceDetails(a,this.options,t),na.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:D.sessionId,testResultId:this.testResultId,nativeAppMetadata:y,sessionCaps:D.capabilities})}catch(k){throw na.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await je({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local"}}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new Vu(c):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,c=(await Ne(i)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await _t(n);await Ls(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Gu(l,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Wu(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=ee(),{sessionPlayer:i}=r,a=n||"runner";X.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((m,p)=>{i.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(p)});return await o.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw na.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw na.error("failed to run test once",{err:l}),l}}}});var Oy={};G(Oy,{WorkerAppium:()=>qu});var ky,On,qu,_y=T(()=>{"use strict";gn();ky=require("linkedom");Sn();B();At();$u();be();ui();ce();On=x("worker-appium"),qu=class extends tt{initPlayer(t){return new ws(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,{appPath:c,isTdcAppIdExists:l,isHSAppIdExists:d}=await pt.getAppInfoForRemoteRun({testRunHandler:t,options:this.options}),m=a==="android"?t.androidActivityWait:null,p=t.nativeAppMetadata;if(!p)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let g={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag}},f={projectType:a,nativeAppMetadata:p,appPath:c,androidActivityWait:m,sessionTags:g,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig,isHSAppIdExists:d,isTdcAppIdExists:l},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await pt.lockDevice(o,this.options.deviceUdid),h=await ng(f)):h=sg(f),On.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:g,nativeAppMetadata:p,capabilities:og(h)}),this.activeSession=await i.remote(h),this.device=await pt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options),On.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(g){throw On.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===N.TESTIM_HEADSPIN||o===N.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var p,g;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l;if(this.options.skipLoadBalancer){let f=this.options.deviceUdid||((p=this.testRunConfig.mobile)==null?void 0:p.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:v,path:S}=await pt.getHeadSpinDeviceConnection(this.options.gridData,f);l=`${h}://${y}:${v}${S}`}else l=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(g=this.options.company)==null?void 0:g.companyId,device:this.device},a.playbackManager.appiumApi=new o(l,this.activeSession.sessionId,ky.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let f=await new Promise((y,v)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(v)});return await i.drain(),f.stepsResults=null,f.resultId=this.testResultId,{...f,...t.seleniumPerfStats.getStats()}}catch(f){throw On.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:f}),f}};try{return await super.runTestOnce(t,r),await m()}catch(f){throw On.error("failed to run test once",{err:f}),f}}}});var oa,Ly=T(()=>{"use strict";j();bn();z();oa=class{constructor(e){this.id=e;this.driver=new Sr}async onDone(){try{await ae(this.driver.end(),12e4)}catch(t){t instanceof re&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Dy,ia,My=T(()=>{"use strict";Dy=E(require("ws"));j();ia=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Dy.default(this._cdpUrl,{timeout:e}),r=Vt(o=>{t.once("open",o)}),n=Vt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var ca,zu,aa,Ny=T(()=>{"use strict";j();ca=E(require("chrome-launcher"));gn();My();en();zu=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ia}async init(e,t,r,n,o,i,a,c,l,d){var f,h,y,v;let m=di(e,t,r,n,o,i,a),p=[...((f=m.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((v=(y=(h=m.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:v.args)??[],...ca.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await ca.launch({chromeFlags:p,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await mr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),Yr(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},aa=class{constructor(e){this.id=e;this.sessionId=te();this.driver=new zu(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Fy={};G(Fy,{WorkerExtension:()=>_n});function lS(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Uy(s){return lS(s)?s:new Error(s)}var rt,_n,Ku=T(()=>{"use strict";Fe();z();Sn();j();B();At();ce();Ly();Ny();rt=x("worker-ext"),_n=class extends tt{initPlayer(){return this.options.useChromeLauncher?new aa(this.id):new oa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw rt.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return X.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;L("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ae(e.runTestUsingCDP(d.cdpTestRunner),m,$e.TEST_START_TIMEOUT_MSG)}catch(p){if(!(p instanceof re))throw p;return rt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,p)=>{try{let g=await d.url(m);return p.driverUrlFinished=!0,g}catch(g){throw rt.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),g}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var g;if(L("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){X.onWaitToTestStart(this.id),X.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw rt.warn("failed to run test via CDP",{err:f}),f}}let{driver:m}=t,p={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();X.onWaitToTestStart(this.id);try{await ae(Promise.all([a(t.driver,f,p),c(p)]),this.options.testStartTimeout,$e.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof re))throw v;rt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...p}),await e.checkViaRestAPIIfTestStarted()}X.onWaitToTestComplete(this.id);let h=new AbortController,y=v=>{e.onCompletedCleanup(),rt.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),v.type=Ms.BROWSER_CLOSED,h.abort(v)};m.registerToClosedBrowser(y);try{let v=ae(e.onCompleted(),this.testRunTimeout,$e.TEST_COMPLETE_TIMEOUT_MSG),S=await Ma(v,h.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(S.success),S.reason)}catch(I){rt.error("Could not update the grid about the test status",{err:I})}m.isAlive()||(rt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(rt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(v){throw rt.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:o}),Uy(v)}finally{m.unregisterToClosedBrowser(y)}}catch(f){throw rt.warn("failed to start url",{err:f}),Uy(f)}};t.driver.start();try{return await super.runTestOnce(e,t),L("WorkerExtension super.runTestOnce"),await l()}catch(d){throw rt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var By={};G(By,{WorkerExtensionSingleBrowser:()=>Ju});var uS,pS,Ju,jy=T(()=>{"use strict";Fe();j();B();Tu();At();Ku();uS=x("base-worker"),pS=500,Ju=class extends _n{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await vn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return X.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(uS.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;L("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await oe(pS)}}});function dS(s,e){e===0?s():setTimeout(s,e*Rp)}var Yu,la,$y=T(()=>{"use strict";bn();le();Fe();Hl();Rt();cu();z();B();ce();qg();Yu=x("parallel-worker-manager"),la=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(Ty(),fe(by)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(Cy(),fe(Py)).WorkerLocalTma:(_y(),fe(Oy)).WorkerAppium;default:return gi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(jy(),fe(By)).WorkerExtensionSingleBrowser:(Ku(),fe(Fy)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return L("before new Worker",n.mode),new o(t,...r)}finally{L("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,c,l){if(e&&e.length===0)return;let d=!1,m=0,p=g=>new Promise(f=>{var ht,Pr,A,_,F,H,st,ga;let h=o.project,y=new Ei(r,n,e,o,i,t),v={},S=e.length,b=((ht=o.company)==null?void 0:ht.ucid)||"",w=(Pr=o.company)==null?void 0:Pr.companyId,I=(A=o.company)==null?void 0:A.name,C=o.source||"cli",k=o.user,R=(_=o.company)==null?void 0:_.planType,M=(F=o.company)==null?void 0:F.isStartUp,O=(H=o.projectData)==null?void 0:H.name,D=(st=o.projectData)==null?void 0:st.type,$=o.lightweightMode,V=(ga=o.gridData)==null?void 0:ga.type,J=(kt,nt,he,ha,Dn,ya)=>(m++,Tf({executionId:r,projectId:h,testId:nt,resultId:he,ucid:b,companyId:w,companyName:I,projectName:O,companyPlan:R,source:C,user:k,lightweightMode:$,isStartUp:M,projectType:D,appSource:ya,gridType:V}),t.testStartAndReport(kt,r,he,ha,Dn)),Q=async(kt,nt,he,ha,Dn,ya)=>{var ap,cp,lp;m--;let Xe={...($==null?void 0:$.onlyTestIdsNoSuite)&&{show:!0},...he.seleniumStats&&{seleniumStats:he.seleniumStats},...he.gridIssues&&{gridIssues:he.gridIssues},...he.keepAliveIssue&&{keepAliveIssue:he.keepAliveIssue},...o.host&&{gridHost:o.host}};if(he.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(he.seleniumPerfMarks),delete he.seleniumPerfMarks),o.grid||o.gridId?(Xe.gridName=o.grid||((ap=o.gridData)==null?void 0:ap.name),Xe.gridType=(cp=o.gridData)==null?void 0:cp.type,Xe.gridProvider=(lp=o.gridData)==null?void 0:lp.provider):o.localTmaUrl?(Xe.gridName="local-tma-from-options",Xe.gridType="local-tma"):o.useLocalChromeDriver?(Xe.gridName="local-chrome-driver-from-options",Xe.gridType="local-chrome"):o.useChromeLauncher?(Xe.gridName="chrome-launcher-from-options",Xe.gridType="local-chrome"):o.browserstack?Xe.gridName="browserstack-from-options":o.saucelabs&&(Xe.gridName="saucelabs-from-options"),await t.testEndAndReport(kt,he,r,ha,Dn,Xe).catch(Db=>Yu.error("testEndAndReport threw an error",{err:Db})),Dn)return;v[he.resultId]=he,wf({executionId:r,projectId:h,testId:nt,resultId:he.resultId,result:he,ucid:b,companyId:w,companyName:I,projectName:O,companyPlan:R,source:C,user:k,lightweightMode:$,logger:Yu,isStartUp:M,projectType:D,appSource:ya}),l&&!he.success&&(y.stop(),d=!0),(Object.keys(v).length===S||d&&m===0)&&f(v)},de=(kt,nt)=>{v[nt.resultId]=nt,t.onTestIgnored(kt,nt.resultId),m--,(Object.keys(v).length===S||d&&m===0)&&f(v)},$t=(kt,nt)=>t.onGridSlot(kt,nt);o.userData={loginData:Object.assign({},Mt(),{refreshToken:wo(),authData:Mt(),token:g}),projectId:o.project,company:o.company,servicesUrl:me},L("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,r,J,Q,$t,de).forEach((kt,nt)=>{L("before schedule worker.run after createWorkers"),dS(()=>{L("right before worker.run"),kt.run()},nt)})});try{let g=await Kt(),f=await p(g);if(d)throw new Gt;return f}catch(g){throw Yu.error("failed running parallel workers",{executionId:r,err:g}),g}}}});async function Gy(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:te()}))]}:await Cc({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 Xu(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 Qu(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Wy.difference(Ns(s,e),t);if(r.length>0)throw lt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Wy,Vy=T(()=>{"use strict";Wy=E(require("lodash"));j();Xr();ye();z()});var Ln,b_,Zu,ep,ua,Hy=T(()=>{"use strict";Ln=E(require("lodash"));j();B();le();ce();Fe();ts();Cl();Hl();ye();Rt();At();$f();z();$y();Vy();({testRunStatus:b_,CLI_MODE:Zu}=Lt),ep=x("test-plan-runner"),ua=class{constructor(e){this.startTime=Date.now();this.workerManager=new la(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},d=Mt(),m=async()=>{let h=o.beforeParallel||1,y=!0,v=await this.workerManager.runTests(e,c,i,a,o,n,d,h,y);Object.assign(l,v)},p=async()=>{let h=zn||o.parallel,y=!1;L("right before this.workerManager.runTests");let v=await this.workerManager.runTests(t,c,i,a,o,n,d,h,y);L("right after this.workerManager.runTests"),Object.assign(l,v)},g=async()=>{let h=o.afterParallel||1,y=!1,v=await this.workerManager.runTests(r,c,i,a,o,n,d,h,y);Object.assign(l,v)};vf({executionId:i,projectId:o.project}),L("right before runBeforeTests");try{return await m(),L("right before runTestPlanTests"),await p(),L("right after runTestPlanTests"),await g(),l}catch(h){if(ep.error("error running test plan",{err:h}),h instanceof Gt)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await f()}async function f(){var y,v,S,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Zu.SELENIUM){let[{getSessionPlayer:w},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(be(),Yt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=w();await C.closeBatch(i,I);return}let h;try{if(!((b=(S=(v=o.company)==null?void 0:v.activePlan)==null?void 0:S.premiumFeatures)!=null&&b.applitools)||(h=await qc(o.project),Ln.default.isEmpty(h)||!i))return;let{runKey:w,url:I}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:w}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,c){var b,w,I;let l=te(),d=n.project;ka(l),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],p=new li(m,n,i,a),g=Ln.default.chain(m).map(C=>{var k;return((k=C.overrideTestConfig)==null?void 0:k.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:p.executionStart(l,d,this.startTime,o,h);L("before testListInfoPromise");let v=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||X.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,o,l,c,f),L("before runTestAllPhases");let S=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,n,l,o||"All Tests",p);return L("before executionEnd"),await p.executionEnd(l),L("after executionEnd"),{results:S,executionId:l,testPlanName:o,configName:f}}async runTestPlans(e,t){ep.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(d){return Ln.default.flattenDeep(Object.values(d)).reduce((m,p)=>m.concat(p.beforeTests,p.tests,p.afterTests),[])}let n={},o={},i=e.project,a=await Pc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Zu.APPIUM&&await Qu(e,r(l)),await ie(c,async d=>{var f;let m=d.testPlanId;n[m]={};let p=Object.assign({},e);p.baseUrl||=d.startUrl,p.appId||=((f=d.mobileApp)==null?void 0:f.appId)||void 0,p.gridId||=d.gridId,e.grid&&delete p.gridId,p.gridData=await ef(e,d);let g=p.overrideExecutionName||d.name;return await ie(l[m],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,p,g,m,t);X.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let v=Object.keys(n[m]).map(I=>({executionId:I,status:Xu(n[m][I])})),S=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,C)=>Object.assign(I,C),{}),b=Xu(S);Object.assign(o,S);let w=b?v[0].executionId:v.find(I=>!I.status).executionId;return await Ic(i,m,{success:b,executions:v,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var a;ep.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),L("before getSuite");let r=await Gy(e,t);if(L("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return L("Right before validateConfig + runAnonymousTestPlan tests map"),await ie(r.tests,async c=>{if(e.resultId){let d=c[0];d.resultId=e.resultId,c=[d]}e.mode!==Zu.APPIUM&&await Qu(e,c),L("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);return L("right after runTestPlan"),await X.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i),l})}async run(e){let t=ln(),r=[];Us(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Ln.default.flattenDeep(r);return L("right before onAllTestPlansFinished"),await X.onAllTestPlansFinished(n),L("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var Jy={};G(Jy,{init:()=>OS,run:()=>CS});async function fS(s){let e=s.project,t=await Oc(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"),tn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ps}function gS(s,e){var i,a,c,l,d,m;let t=ro(e.activePlan),r=s.parallel;if(t==="free"&&r>zy)throw new P(`The free plan allows only ${zy} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let p=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!p)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
408
|
+
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}let n=s.retentionDays;if(!n)return;let o=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function hS(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await fS(s)}catch(t){if([P,Ps].some(r=>t instanceof r))throw t;mS.error("could not validate cli account",{err:t})}}function yS(s){let e=Mt();return cm({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function bS(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(U.flags.useNewWSCLI.isEnabled()&&!e&&!t)return ft.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Ti(),Ng));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(wi(),Bg));r.init(s)}}function TS(s,e){let{branch:t,autoDetect:r}=s;if(nf(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function wS(s){let{project:e}=s,t=ln();Ky.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(s.sfdcCredential=await Sc({projectId:e,branch:t}))}function vS(s,e){let{onprem:t,id:r,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:m,extensionPath:p,ext:g,playerPath:f}=s;if([Y.SELENIUM].includes(m)&&!f)throw new P("in selenium on prem mode --player-path must be provided");if(m==="extension"&&!p&&!g)throw new P("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),d=ro(a);d==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<qy?qy:s.newBrowserWaitTimeout),U.setCompanyId(r),U.setIsPOC(c),U.setIsStartUp(l),U.setPlanType(d),xt.setPlanType(d),s.company={ucid:"",companyId:r,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:d,isPOC:c,isStartUp:l,activePlan:a}}function ES(s,e){if(kr){s.editorUrl=kr;return}s.editorUrl=e.editorUrl}function SS(s,e){s.allGrids=e}function RS(s,e){s.authData=e}function IS(s,e){let{id:t,name:r,type:n,defaults:o}=e;U.setProjectId(t),U.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function xS(s){s.gridData=await tf(s)}async function AS(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(lt("user-override-file",t),s.mockNetworkRules=await Yd(s.overrideMappingFile))}async function PS(s,e){L("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await km(),L("in runner.js after checkNpmVersion"),await hS(s),L("in runRunner before tunnel.connect"),await Go(s),L("in runRunner after tunnel.connect");let a=await new ua(e).run(s);return L("before tunnel.disconnect"),await Vo(s),await an.end(t),L("after tunnel.disconnect and gridService.keepAlive.end"),a}function kS(s){var e;xt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
408
409
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
409
410
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
410
|
-
`)}async function
|
|
411
|
-
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`),an.start(e),
|
|
411
|
+
`)}async function OS(s){var h,y,v;L("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o}=s,i=U.fetch(),a=bS(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{}),a.catch(()=>{});let{authData:c,editorConfig:l,companyByProjectId:d,projectById:m,branchName:p,allGrids:g}=await Qs(s);gS(s,d),await Promise.all([i,a]),L("after featureFlagsReady and socketConnected"),ES(s,l),vS(s,d),IS(s,m),TS(s,p),SS(s,g),RS(s,c),await wS(s),(h=s.lightweightMode)!=null&&h.disableLabs||await gi.loadLabFeatures(m.id,d.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(U.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((v=s.lightweightMode)==null?void 0:v.type)==="turboMode"&&console.log(`
|
|
412
|
+
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`),an.start(e),yS(e),await AS(s),await xS(s),kS(s);let f=ln();await X.setOptions(s,f)}var Ky,qy,zy,mS,CS,Yy=T(()=>{"use strict";Ky=E(require("lodash"));j();wl();Al();Fe();ts();Xr();Cl();ye();Rt();B();At();le();ce();z();Hy();yi();cu();Te();pn();rl();qy=30*60*1e3,zy=1,mS=x("runner");CS=PS});function Xy(s){s.get("/",(e,t)=>{let r=tp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Tl()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());pl({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var Qy=T(()=>{"use strict";Qr();rp();wl()});var sp,Zy,vs,pa,eb=T(()=>{"use strict";sp=E(require("chalk"));Rr();Zy=require("express");B();z();vs=x("cli-router"),pa=(0,Zy.Router)();pa.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!o||!i||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let m=await cs(t,r,n,o,i,a,c,l,d);m.success||(console.log(sp.default.red(m.result.resultValue)),vs.error("CLI Action Failure",{message:m.result.resultValue})),e.status(200).json({success:!0,data:m})}catch(m){vs.error("failed to run cli code",{err:m}),console.log(sp.default.red("failed to run cli code",m)),e.status(500).json({success:!1,code:"internal-error"})}});pa.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:o,stepResultId:i,timeout:a}=s.body;if(!t||typeof o!="object"||!r||typeof n!="number"||!i||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let c=await as(t,r,n,o,i,a);vs.info("installed packages successfully"),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof wt){vs.error("failed to install node packages",{err:c}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof re){vs.error("timeout installing node package"),e.status(200).json({success:!1,code:"timeout"});return}vs.error("failed to install node packages",{err:c}),e.status(500).json({success:!1,code:"internal-error"})}})});var _S,tb=T(()=>{"use strict";Rr();B();eb();_S=x("cli-service");Rg().catch(s=>_S.warn("failed to clean local package folder",{err:s}))});async function LS(s,e,t="utf8"){let r=nb.join(sb.tmpdir(),s);return await rb.promises.writeFile(r,e,t),r}async function MS(s){var t;let e=Date.now();try{let r=`
|
|
412
413
|
module.paths = ${JSON.stringify(module.paths)};
|
|
413
414
|
process.on('unhandledRejection', (error) => {
|
|
414
415
|
process.send({type: 'unhandledRejection', error: {message: error.message, stack: error.stack}});
|
|
@@ -418,13 +419,13 @@ Turbo mode will ignore step delays. Test artifacts like screenshots and logs wil
|
|
|
418
419
|
process.send({type: 'uncaughtException', error: {message: error.message, stack: error.stack}});
|
|
419
420
|
process.exit(1);
|
|
420
421
|
});
|
|
421
|
-
${
|
|
422
|
-
`,n=await
|
|
422
|
+
${s};
|
|
423
|
+
`,n=await LS(`tst-playground-${Date.now()}.js`,r),o=DS(n);Es[e]=o.child;let{error:i,exitCode:a}=await o;if(i)throw i;if(a!==0)throw new Error(`Process exited with exit code: ${a}`);return}finally{(t=Es[e])==null||t.kill(),delete Es[e]}}async function ib({code:s,type:e}){if(np.includes(e))return MS(s);throw new Nr}function ab(){Object.keys(Es).forEach(s=>{Es[s].kill(),delete Es[s]})}var rb,sb,nb,ob,np,Es,DS,cb=T(()=>{"use strict";rb=E(require("fs")),sb=E(require("os")),nb=E(require("path")),ob=require("child_process");z();np=["playwright","selenium","puppeteer"],Es={};DS=s=>{let e,t=new Promise(n=>{e=n}),r=(0,ob.fork)(s,{stdio:["inherit","inherit","inherit","ipc"]});return r.on("message",n=>{if(!n)return;let{type:o,error:i}=n;i&&["uncaughtException","unhandledRejection"].includes(o)&&e({error:new Ur(i.stack)})}),r.on("error",n=>{e({error:n})}),r.on("exit",n=>{e({exitCode:n})}),Object.assign(t,{child:r})}});var pb,da,db,lb,ub,NS,mb=T(()=>{"use strict";pb=require("express");B();z();le();cb();da=(0,pb.Router)(),db=x("playground-router"),lb=["localhost","app.testim.io","playground.testim.io","staging.testim.io","app.staging.testim.cc","tta-crm.tricentis.com"],ub=s=>{if(!s)return{};try{return new URL(s)}catch{return{}}},NS=(s,e,t)=>{if(Vn)return t();let{referer:r,origin:n}=s.headers;if(!r&&!n)return e.status(400).send();let o=ub(r),i=ub(n);return!lb.includes(o.hostname)&&!lb.includes(i.hostname)?e.status(400).send():t()};da.post("/run",NS,async(s,e)=>{let{code:t,type:r}=s.body;if(!t||!np.includes(r)){e.status(400).send({success:!1,reason:"missing arguments"});return}try{await ib({code:t,type:r}),e.send({success:!0})}catch(n){if(n instanceof Nr){e.status(404).send({success:!1});return}if(n instanceof Ur){e.json({success:!1,type:"playground-error",stack:n.innerStack});return}e.json({success:!1,reason:n.message}),db.error(n)}});da.post("/stop",(s,e)=>{try{ab(),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),db.error(t)}})});function gb(s){let e=(0,fb.Router)();return e.get("/cdp-url",(t,r)=>{if(!s){r.status(503).send({error:"Testim standalone browser is not running"});return}r.status(200).send({url:s.webdriverApi.cdpUrl})}),e.get("/status",(t,r)=>{if(!s){r.status(503).send({ok:!1});return}r.status(200).send({ok:!0})}),e}var fb,hb=T(()=>{"use strict";fb=require("express")});var wb={};G(wb,{orchestrateRoutes:()=>US});function US(s,e){let t=(0,bb.default)();s(t),t.use(op.default.urlencoded({extended:!1,limit:"50mb"})),t.use((0,Tb.default)()),t.use(op.default.json({limit:"50mb"}));let n={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Ce||Vn?"*":["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 t.use("*",(0,yb.default)(n)),Xy(t),t.use("/playground",da),t.use("/cliJs",pa),t.use("/standalone-browser",gb(e)),t.use((o,i)=>{i.status(404).send("Endpoint Not Found")}),t}var yb,bb,op,Tb,vb=T(()=>{"use strict";yb=E(require("cors")),bb=E(require("express")),op=E(require("body-parser")),Tb=E(require("compression"));Qy();tb();mb();hb();le()});var Sb={};G(Sb,{init:()=>FS});async function FS({agentPort:s,agentBind:e,project:t,token:r,installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i},a){await jS({installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i,project:t}),await BS({agentPort:s,agentBind:e,project:t,token:r},a)}async function BS({agentPort:s,agentBind:e,project:t,token:r},n){let{orchestrateRoutes:o}=await Promise.resolve().then(()=>(vb(),wb));return new Promise((i,a)=>{let c=()=>{};t&&($d(t,r),c=g=>{g.use((f,h,y)=>{Object.assign(f,{project:t}),y()})});let l=o(c,n),d=Eb.createServer(l);d.listen(s,e),d.on("error",m),d.on("listening",p);function m(g){if(g.syscall!=="listen")return a(g);switch(g.code){case"EACCES":case"EPERM":return a(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return a(new P(`Port ${s} is already in use, is another Testim instance running?`));default:return a(g)}}function p(){let{port:g}=d.address();console.log(`Running on port: ${g}`),$S()}})}function jS({installPlaygroundPlaywrightDeps:s,installPlaygroundPuppeteerDeps:e,installPlaygroundSeleniumDeps:t,project:r}){let n=[];return s&&n.push(Ee("playwright")),e&&n.push(Ee("puppeteer")),t&&n.push(Ee("selenium-webdriver"),gr({projectId:r})),Promise.all(n)}async function $S(){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 Eb,Rb=T(()=>{"use strict";Eb=E(require("http"));Rt();z();Tr();zr()});var Ob={};G(Ob,{getStartedWithStart:()=>tp,runAgentMode:()=>HS});async function HS(s){var r;let e;if(await hr(s.playerLocation,s.canary),s.startTestimBrowser){await KS();try{e=await zS(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new P('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(Rb(),Sb));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(Fu(),fe(yy)));let o=["webpack"];for(let i of o)await Ee(i,{silent:!0}).catch(()=>null)},6e3),t.init(s,e)}function tp(){return Cb}function Ib(s){try{return process.kill(s,0)}catch{return!1}}async function qS(s,e,t){let r=ar.join(Dt,`chrome-${zs}-process`),n=3e3,o=()=>{Ae.rmSync(r,{recursive:!0}),console.log(`
|
|
423
424
|
|
|
424
|
-
Browser session ended`),process.exit(0)};if(await ge(
|
|
425
|
-
`).map(o=>o.trim()),
|
|
426
|
-
`):""}overrideMimeType(t){if([Se.LOADING,Se.DONE].includes(this.readyState))throw new
|
|
427
|
-
${
|
|
425
|
+
Browser session ended`),process.exit(0)};if(await ge(r)){let g=JSON.parse(Ae.readFileSync(r));if(Ib(g.pid)){let f=()=>Ib(g.pid)?setTimeout(f,n):o();return f(),{webdriverApi:g}}}let i=await bo();await ge(Ss)||await Ae.promises.mkdir(Ss,{recursive:!0});let c=[...kb(Ss,e,t,i).desiredCapabilities.chromeOptions.args,...fa.Launcher.defaultFlags().filter(g=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(g))],l={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 fa.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Ss,chromePath:i,envVars:l}),p={port:m.port,pid:m.pid,cdpUrl:await mr(`localhost:${m.port}`)};return Ae.writeFileSync(r,JSON.stringify(p)),m.process.once("exit",o),m.process.once("close",o),{webdriverApi:p}}async function zS(s){let e=`${Ap}/extension/testim-full-master.zip`,t=ar.basename(e),r=ar.join(Dt,t),n=ar.join(Dt,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await ge(r)){let g=await Ae.promises.stat(r);o=Date.now()-GS>g.mtimeMs}if(await Ae.promises.mkdir(Dt,{recursive:!0}),o){let g=(0,Ab.default)("Downloading Testim Editor").start();await He(e,r);try{await Ze(r,n)}catch{await Ae.promises.rm(r,{recursive:!0,force:!0}),await He(e,r);try{await Ze(r,n)}catch{throw await Ae.promises.rm(r,{recursive:!0,force:!0}),g.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Ae.promises.rm(n,{recursive:!0,force:!0})}g.succeed()}let i=s.extensionPath?null:(await Ae.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await qS(s,i,n);await gr({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=kb(Ss,i,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(bn(),fe(yg)),{SeleniumPerfStats:l}=(ss(),fe(Mf)),d=new c;d.seleniumPerfStats=new l;let m=await d.initClient(a);Cb=!0;let p=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(p),Object.assign(d,{initialUrl:p});try{d.cdpUrl=await mr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function kb(s,e,t,r){let n=e?[e]:[],o=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&o.push(`--load-extension=${t}`),{logLevel:WS,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function KS(){if(await ge(ma))try{let{webSocketDebuggerUrl:s}=await JS();await YS(s),await Ae.promises.unlink(ma)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Ae.promises.unlink(ma)}}async function JS(){let s=await Ae.promises.readFile(ma,{encoding:"utf8"}),[e,t]=s.split(`
|
|
426
|
+
`).map(o=>o.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 mr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function YS(s,e=100){let t=await XS(s,e);return Vt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function XS(s,e=100){let t=new Pb.default(s,{timeout:e}),r=Vt(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=Vt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var xb,Ab,Pb,Ae,ar,fa,WS,GS,Ss,VS,ma,Cb,rp=T(()=>{"use strict";xb=E(require("ms")),Ab=E(require("ora")),Pb=E(require("ws")),Ae=E(require("fs")),ar=E(require("path")),fa=E(require("chrome-launcher"));le();zr();z();Tr();gc();j();WS=qn?"verbose":"silent",GS=(0,xb.default)("1h"),Ss=ar.join(Dt,"profile"),VS="DevToolsActivePort",ma=ar.join(Ss,VS);Cb=!1});var aL=require("source-map-support/register");Array.prototype.at||=function(s){let e=Number.isInteger(s)?s:0,t=e>=0?e:this.length+e;if(!(t<0||t>=this.length))return this[t]};var pp=require("perf_hooks");var Wn=E(require("os")),Is=E(require("url")),xs=E(require("http")),ba=E(require("https")),Nn=E(require("form-data")),Un=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 o of r)o==null||o.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},Fn=class extends Un{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(!(typeof t>"u"||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 o=0;o<t.byteLength;o++)r[o]=n[o];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,o=new Uint8Array(t.buffer);for(let i=0;i<t.byteLength;i++)r[i]=o[i+n];this._body=r}else if(typeof t=="object"&&t instanceof Nn.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()}},Rs=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}},Bn=class extends Error{},jn=class extends Error{},$n=class extends Error{},cr=class extends Error{},Se=class extends Un{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=xs.globalAgent;this.nodejsHttpsAgent=ba.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 (${Wn.type()} ${Wn.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Se.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new Fn(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){Se.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&&!Is.parse(r,!1,!0).protocol)throw new Bn("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new $n(`HTTP method ${t} is not allowed in XHR`);let o=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=o,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Se.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!==Se.OPENED)throw new cr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||/^sec-/.test(n)||/^proxy-/.test(n)||(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!==Se.OPENED)throw new cr("XHR readyState must be OPENED");if(this._request)throw new cr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new jn(`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
|
|
427
|
+
`):""}overrideMimeType(t){if([Se.LOADING,Se.DONE].includes(this.readyState))throw new cr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new Rs("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new jn("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,o=(this._url.protocol==="http:"?xs:ba).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 Nn.default&&t.pipe(o),this._request=o,this.timeout&&o.setTimeout(this.timeout,()=>this._onHttpTimeout(o)),o.on("response",i=>this._onHttpResponse(o,i)),o.on("error",()=>this._onHttpRequestError(o)),this.upload._startUpload(o),this._request===o&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof Nn.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",o=>this._onHttpResponseData(r,o)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=xs.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(Se.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Se.LOADING&&this._setReadyState(Se.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Se.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(Se.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Se.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Se.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new Rs(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,o,i=this.nodejsBaseUrl===null?t:Is.resolve(this.nodejsBaseUrl,t),a=Is.parse(i,!1,!0);return a.hash=null,a.auth&&(typeof o<"u"&&o!==null||typeof n<"u"&&n!==null)&&(r=a.auth.indexOf(":"),r===-1?o||(o=a.auth):(o||(o=a.substring(0,r)),n||(n=a.substring(r+1)))),(o||n)&&(a.auth=`${o}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let o=r.toLowerCase();this._privateHeaders[o]||(this._mimeOverride!==null&&o==="content-type"&&(n=this._mimeOverride),this._responseHeaders[o]=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 o=0;o<t.length;o++)n[o]=t[o];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"}},Pe=Se;Pe.SyntaxError=Bn,Pe.ProgressEvent=Rs,Pe.SecurityError=$n,Pe.XMLHttpRequest=Se,Pe.InvalidStateError=cr,Pe.XMLHttpRequestUpload=Fn,Pe.UNSENT=0,Pe.OPENED=1,Pe.HEADERS_RECEIVED=2,Pe.LOADING=3,Pe.DONE=4;Object.assign(global,{xhr2:Pe,XMLHttpRequest:Pe,performance:pp.performance,...typeof Blob>"u"&&{Blob:require("buffer").Blob}});var _b=E(require("semver"));Fe();rl();qt();zr();var ip=E(require("chalk")),Lb=require("events");ce();en();z();ce();vo();B();var Zd=E(require("os")),sl=E(require("path")),nl=E(require("chalk")),Co=require("fs");le();function em(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=Zd.homedir();(0,Co.mkdirSync)(sl.resolve(n,".testim_logs"),{recursive:!0});let o=sl.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(` ${o}`),Ep&&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(i=>i.includes("player-require-path"))&&(console.log(nl.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(nl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Co.writeFileSync)(o,`${s}
|
|
428
|
+
${s==null?void 0:s.stack}
|
|
428
429
|
|
|
429
|
-
${JSON.stringify(
|
|
430
|
+
${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Gs();var aw=x("process-handler"),tm=!1;function cw(s){return s instanceof Error?1:tm?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:o})=>[t,o].includes(pe.SKIPPED)||[t,o].includes(pe.FAILED)&&n===qe.EVALUATING?!1:r!==!0)?1:0)}function lw(){try{zt("chromedriver").stop()}catch{}}function rm(){tm=!0}async function ol(s){s!=null&&s.stack&&(Kr?console.error(s,s.stack):em(s)),lw(),await aw.waitForFlush(),process.exit(cw(s))}ye();B();var QS=x("cli-entry");function ZS(s){if(!_b.satisfies(process.version,s))throw new P(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=16,t=18,r=Number(process.versions.node.split(".")[0]),n=new Date("2023-09-11T00:00:00.000Z"),o=n<=new Date,i=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new P(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&o)throw new P(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(ip.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${i}. please upgrade to a newer Node.js version.`))}async function eR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(j(),K)),Promise.resolve().then(()=>(vm(),wm))]);L("Starting Testim.io CLI"),Qd(ol);try{ZS(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{let t=await e.process();if(L("in main, after options.process"),_a(global.proxyUri),"parallel"in t&&t.parallel>5&&(Lb.EventEmitter.defaultMaxListeners=t.parallel*2),Oa(t.project),bd("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(Tr(),Im));return await o()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await fd(),await Qs(t);let{preloadTests:o}=await Promise.resolve().then(()=>(Mo(),Am));await o(t),!t.playerRequirePath&&t.mode!==Y.EXTENSION&&await hr(t.playerLocation,t.canary);let i=await hd();i.success?console.log(`created prefetched data at ${co()}`):console.error("failed to create prefetch data",i.error);return}let r=await Promise.resolve().then(()=>(Yy(),Jy));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(Al(),xl));await o(t);return}if(s.isAgentMode(t)){let{runAgentMode:o}=await Promise.resolve().then(()=>(rp(),Ob));return o(t)}if(t.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(Jl(),Bf)),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&rm(),L("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([Jd(t),r.init(t)]);return L("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof Lr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Yc({...r,error:t.message}).catch(()=>{}),t instanceof P?(console.log(ip.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),QS.error("runner ended with unexpected error",{err:t}),t)}}eR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),ol(s)});
|
|
430
431
|
//# sourceMappingURL=cli.js.map
|