@testim/testim-cli 4.53.0-beta.0 → 4.53.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 +16 -16
- package/cli.js.map +3 -3
- package/npm-shrinkwrap.json +20056 -7
- package/package.json +7 -13
package/cli.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var Zb=Object.create;var Un=Object.defineProperty;var eT=Object.getOwnPropertyDescriptor;var tT=Object.getOwnPropertyNames;var rT=Object.getPrototypeOf,sT=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>{for(var t in e)Un(s,t,{get:e[t],enumerable:!0})},Sp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of tT(e))!sT.call(s,n)&&n!==t&&Un(s,n,{get:()=>e[n],enumerable:!(r=eT(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?Zb(rT(s)):{},Sp(e||!s||!s.__esModule?Un(t,"default",{value:s,enumerable:!0}):t,s)),he=s=>Sp(Un({},"__esModule",{value:!0}),s);var Fe={};V(Fe,{log:()=>N,measure:()=>oT});function N(...s){if(!xp)return;let e=Date.now();console.log(`${e-nT} ${e-Rp} `,...s),Rp=e}function oT(s,e){if(!xp)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var xp,nT,Rp,Be=w(()=>{"use strict";xp=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,nT=Date.now(),Rp=Date.now()});var va,Ht,Ea,Or=w(()=>{"use strict";va={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"},Ht="element-6066-11e4-a52e-4f735466cecf",Ea=79});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function He(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 Sa(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function je(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var Ia=w(()=>{"use strict"});var xa,Ap,Cp,Hn=w(()=>{xa={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"},Ap={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29",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",
|
|
3
|
-
${l.msg}`));for(let u of lT)a[u]instanceof Error&&(l[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(l).length>0&&(i&&!m&&(l.msg=i),d.text=l),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Lr.options=t}}});var Na={};V(Na,{getLogger:()=>A,setExecutionId:()=>La,setProjectId:()=>Da,setProxyUri:()=>Ma});function dT(){let s=[],e=()=>Promise.resolve();if(!ke){let{CoralogixTransport:t}=(ka(),he(Pa));t.configure(sd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return Lp&&s.push(new Tt.transports.Console({format:Tt.format.combine(Tt.format.colorize(),Tt.format.simple())})),[s,e]}function La(s){Oa=s}function Da(s){nd=s}function Ma(s){if(ke||!s)return;let{CoralogixTransport:e}=(ka(),he(Pa));e.configure({...sd,proxyUri:s})}function td(s){return{projectId:nd,time:new Date().toISOString(),...Oa&&!s&&{executionId:Oa}}}function A(s){return new _a(yT.child({category:s}))}var rd,Tt,uT,pT,sd,mT,fT,gT,hT,yT,Oa,nd,_a,j=w(()=>{"use strict";rd=E(require("os")),Tt=E(require("winston"));le();B();uT=rd.hostname(),pT=lt(),sd={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[mT,fT]=dT(),gT=Dp?"debug":"info",hT={release:Boolean(!0),branch:"production"},yT=Tt.createLogger({levels:Tt.config.syslog.levels,level:gT,transports:mT,defaultMeta:{name:"runner",hostname:uT,nodeVersion:process.version,runnerVersion:pT,...hT}}),Oa=null,nd=null;_a=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},td(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},td(n)))}catch{}}}waitForFlush(){return fT()}}});var Qn,Dr,C,qt,pr,wt,Yn,Mr,se,ks,vt,Nr,Et,Xn,Ur,Fr,Br,Os,z=w(()=>{"use strict";Qn=require("p-retry"),Dr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},pr=class extends Error{constructor(t,r){super(t);this.type=r}},wt=class extends Qn.AbortError{},Yn=class extends Qn.AbortError{},Mr=class extends Qn.AbortError{},se=class extends Error{},ks=class extends Error{},vt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Nr=class extends vt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Et=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Xn=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Ur=class extends Error{},Fr=class extends Error{constructor(t){super();this.innerStack=t}},Br=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Os=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Ua(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ne(s){return(0,ad.setTimeout)(s)}function Fa(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){zn&&!od&&(od=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new se(t);return e=zn?Number(zn)||6e5:e,Promise.race([s,ne(e).then(()=>{throw r})])}async function ae(s,e,{concurrency:t}={}){if(t){id||=(await import("p-limit")).default;let r=id(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function zt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var ad,od,id,Ba=w(()=>{"use strict";ad=require("timers/promises");z();le();od=!1});var Ls,cd,bT,_s,ld,TT,wT,ud,pd=w(()=>{"use strict";Ls=E(require("lodash"));le();cd=require("dns");j();Ba();bT=A("http-request-counters"),_s=!1,ld=async()=>{if(ke)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ae(s,t=>cd.promises.lookup(t)));return e||(_s=!0),e}catch{return bT.error("network connectivity test failed"),_s=!0,!1}},TT=Ls.throttle(ld,10*1e3),wT=60*1e3*15,ud=()=>{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)},wT)}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),_s||TT(),a}}}async function r(){if(_s||!await ld())return!1;let n=Ls.sum([...s.fail.values()]),o=Ls.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>_s,t}});var et={};V(et,{deleteFullRes:()=>RT,deleteReq:()=>Ds,didNetworkConnectivityTestFail:()=>za,download:()=>Ha,get:()=>Re,getFullRes:()=>AT,getText:()=>Ns,head:()=>CT,isNetworkHealthy:()=>qa,post:()=>We,postForm:()=>Ms,postFullRes:()=>xT,postText:()=>Va,put:()=>Ga});function ET(){return global.caFileContent}function ST(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function IT(){return!St.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(St.default),global.proxyUri}function dr(s,e=!1){let t=ET();t&&s.ca(t);let r=!e&&IT();r&&s.proxy(r)}async function dd(s,e={},t={},r=jr){let n=St.default.delete(s).send(e).timeout(r).set(t);return dr(n),await n}async function $a(s,e,t={},r=jr,n=0){let o=St.default.post(s).send(e).timeout(r).set(t);dr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function Wa(s,e,t={},r=jr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=St.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),dr(i,o),await i}var St,ja,$e,jr,vT,_t,Ds,RT,We,xT,Ms,Ns,Va,Re,AT,CT,Ga,Ha,qa,za,qe=w(()=>{"use strict";St=E(require("superagent"));j();pd();ja=A("http-request"),$e=ud(),jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,vT=6e4;_t=(s,e,t)=>{throw ja.error(s,{...t,error:e}),e};Ds=$e(async(s,e,t,r)=>{try{let n=await dd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return _t("failed to delete request",n,{url:s})}});RT=$e(dd),We=$e(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await $a(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return _t("failed to post request",o,{url:s})}});xT=$e($a),Ms=$e(async(s,e,t,r={},n=jr)=>{let o=St.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)}),dr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return _t("failed to post request",i,{url:s})}});Ns=$e(async(s,e,t)=>{try{return(await Wa(s,e,t)).text}catch(r){return _t("failed to getText request",r,{url:s,query:e})}}),Va=$e(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await $a(s,e,t,r,n)).text}catch(o){return _t("failed to post request",o,{url:s})}}),Re=$e(async(s,e,t,r,n)=>{try{return(await Wa(s,e,t,r,n)).body}catch(o){return _t("failed to get request",o,{url:s,query:e})}}),AT=$e((s,e,t,r)=>Wa(s,e,t,r)),CT=$e(async s=>{let e=St.default.head(s).timeout(jr);dr(e);try{return await e}catch(t){return _t("failed to head request",t,{url:s})}}),Ga=$e(async(s,e,t={},r=jr)=>{let n=St.default.put(s).send(e).timeout(r).set(t);dr(n);try{return(await n).body}catch(o){return _t("failed to put request",o,{url:s})}}),Ha=$e(async s=>{ja.info("start to download",{url:s});let e=St.default.get(s).timeout(vT).buffer(!0).parse(ST);dr(e);try{let t=await e;return ja.info("finished to download",{url:s}),t}catch(t){return _t("failed to download",t,{url:s})}}),qa=$e.isNetworkHealthy,za=$e.didNetworkConnectivityTestFail});function ut(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Lt.resolve(__dirname,"../../"):s=Lt.resolve(__dirname,""),s):process.cwd()}function Zn(s,e){return je(s)?e||Lt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Lt.basename(s)}function lt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function kT(){try{return Cp.node}catch{return""}}async function gd(s,e,t=!0){let r=await It.promises.readdir(s,{withFileTypes:!0});await It.promises.mkdir(e,{recursive:t});for(let n of r){let o=Lt.join(s,n.name),i=Lt.join(e,n.name);n.isDirectory()?await gd(o,i):await It.promises.copyFile(o,i)}}async function fe(s){try{return await It.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Lt,md,fd,It,PT,Dt,ze,eo,Ka,tt,Ja,hd=w(()=>{"use strict";Lt=E(require("path"));Ia();Hn();md=E(require("p-retry")),fd=E(require("decompress")),It=require("fs"),PT=3;Dt=async s=>{let e=await Promise.resolve().then(()=>(qe(),et));return(0,md.default)(()=>e.download(s),{retries:PT,factor:1})},ze=async(s,e)=>{let t=await Dt(s);return It.promises.writeFile(e,t.body)};eo=async(s,e)=>{let t=Zn(s,e);return je(s)?ze(s,t):It.promises.copyFile(s,t)},Ka=async s=>je(s)?Dt(s):It.promises.readFile(s),tt=async(s,e)=>await(0,fd.default)(s,e),Ja=s=>(0,It.statSync)(s).size/1e6});var Mt={};V(Mt,{APPIUM_SESSION_MESSAGE:()=>ec,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>to,MOBILE_RUN_SKIP_REASON:()=>Za,gridMessages:()=>$r,gridTypes:()=>O,mobileWeb:()=>Xa,runnerStatus:()=>Ya,runnerTestStatus:()=>pe,socketEventTypes:()=>Rt,stepResult:()=>Fs,test:()=>Qa,testRunStatus:()=>Us,testStatus:()=>Ke,timeoutMessages:()=>Ve});var Ve,Us,Ya,pe,Ke,$r,Xa,Qa,Rt,Y,O,Fs,to,Za,ec,ie=w(()=>{"use strict";Ve={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Us={COMPLETED:"completed",RUNNING:"running"},Ya={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"},Ke={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"},Xa={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Qa={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Rt={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"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Fs={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"},Za={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},ec={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 Bs(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 OT(){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 js,yd,Je,_T,LT,DT,MT,NT,tc,rc,bd=w(()=>{"use strict";ie();js=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},yd=s=>Boolean(s.resultId&&s.source==="remote-run"),Je=(s,e)=>s.testStatus===Ke.QUARANTINE&&!yd(e)&&!e.runQuarantinedTests;_T=s=>Boolean(s.loginMode),LT=s=>Boolean(s.tunnelOnlyMode),DT=s=>Boolean(s.createPrefechedData),MT=s=>Boolean(s.installLazyDepsMode),NT=s=>Boolean(s.agentMode),tc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},rc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function so(s=0){return ro.default.duration(s).format("HH:mm:ss.SSS")}function sc(s=0){return ro.default.duration(s).asSeconds()}var ro,Td,wd=w(()=>{"use strict";ro=E(require("dayjs")),Td=E(require("dayjs/plugin/duration"));ro.default.extend(Td.default)});var $s,Wr,Ws,vd,Vr,Ed=w(()=>{"use strict";ie();$s=s=>!(!s||"fileName"in s),Wr=(s,e)=>e===O.TESTIM_TVC?!1:s&&"fileName"in s?s.fileName.endsWith(".app"):!1,Ws=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},vd=s=>s===O.TESTIM_TVC,Vr=(s,e)=>vd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function nc(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var Sd=w(()=>{"use strict"});var K={};V(K,{TESTIM_BROWSER_DIR:()=>Nt,buildBasicHeader:()=>Sa,calcPercentile:()=>io,copyDir:()=>gd,delay:()=>ne,doesPathExist:()=>fe,download:()=>Dt,downloadAndSave:()=>ze,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>OT,getBrowserInfo:()=>FT,getCdpAddressForHost:()=>gr,getCliLocation:()=>ut,getDuration:()=>so,getDurationSec:()=>sc,getEnginesVersion:()=>kT,getEnvironmentGitBranch:()=>fr,getLocalFileSizeInMB:()=>Ja,getMemorySnapshot:()=>nc,getPlanType:()=>oo,getRunConfigByBrowserName:()=>Gs,getRunnerVersion:()=>lt,getSource:()=>eo,getSourceAsBuffer:()=>Ka,getSourcePath:()=>Zn,getTestUrl:()=>He,getUniqBrowsers:()=>Bs,groupTestsByRetries:()=>ic,guid:()=>re,hasTestPlanFlag:()=>js,isAgentMode:()=>NT,isAppFromDevice:()=>$s,isAppFromDeviceDisabled:()=>Vr,isCreatePrefetchedDataMode:()=>DT,isInstallLazyDepsMode:()=>MT,isLoginMode:()=>_T,isMobileProject:()=>Ws,isPromise:()=>Ua,isQuarantineAndNotRemoteRun:()=>Je,isRemoteRun:()=>yd,isTestimVirtualGrid:()=>vd,isTunnelOnlyMode:()=>LT,isURL:()=>je,promiseAbort:()=>Fa,promiseFromCallback:()=>zt,promiseMap:()=>ae,promiseTimeout:()=>ce,removePropertyFromObject:()=>no,replaceArgsWithNoDashes:()=>tc,shouldBlockVirtualIosBuild:()=>Wr,spreadObjectToArgs:()=>rc,unzipFile:()=>tt});function FT(s){return s=s.toLowerCase(),oc.find(e=>e.browserValue===s)}function Gs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=oc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||oc[0],n=Vs.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=Vs.find(o=>o.sl.platform===e.platform):e.platformName&&(n=Vs.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=Vs.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=Vs.find(o=>o.bs.platform===t.platform))),mr.merge(r,n)}function fr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function no(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&no(s[r],e,t))}function _e(s){return s.ELEMENT||s[Ht]}function oo(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function ic(s=[]){return mr.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=mr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=mr.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function gr(s,e){let t=await Promise.resolve().then(()=>(qe(),et));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 Id,mr,Rd,UT,Nt,Vs,oc,io,B=w(()=>{"use strict";Id=E(require("os")),mr=E(require("lodash")),Rd=E(require("path"));Or();hd();bd();wd();Ia();Ba();Ed();Sd();UT=Id.homedir(),Nt=Rd.join(UT,".testim-browser-profile"),Vs=[{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"}}],oc=[{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"}];io=(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 ac={};V(ac,{$schema:()=>BT,default:()=>GT,definitions:()=>jT,properties:()=>VT,required:()=>WT,type:()=>$T});var BT,jT,$T,WT,VT,GT,xd=w(()=>{BT="http://json-schema.org/draft-07/schema#",jT={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}}}},$T="object",WT=["entries"],VT={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},GT={$schema:BT,definitions:jT,type:$T,required:WT,properties:VT}});async function Ld(){try{return await ce(ao.promises.readFile(po()).then(async s=>{let e=await _d;return zT(e,s)}),3e4)}catch{return{}}}function zT(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Hr.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 pt(s,e,t=HT,r=void 0){return async()=>{if(!Pd)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await KT(e);if(o)return Hs.debug("cache hit:",{fnName:e}),o;if(Hs.debug("cache miss:",{fnName:e}),!kd)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 JT(e,i,t),i}}async function KT(s){let t=(await mo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function JT(s,e,t){if(cc)throw Hs.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 mo;r[s]={value:e,expiry:Date.now()+t},Od=new Promise(n=>{uo=n}),qT(r)}catch{Hs.error("failed updating cache")}}async function qr(){let s=await mo;Object.keys(s).forEach(e=>{delete s[e]})}function Dd(s){Pd=s}function YT(s=!0){kd=s}async function Md(){try{return cc=!0,await Od}finally{cc=!1}}function Nd(s){lo=s,mo=Ld()}var ao,co,Hr,Ad,Hs,lo,Cd,uo,Pd,kd,cc,Od,_d,HT,po,mo,qT,Ud,Fd,oR,Bd,Ut=w(()=>{"use strict";ao=E(require("fs")),co=E(require("path")),Hr=E(require("crypto"));B();Ad=require("lodash");j();Hs=A("local cache"),lo=co.resolve(ut(),"testim-cache"),Pd=!0,kd=!0,cc=!1,Od=new Promise(s=>{uo=s}),_d=new Promise(s=>{Cd=s}),HT=1e3*60*60*3,po=()=>co.resolve(co.resolve(lo,"testim.cache"));mo=Ld(),qT=(0,Ad.debounce)(async s=>{let e;try{let t=await _d,r=Hr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Hr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await fe(lo)||await ao.promises.mkdir(lo,{recursive:!0}),await ao.promises.writeFile(po(),a)}catch(t){Hs.error("failed saving cache",{err:t}),e=t}uo(e?{success:!1,error:e}:{success:!0})},200);Ud=Cd,Fd=Dd.bind(void 0,!1),oR=Dd.bind(void 0,!0),Bd=()=>YT(!1)});function fo(){return{cliLocation:ut(),userInfo:zr.userInfo(),platform:zr.platform(),release:zr.release()}}var zr,lc=w(()=>{"use strict";zr=E(require("os"));B()});function XT(s){try{return go.resolve(go.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 Jt(s){let e=XT(s);return require(e)}var go,qs=w(()=>{"use strict";go=E(require("path"))});async function Vd(s){return(await $d(`npm view ${s} version`)).stdout.trim()}function pc(s){try{return Jt(s)}catch{return!1}}function Gd(s,e){return require(Kr.join(s,`./node_modules/${e}/package.json`)).version}async function yo(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=Kr.join(s,"npm-shrinkwrap.json"),i=Kr.join(s,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await fe(o)&&(await uc.promises.rename(o,i),a=!0)}catch{}return await $d(`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?(Wd.info("Failed to install package due to insufficient write access",{...fo(),package:e,path:l||s}),console.error(`
|
|
2
|
+
"use strict";var Zb=Object.create;var Un=Object.defineProperty;var eT=Object.getOwnPropertyDescriptor;var tT=Object.getOwnPropertyNames;var rT=Object.getPrototypeOf,sT=Object.prototype.hasOwnProperty;var w=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>{for(var t in e)Un(s,t,{get:e[t],enumerable:!0})},Sp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of tT(e))!sT.call(s,n)&&n!==t&&Un(s,n,{get:()=>e[n],enumerable:!(r=eT(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?Zb(rT(s)):{},Sp(e||!s||!s.__esModule?Un(t,"default",{value:s,enumerable:!0}):t,s)),he=s=>Sp(Un({},"__esModule",{value:!0}),s);var Fe={};V(Fe,{log:()=>N,measure:()=>oT});function N(...s){if(!xp)return;let e=Date.now();console.log(`${e-nT} ${e-Rp} `,...s),Rp=e}function oT(s,e){if(!xp)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var xp,nT,Rp,Be=w(()=>{"use strict";xp=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,nT=Date.now(),Rp=Date.now()});var va,Ht,Ea,Or=w(()=>{"use strict";va={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"},Ht="element-6066-11e4-a52e-4f735466cecf",Ea=79});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function He(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 Sa(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function je(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var Ia=w(()=>{"use strict"});var xa,Ap,Cp,Hn=w(()=>{xa={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"},Ap={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","coralogix-logger":"1.1.28","@types/unzip-stream":"0.3.2",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.22.10",jsonwebtoken:"9.0.0",linkedom:"0.15.3",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"8.19.2","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","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","unzip-stream":"0.3.1","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.6.2",yaml:"2.2.2"},Cp={node:">= 16.0.0"}});var Cs,Pp,kp,qn,Op,zn,Ps,_p,me,Lp,Dp,Kn,ke,Aa,Mp,Jn,Np,OI,Up,_I,Fp,Bp,_r,jp,$p,Wp,Vp,Gp,Hp,qp,zp,Kp,Jp,Yp,Xp,Qp,Ca,Zp,le=w(()=>{"use strict";Cs=process.env.SERVICES_HOST||"https://services.testim.io",Pp="https://testimstatic.blob.core.windows.net",kp="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:Cs,Cs=process.env.SERVICES_HOST);qn=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Op=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),zn=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ps=process.env.EDITOR_URL,_p=process.env.WEBSOCKET_HOST||`${Cs}/ws`,me=Cs,Lp=parseInt(process.env.LOGGER_CONSOLE||"0",10),Dp=parseInt(process.env.LOGGER_DEBUG||"0",10),Kn=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),ke=parseInt(process.env.IS_ON_PREM||"0",10),Aa=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Mp=parseInt(process.env.DEBUG_MODE||"0",10),Jn=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Np=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",OI=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Up=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),_I=process.env.APPIUM_VERSION||"1.10.1",Fp=process.env.GATEWAY_URL,Bp=process.env.EXTENSION_SERVICES_HOST||Cs,_r=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Pp,jp=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:kp,$p=Pp,Wp=kp,Vp=5*60*1e3,Gp=40,Hp=process.env.HEADSPIN_MOBILE_DEVICES_API_URL||"https://api-dev.headspin.io/v0",qp=process.env.HEADSPIN_MOBILE_APPS_API_URL||"https://api-dev.headspin.io/v1",zp=process.env.TDC_MOBILE_DEVICES_API_URL||"https://api.tdc.tricentis-cloud.com/v0",Kp=process.env.TDC_MOBILE_APPS_API_URL||"https://api.tdc.tricentis-cloud.com/v1",Jp=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Yp=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Xp=process.env.SAUCE_LABS_US_APPS_API_URL||"https://api.us-west-1.saucelabs.com/v1",Qp=process.env.SAUCE_LABS_EU_APPS_API_URL||"https://api.eu-central-1.saucelabs.com/v1",Ca=process.env.P_CLOUDY_MOBILE_API_URL||"https://device.pcloudy.com/api",Zp=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api"});var Pa={};V(Pa,{CoralogixTransport:()=>Lr});var Ie,ed,cT,lT,Lr,ka=w(()=>{"use strict";Ie=require("coralogix-logger"),ed=E(require("winston-transport")),cT={debug:Ie.Severity.debug,silly:Ie.Severity.verbose,verbose:Ie.Severity.verbose,silent:Ie.Severity.verbose,info:Ie.Severity.info,http:Ie.Severity.info,warn:Ie.Severity.warning,warning:Ie.Severity.warning,error:Ie.Severity.error,critical:Ie.Severity.critical,crit:Ie.Severity.critical},lT=["err","error","reason","e"],Lr=class extends ed.default{constructor(t){t=Object.assign({},Lr.options,t);super(t);this.options=t,this.logger=new Ie.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:o,message:i,meta:a={},...c}=t,l=Object.assign({},a,this.options.extraFields,c),d=new Ie.Log;d.severity=cT[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 u of lT)a[u]instanceof Error&&(l[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(l).length>0&&(i&&!m&&(l.msg=i),d.text=l),this.logger.addLog(d),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Lr.options=t}}});var Na={};V(Na,{getLogger:()=>A,setExecutionId:()=>La,setProjectId:()=>Da,setProxyUri:()=>Ma});function dT(){let s=[],e=()=>Promise.resolve();if(!ke){let{CoralogixTransport:t}=(ka(),he(Pa));t.configure(sd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return Lp&&s.push(new wt.transports.Console({format:wt.format.combine(wt.format.colorize(),wt.format.simple())})),[s,e]}function La(s){Oa=s}function Da(s){nd=s}function Ma(s){if(ke||!s)return;let{CoralogixTransport:e}=(ka(),he(Pa));e.configure({...sd,proxyUri:s})}function td(s){return{projectId:nd,time:new Date().toISOString(),...Oa&&!s&&{executionId:Oa}}}function A(s){return new _a(yT.child({category:s}))}var rd,wt,uT,pT,sd,mT,fT,gT,hT,yT,Oa,nd,_a,j=w(()=>{"use strict";rd=E(require("os")),wt=E(require("winston"));le();B();uT=rd.hostname(),pT=ut(),sd={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[mT,fT]=dT(),gT=Dp?"debug":"info",hT={release:Boolean(!0),branch:"production"},yT=wt.createLogger({levels:wt.config.syslog.levels,level:gT,transports:mT,defaultMeta:{name:"runner",hostname:uT,nodeVersion:process.version,runnerVersion:pT,...hT}}),Oa=null,nd=null;_a=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},td(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},td(n)))}catch{}}}waitForFlush(){return fT()}}});var Qn,Dr,C,qt,pr,vt,Yn,Mr,se,ks,Et,Nr,St,Xn,Ur,Fr,Br,Os,z=w(()=>{"use strict";Qn=require("p-retry"),Dr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},pr=class extends Error{constructor(t,r){super(t);this.type=r}},vt=class extends Qn.AbortError{},Yn=class extends Qn.AbortError{},Mr=class extends Qn.AbortError{},se=class extends Error{},ks=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"}},Ur=class extends Error{},Fr=class extends Error{constructor(t){super();this.innerStack=t}},Br=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Os=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Ua(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ne(s){return(0,ad.setTimeout)(s)}function Fa(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){zn&&!od&&(od=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new se(t);return e=zn?Number(zn)||6e5:e,Promise.race([s,ne(e).then(()=>{throw r})])}async function ae(s,e,{concurrency:t}={}){if(t){id||=(await import("p-limit")).default;let r=id(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function zt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var ad,od,id,Ba=w(()=>{"use strict";ad=require("timers/promises");z();le();od=!1});var Ls,cd,bT,_s,ld,TT,wT,ud,pd=w(()=>{"use strict";Ls=E(require("lodash"));le();cd=require("dns");j();Ba();bT=A("http-request-counters"),_s=!1,ld=async()=>{if(ke)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ae(s,t=>cd.promises.lookup(t)));return e||(_s=!0),e}catch{return bT.error("network connectivity test failed"),_s=!0,!1}},TT=Ls.throttle(ld,10*1e3),wT=60*1e3*15,ud=()=>{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)},wT)}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),_s||TT(),a}}}async function r(){if(_s||!await ld())return!1;let n=Ls.sum([...s.fail.values()]),o=Ls.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>_s,t}});var et={};V(et,{deleteFullRes:()=>RT,deleteReq:()=>Ds,didNetworkConnectivityTestFail:()=>za,download:()=>Ha,get:()=>Re,getFullRes:()=>AT,getText:()=>Ns,head:()=>CT,isNetworkHealthy:()=>qa,post:()=>We,postForm:()=>Ms,postFullRes:()=>xT,postText:()=>Va,put:()=>Ga});function ET(){return global.caFileContent}function ST(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function IT(){return!It.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(It.default),global.proxyUri}function dr(s,e=!1){let t=ET();t&&s.ca(t);let r=!e&&IT();r&&s.proxy(r)}async function dd(s,e={},t={},r=jr){let n=It.default.delete(s).send(e).timeout(r).set(t);return dr(n),await n}async function $a(s,e,t={},r=jr,n=0){let o=It.default.post(s).send(e).timeout(r).set(t);dr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function Wa(s,e,t={},r=jr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=It.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),dr(i,o),await i}var It,ja,$e,jr,vT,_t,Ds,RT,We,xT,Ms,Ns,Va,Re,AT,CT,Ga,Ha,qa,za,qe=w(()=>{"use strict";It=E(require("superagent"));j();pd();ja=A("http-request"),$e=ud(),jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,vT=6e4;_t=(s,e,t)=>{throw ja.error(s,{...t,error:e}),e};Ds=$e(async(s,e,t,r)=>{try{let n=await dd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return _t("failed to delete request",n,{url:s})}});RT=$e(dd),We=$e(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await $a(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return _t("failed to post request",o,{url:s})}});xT=$e($a),Ms=$e(async(s,e,t,r={},n=jr)=>{let o=It.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)}),dr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return _t("failed to post request",i,{url:s})}});Ns=$e(async(s,e,t)=>{try{return(await Wa(s,e,t)).text}catch(r){return _t("failed to getText request",r,{url:s,query:e})}}),Va=$e(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await $a(s,e,t,r,n)).text}catch(o){return _t("failed to post request",o,{url:s})}}),Re=$e(async(s,e,t,r,n)=>{try{return(await Wa(s,e,t,r,n)).body}catch(o){return _t("failed to get request",o,{url:s,query:e})}}),AT=$e((s,e,t,r)=>Wa(s,e,t,r)),CT=$e(async s=>{let e=It.default.head(s).timeout(jr);dr(e);try{return await e}catch(t){return _t("failed to head request",t,{url:s})}}),Ga=$e(async(s,e,t={},r=jr)=>{let n=It.default.put(s).send(e).timeout(r).set(t);dr(n);try{return(await n).body}catch(o){return _t("failed to put request",o,{url:s})}}),Ha=$e(async s=>{ja.info("start to download",{url:s});let e=It.default.get(s).timeout(vT).buffer(!0).parse(ST);dr(e);try{let t=await e;return ja.info("finished to download",{url:s}),t}catch(t){return _t("failed to download",t,{url:s})}}),qa=$e.isNetworkHealthy,za=$e.didNetworkConnectivityTestFail});function pt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Lt.resolve(__dirname,"../../"):s=Lt.resolve(__dirname,""),s):process.cwd()}function Zn(s,e){return je(s)?e||Lt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Lt.basename(s)}function ut(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function kT(){try{return Cp.node}catch{return""}}async function gd(s,e,t=!0){let r=await tt.promises.readdir(s,{withFileTypes:!0});await tt.promises.mkdir(e,{recursive:t});for(let n of r){let o=Lt.join(s,n.name),i=Lt.join(e,n.name);n.isDirectory()?await gd(o,i):await tt.promises.copyFile(o,i)}}async function fe(s){try{return await tt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Lt,md,fd,tt,PT,Dt,ze,eo,Ka,rt,Ja,hd=w(()=>{"use strict";Lt=E(require("path"));Ia();Hn();md=E(require("unzip-stream")),fd=E(require("p-retry")),tt=require("fs"),PT=3;Dt=async s=>{let e=await Promise.resolve().then(()=>(qe(),et));return(0,fd.default)(()=>e.download(s),{retries:PT,factor:1})},ze=async(s,e)=>{let t=await Dt(s);return tt.promises.writeFile(e,t.body)};eo=async(s,e)=>{let t=Zn(s,e);return je(s)?ze(s,t):tt.promises.copyFile(s,t)},Ka=async s=>je(s)?Dt(s):tt.promises.readFile(s),rt=async(s,e)=>await(0,tt.createReadStream)(s).pipe(md.Extract({path:e})),Ja=s=>(0,tt.statSync)(s).size/1e6});var Mt={};V(Mt,{APPIUM_SESSION_MESSAGE:()=>ec,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>to,MOBILE_RUN_SKIP_REASON:()=>Za,gridMessages:()=>$r,gridTypes:()=>O,mobileWeb:()=>Xa,runnerStatus:()=>Ya,runnerTestStatus:()=>pe,socketEventTypes:()=>Rt,stepResult:()=>Fs,test:()=>Qa,testRunStatus:()=>Us,testStatus:()=>Ke,timeoutMessages:()=>Ve});var Ve,Us,Ya,pe,Ke,$r,Xa,Qa,Rt,Y,O,Fs,to,Za,ec,ie=w(()=>{"use strict";Ve={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Us={COMPLETED:"completed",RUNNING:"running"},Ya={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"},Ke={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"},Xa={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Qa={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Rt={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"},O={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Fs={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"},Za={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},ec={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 Bs(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 OT(){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 js,yd,Je,_T,LT,DT,MT,NT,tc,rc,bd=w(()=>{"use strict";ie();js=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},yd=s=>Boolean(s.resultId&&s.source==="remote-run"),Je=(s,e)=>s.testStatus===Ke.QUARANTINE&&!yd(e)&&!e.runQuarantinedTests;_T=s=>Boolean(s.loginMode),LT=s=>Boolean(s.tunnelOnlyMode),DT=s=>Boolean(s.createPrefechedData),MT=s=>Boolean(s.installLazyDepsMode),NT=s=>Boolean(s.agentMode),tc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},rc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function so(s=0){return ro.default.duration(s).format("HH:mm:ss.SSS")}function sc(s=0){return ro.default.duration(s).asSeconds()}var ro,Td,wd=w(()=>{"use strict";ro=E(require("dayjs")),Td=E(require("dayjs/plugin/duration"));ro.default.extend(Td.default)});var $s,Wr,Ws,vd,Vr,Ed=w(()=>{"use strict";ie();$s=s=>!(!s||"fileName"in s),Wr=(s,e)=>e===O.TESTIM_TVC?!1:s&&"fileName"in s?s.fileName.endsWith(".app"):!1,Ws=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},vd=s=>s===O.TESTIM_TVC,Vr=(s,e)=>vd(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function nc(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var Sd=w(()=>{"use strict"});var K={};V(K,{TESTIM_BROWSER_DIR:()=>Nt,buildBasicHeader:()=>Sa,calcPercentile:()=>io,copyDir:()=>gd,delay:()=>ne,doesPathExist:()=>fe,download:()=>Dt,downloadAndSave:()=>ze,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>OT,getBrowserInfo:()=>FT,getCdpAddressForHost:()=>gr,getCliLocation:()=>pt,getDuration:()=>so,getDurationSec:()=>sc,getEnginesVersion:()=>kT,getEnvironmentGitBranch:()=>fr,getLocalFileSizeInMB:()=>Ja,getMemorySnapshot:()=>nc,getPlanType:()=>oo,getRunConfigByBrowserName:()=>Gs,getRunnerVersion:()=>ut,getSource:()=>eo,getSourceAsBuffer:()=>Ka,getSourcePath:()=>Zn,getTestUrl:()=>He,getUniqBrowsers:()=>Bs,groupTestsByRetries:()=>ic,guid:()=>re,hasTestPlanFlag:()=>js,isAgentMode:()=>NT,isAppFromDevice:()=>$s,isAppFromDeviceDisabled:()=>Vr,isCreatePrefetchedDataMode:()=>DT,isInstallLazyDepsMode:()=>MT,isLoginMode:()=>_T,isMobileProject:()=>Ws,isPromise:()=>Ua,isQuarantineAndNotRemoteRun:()=>Je,isRemoteRun:()=>yd,isTestimVirtualGrid:()=>vd,isTunnelOnlyMode:()=>LT,isURL:()=>je,promiseAbort:()=>Fa,promiseFromCallback:()=>zt,promiseMap:()=>ae,promiseTimeout:()=>ce,removePropertyFromObject:()=>no,replaceArgsWithNoDashes:()=>tc,shouldBlockVirtualIosBuild:()=>Wr,spreadObjectToArgs:()=>rc,unzipFile:()=>rt});function FT(s){return s=s.toLowerCase(),oc.find(e=>e.browserValue===s)}function Gs(s,e,t){s=s==null?void 0:s.toLowerCase();let r=oc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||oc[0],n=Vs.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=Vs.find(o=>o.sl.platform===e.platform):e.platformName&&(n=Vs.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=Vs.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=Vs.find(o=>o.bs.platform===t.platform))),mr.merge(r,n)}function fr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function no(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&no(s[r],e,t))}function _e(s){return s.ELEMENT||s[Ht]}function oo(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function ic(s=[]){return mr.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=mr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=mr.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function gr(s,e){let t=await Promise.resolve().then(()=>(qe(),et));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 Id,mr,Rd,UT,Nt,Vs,oc,io,B=w(()=>{"use strict";Id=E(require("os")),mr=E(require("lodash")),Rd=E(require("path"));Or();hd();bd();wd();Ia();Ba();Ed();Sd();UT=Id.homedir(),Nt=Rd.join(UT,".testim-browser-profile"),Vs=[{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"}}],oc=[{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"}];io=(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 ac={};V(ac,{$schema:()=>BT,default:()=>GT,definitions:()=>jT,properties:()=>VT,required:()=>WT,type:()=>$T});var BT,jT,$T,WT,VT,GT,xd=w(()=>{BT="http://json-schema.org/draft-07/schema#",jT={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}}}},$T="object",WT=["entries"],VT={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},GT={$schema:BT,definitions:jT,type:$T,required:WT,properties:VT}});async function Ld(){try{return await ce(ao.promises.readFile(po()).then(async s=>{let e=await _d;return zT(e,s)}),3e4)}catch{return{}}}function zT(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Hr.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 dt(s,e,t=HT,r=void 0){return async()=>{if(!Pd)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await KT(e);if(o)return Hs.debug("cache hit:",{fnName:e}),o;if(Hs.debug("cache miss:",{fnName:e}),!kd)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 JT(e,i,t),i}}async function KT(s){let t=(await mo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function JT(s,e,t){if(cc)throw Hs.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 mo;r[s]={value:e,expiry:Date.now()+t},Od=new Promise(n=>{uo=n}),qT(r)}catch{Hs.error("failed updating cache")}}async function qr(){let s=await mo;Object.keys(s).forEach(e=>{delete s[e]})}function Dd(s){Pd=s}function YT(s=!0){kd=s}async function Md(){try{return cc=!0,await Od}finally{cc=!1}}function Nd(s){lo=s,mo=Ld()}var ao,co,Hr,Ad,Hs,lo,Cd,uo,Pd,kd,cc,Od,_d,HT,po,mo,qT,Ud,Fd,oR,Bd,Ut=w(()=>{"use strict";ao=E(require("fs")),co=E(require("path")),Hr=E(require("crypto"));B();Ad=require("lodash");j();Hs=A("local cache"),lo=co.resolve(pt(),"testim-cache"),Pd=!0,kd=!0,cc=!1,Od=new Promise(s=>{uo=s}),_d=new Promise(s=>{Cd=s}),HT=1e3*60*60*3,po=()=>co.resolve(co.resolve(lo,"testim.cache"));mo=Ld(),qT=(0,Ad.debounce)(async s=>{let e;try{let t=await _d,r=Hr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Hr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await fe(lo)||await ao.promises.mkdir(lo,{recursive:!0}),await ao.promises.writeFile(po(),a)}catch(t){Hs.error("failed saving cache",{err:t}),e=t}uo(e?{success:!1,error:e}:{success:!0})},200);Ud=Cd,Fd=Dd.bind(void 0,!1),oR=Dd.bind(void 0,!0),Bd=()=>YT(!1)});function fo(){return{cliLocation:pt(),userInfo:zr.userInfo(),platform:zr.platform(),release:zr.release()}}var zr,lc=w(()=>{"use strict";zr=E(require("os"));B()});function XT(s){try{return go.resolve(go.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 Jt(s){let e=XT(s);return require(e)}var go,qs=w(()=>{"use strict";go=E(require("path"))});async function Vd(s){return(await $d(`npm view ${s} version`)).stdout.trim()}function pc(s){try{return Jt(s)}catch{return!1}}function Gd(s,e){return require(Kr.join(s,`./node_modules/${e}/package.json`)).version}async function yo(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=Kr.join(s,"npm-shrinkwrap.json"),i=Kr.join(s,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await fe(o)&&(await uc.promises.rename(o,i),a=!0)}catch{}return await $d(`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?(Wd.info("Failed to install package due to insufficient write access",{...fo(),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
7
|
Testim had missing write access to ${l||s}
|
|
8
8
|
|
|
9
9
|
`),new Br(l||s)):c})}finally{if(a)try{await uc.promises.rename(i,o)}catch{}}}function Hd(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,ho.spawn)("node",[QT,"i","--prefix",s,...d,...e,...i],a);m.stderr.pipe(process.stderr),m.stdout.pipe(process.stdout),m.stdout.on("data",u=>{c+=u}),m.stderr.on("data",u=>{l+=u}),m.on("close",u=>{var f;if(u){let g;try{let h=(f=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(l))==null?void 0:f[1];g=`404 Not Found - GET https://registry.npmjs.org/${h==null?void 0:h.split("@")[0]} - Not found`}catch{g=`Npm Install closed with exit code ${u}
|
|
10
|
-
stdout: ${c} stderr: ${l}`}Wd.debug(`Npm Install closed with exit code ${u}`,{message:g}),o(new
|
|
10
|
+
stdout: ${c} stderr: ${l}`}Wd.debug(`Npm Install closed with exit code ${u}`,{message:g}),o(new St(g))}else n(c)}),setTimeout(()=>{try{m.kill()}finally{o(new se)}},r)})}var uc,Kr,jd,ho,$d,Wd,QT,zs=w(()=>{"use strict";uc=E(require("fs")),Kr=E(require("path"));B();jd=require("util"),ho=require("child_process");j();lc();qs();z();$d=(0,jd.promisify)(ho.exec),Wd=A("cli-service");QT=Kr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var Yd={};V(Yd,{install:()=>ew,isReady:()=>rw,start:()=>tw});var qd,zd,Kd,Jd,dc,ZT,ew,tw,rw,Xd=w(()=>{"use strict";qd=E(require("fkill")),zd=E(require("p-retry"));zs();qe();B();qs();Kd="chromedriver",Jd=9515,dc=`http://localhost:${Jd}/wd/hub`,ZT=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],ew=async()=>{await yo(pt(),`${Kd} --detect_chromedriver_version`)},tw=async()=>{process.env.NODE_OPTIONS="",await(0,qd.default)(`:${Jd}`,{silent:!0}),await Jt(Kd).start(ZT,!0)},rw=async({chromeBinaryLocation:s})=>{await(0,zd.default)(async()=>{var n;let e=await Re(`${dc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await We({url:`${dc}/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 Ds(`${dc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var Ks={};V(Ks,{getSessionPlayerFolder:()=>hc,prepareChromeDriver:()=>hr,prepareCustomExtension:()=>fc,prepareExtension:()=>gc,preparePlayer:()=>yr});async function fc(s,e=!1){if(!s)return;if(je(s)){let n=Jr.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await sw(s)>mc&&!e)throw new C(Qd);return await ze(s,n),n}let t=Jr.resolve(s);if(!em.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Ja(t)>mc&&!e)throw new C(Qd);return t}async function sw(s){let e=(qe(),he(et));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw To.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function gc(s){To.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Zn(t)}));return dt(()=>ae(e,({location:t,path:r})=>eo(t,r)),"prepareExtension",rm,e)()}async function hr(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=await Promise.resolve().then(()=>(Xd(),Yd));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 Br||(To.error(a,{...s,...fo(),error:(0,tm.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 nw(){let s=`${_r}/extension/sessionPlayer_LATEST_RELEASE`;return(await Dt(s)).body.toString("utf8")}async function ow(s,e){if(!je(s)||je(s)&&e||ke)return s;let t=await nw();return`${s}-${t}`}function hc(){let s=ut();return Jr.resolve(s,"testim-bin")}function iw(){let s=hc();return Jr.resolve(s,"sessionPlayer.zip")}async function sm(s,e,t=!1){try{return await eo(s,e),await tt(e,hc())}catch(r){if(t)throw r;return await sm(s,e,!0)}}async function yr(s,e){To.info("prepare player",{location:s,canary:e});let t=iw();return pt(async()=>{let r=await ow(s,e);return await sm(r,t),{}},"preparePlayer",rm,[s,e,t])()}var Zd,em,Jr,tm,To,rm,mc,Qd,Yr=w(()=>{"use strict";Zd=E(require("ms")),em=E(require("fs")),Jr=E(require("path"));le();Ut();tm=require("serialize-error");j();lc();z();B();To=A("prepare runner and testim start"),rm=(0,Zd.default)("0.5 day"),mc=16,Qd=`The size of the custom extension is more than ${mc}MB`});function aw(){let s=Js.type().toLowerCase();return s==="darwin"?Js.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?Js.arch()==="x64"?"win64":"win32":"linux"}async function vo(){let s=aw(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new C(`Unsupported platform: ${s}`);let r=parseInt(Ys,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]}/${Ys}/${n[s]}.zip`,a=wo.join(yc,n[s]),c=`${a}.zip`,l=wo.join(a,o[s]);if(await fe(l))return l;if(!await fe(c)){let m=(0,bc.default)("Downloading Chromium").start();try{await nm.promises.mkdir(yc),await ze(i,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,bc.default)("Extracting Chromium").start();try{await tt(c,yc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),l}var nm,Js,wo,bc,Ys,yc,Tc=w(()=>{"use strict";nm=E(require("fs")),Js=E(require("os")),wo=E(require("path")),bc=E(require("ora"));z();B();Ys="1000968",yc=wo.join(Nt,`chrome-${Ys}`)});async function im(s,e){return Eo=s,Sc=e,await wc()}function am(s,e,t){rt=s.token,Eo=e,Sc=t,Qs=Ic(rt),Zs=s.refreshToken,vc=s.ngrokToken,Ec=s.isNgrokWhitelisted}function cw(s=Eo,e=Sc){return pt(()=>(Xs.info("request to get cli token from server"),We({url:`${me}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",om*10,{projectId:s,token:e})()}async function lw(){Xs.info("request to refresh JWT cli token from server");let s=await We({url:`${me}/auth/refreshToken`,body:{token:rt,refreshToken:Zs}});return rt=s.token,Qs=Ic(rt),s.refreshToken&&(Zs=s.refreshToken),rt}async function wc(){try{let s=await cw();return Xs.info("successfully get cli token from server"),rt=s.token,Qs=Ic(rt),Zs=s.refreshToken,vc=s.ngrokToken,Ec=s.isNgrokWhitelisted,rt}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(Xs.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Eo}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function Ic(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Yt(){if(!Qs)return wc();if(Qs<Date.now()+4*om)try{return await lw()}catch(s){return Xs.error("failed to refresh token, executing fallback",s),wc()}return rt}function So(){return Zs}function Ft(){return rt?{uid:require("jsonwebtoken").decode(rt).id,ngrokToken:vc,isNgrokWhitelisted:Ec}:{}}var Xs,rt,Qs,Zs,vc,Ec,Eo,Sc,om,xt=w(()=>{"use strict";le();qe();Ut();z();j();Xs=A("testim-custom-token"),Eo=null,Sc=null,om=5*60*1e3});var cm={};V(cm,{isCi:()=>Xr});var Xr,Io=w(()=>{"use strict";Xr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Le={};V(Le,{addTestRetry:()=>Jc,clearTestResult:()=>qc,deleteCloudflareTunnel:()=>Zc,fetchLambdatestConfig:()=>Vc,forceUpdateCloudflareTunnelRoutes:()=>Qc,getAllGrids:()=>Wc,getAppDetails:()=>Dc,getApplitoolsIntegrationData:()=>Yc,getCloudflareTunnel:()=>Xc,getEditorUrl:()=>hw,getGridById:()=>Ao,getGridByName:()=>jc,getHybridGridProvider:()=>Bc,getLabFeaturesByProjectId:()=>Gc,getMobileDevicesFromGrid:()=>tl,getRealData:()=>Hc,getS3Artifact:()=>en,getS3ArtifactText:()=>xc,getSuiteTestList:()=>Lc,getTestPlan:()=>gw,getTestPlanTestList:()=>_c,getTestResults:()=>Tr,getUsageForCurrentBillingPeriod:()=>Mc,initializeUserWithAuth:()=>$c,isTestResultCompleted:()=>Nc,keepAliveGrid:()=>Uc,loadSfdcCredential:()=>Ac,loadTest:()=>Cc,releaseGridSlot:()=>Fc,reportExecutionFinished:()=>xo,reportExecutionStarted:()=>Oc,saveRemoteStep:()=>zc,saveTestPlanResult:()=>Pc,updateExecutionTests:()=>kc,updateRemoteRunFailure:()=>el,updateTestDataArtifact:()=>Po,updateTestResult:()=>Co,updateTestStatus:()=>br,uploadAppToGrid:()=>rl,uploadRunDataArtifact:()=>Kc});async function Qr(){let s=await Yt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Ye({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await Qr(),i=Object.assign({},t,o);return We({url:`${me}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function dw(s,e,t,r={},n=void 0){let o=await Qr(),i=Object.assign({},r,o);return await Ms(`${me}${s||""}`,e,t,i,n)}async function Ro(s,e){let t=await Qr();return await Ga(`${me}${s||""}`,e,t)}async function mw(s,e){let t=await Qr();return await Ds(`${me}${s||""}`,e,t)}async function fw(s,e){let t=await Qr();return await Ns(`${me}${s||""}`,e||void 0,t)}async function xe(s,e,t,r){let n=await Qr();return await Re(`${me}${s||""}`,e||void 0,n,r,t)}function en(s,e){return(0,Z.default)(()=>xe(`/storage${s}`,null,{isBinary:!0},e),{retries:oe,factor:1})}function xc(s){return(0,Z.default)(()=>fw(`/storage${s}`))}async function gw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Z.default)(()=>xe("/testPlan",{projectId:s,name:e.join(",")}),{retries:oe,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 Ac({branch:s,projectId:e}){let t=await(0,Z.default)(()=>xe(`/branch/branchData/${s}`,{projectId:e}),{retries:oe,factor:1});return t==null?void 0:t.sfdcCredential}function Cc({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Z.default)(()=>xe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:oe,factor:1})}function Pc(s,e,t){return(0,Z.default)(()=>Ye({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:oe,factor:1})}function br(s,e,t,r,n,o,i=oe){return(0,Z.default)(()=>Ro("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:uw,...o}),{retries:i,factor:1})}function kc(s,e,t,r,n,o,i,a){return(0,Z.default)(()=>Ro("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:oe,factor:1})}async function Oc({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(()=>(Io(),cm));return Ye({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 xo(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,Z.default)(()=>Ro("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:oe,factor:1})}async function _c(s,e,t,r,n){return(0,Z.default)(()=>Ye({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:oe,factor:1})}function Lc({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)(()=>Ye({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:oe,factor:1})}async function Dc({appId:s,projectId:e}){try{return await(0,Z.default)(()=>xe(`/mobile-app/app/${s}?projectId=${e}`),{retries:oe,factor:1})}catch(t){jt.error("failed getting application details",{appId:s,error:t});return}}async function Mc(s){try{return await(0,Z.default)(()=>xe(`/plan/project/${s}/usage-current-billing-period`),{retries:oe,factor:1})}catch(e){jt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Nc(s,e,t){return(0,Z.default)(()=>xe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:oe,factor:1})}function Tr(s,e,t,r){return(0,Z.default)(()=>xe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:oe,factor:1})}function Uc(s,e){return Ye({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function Fc(s,e,t,r,n){return Ye({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Bc(s){return Ye({url:"/grid/hybrid/provider",body:s})}function jc(s,e,t,r,n){return(0,Z.default)(()=>xe("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:re()}),{retries:oe,factor:1})}function Ao(s,e,t,r,n){return(0,Z.default)(()=>xe(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:re()}),{retries:oe,factor:1})}async function $c({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,gridId:o,grid:i}){var a,c;try{return await(0,Z.default)(()=>We({url:`${me}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,gridId:o,gridName:i}}),{retries:oe,factor:1})}catch(l){throw jt.error("error initializing info from server",l),(a=l==null?void 0:l.message)!=null&&a.includes("Bad Request")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(c=l==null?void 0:l.code)!=null&&c.includes("ENOTFOUND")?new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):l}}async function hw(){if(Ps)return{editorUrl:Ps};try{return await(0,Z.default)(()=>xe("/system-info/editor-url"),{retries:oe,onFailedAttempt:s=>{if(s.attemptNumber>=oe)throw s},factor:1})}catch{return jt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function Wc(s){return(0,Z.default)(()=>xe("/grid",{companyId:s}),{retries:oe,factor:1})}function Hc(s,e,t){return(0,Z.default)(()=>xe(`/real-data/${e}?${t}&projectId=${s}`),{retries:oe,factor:1})}function Co(s,e,t,r,n){return(0,Z.default)(()=>Ye({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:oe,factor:1})}function qc(s,e,t,r){return(0,Z.default)(()=>Ye({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:oe,factor:1})}function zc(s,e,t,r){return(0,Z.default)(()=>Ye({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:oe,factor:1})}function yw(s){return s.startsWith("/")?s:`/${s}`}function bw(s,e,t){let r=yw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function um(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${re()}${i||""}`,c=`${e}/${t}/${a}`,l=bw(c,"test-result-artifacts",s),d=Buffer.from(lm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Z.default)(()=>dw(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:oe,factor:1}),l}function Jc({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,Z.default)(()=>Ye({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:oe,factor:1})}async function Yc(s){try{return await xe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return jt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Xc(s,e){try{return await Ro("/tunnel",{companyId:s,routes:e})}catch(t){return jt.warn("could'nt get tunnel.",{err:t}),{}}}async function Qc(s,e){try{return await Ye({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}async function Zc(s,e){try{return await mw(`/tunnel/${e}`,{companyId:s})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}function el(s){return We({url:`${me}/result/remoteRunFailure`,body:s})}async function tl({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${pw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,Z.default)(()=>xe(o,{projectId:s}),{retries:oe,factor:1})}catch(i){return jt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function rl({projectId:s,gridId:e,app:t,timeout:r}){return(0,Z.default)(()=>Ye({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:oe,factor:1})}var Xt,lm,Z,Rc,uw,jt,oe,pw,Vc,Gc,Kc,Po,be=w(()=>{"use strict";Xt=E(require("lodash")),lm=E(require("pako"));B();le();ie();qe();xt();Z=E(require("p-retry")),Rc=E(require("object-hash"));z();j();uw=lt(),jt=A("testim service api"),oe=3,pw="/grid";Vc=async()=>(0,Z.default)(()=>xe("/grid/lt/config"),{retries:oe,factor:1}),Gc=async s=>(0,Z.default)(()=>xe(`/labFeature/v2/project/${s}`),{retries:oe,factor:1});Kc=Xt.memoize(async(s,e,t,r)=>{if(!Xt.isEmpty(r))return await um(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Rc.default)(r)}:${e}:${t}`),Po=Xt.memoize(async(s,e,t,r,n)=>!r||Xt.isEmpty(r)?void 0:await um(s,e,t,JSON.stringify((()=>{let i=Xt.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&Object.assign(i,{[c]:Qa.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Rc.default)(r)}:${e}:${t}`)});var Qt={};V(Qt,{getSessionPlayer:()=>ee,options:()=>nl});var ko,nl,sl,ee,Te=w(()=>{"use strict";ko=require("path"),nl={playerPath:void 0},ee=()=>{if(sl)return sl;let s=(Be(),he(Fe));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Yr(),he(Ks)),t=e(),r=nl.playerPath?(0,ko.resolve)(nl.playerPath,"src/background/sessionPlayerInit.ts"):(0,ko.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),sl=n,n}});function vw(s){process.nextTick(()=>{if([Y.SELENIUM,Y.APPIUM].includes(s))try{(Te(),he(Qt)).getSessionPlayer()}catch{}})}async function tn(s){let{project:e,token:t,lightweightMode:r,useLocalChromeDriver:n,useChromeLauncher:o,mode:i,gridId:a,grid:c}=s,l=Boolean(r==null?void 0:r.general),d=Boolean(n||o),m=l?ww:Tw;N("before initializeUserWithAuth");let u=await pt(async()=>(vw(i),await $c({projectId:e,token:t,branchName:s.branch,lightweightMode:r,localGrid:d,gridId:a,grid:c})),"initializeUserWithAuth",m,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:l,localGrid:d,gridId:a,grid:c})();return N("after initializeUserWithAuth"),am(u.authData,s.project,s.token),u}var Tw,ww,pm=w(()=>{"use strict";Be();be();Ut();xt();ie();Tw=1e3*60*5,ww=1e3*60*60*10});async function fm(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await vo():s.chromeBinaryLocation,e=hr({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 yr(s.playerLocation,s.canary),s.mode===Y.EXTENSION&&!s.ext&&await gc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await fc(s.installCustomExtension,n)}return await e,t}async function gm(s){var i;Ew.info("prepare MockNetwork",{location:s});let e=await Ka(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>dm*1e6)throw new Error(`${ol} exceeded ${dm}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${ol} cannot be parsed.${Oo.EOL}${a}`)}let n=new mm.default;if(!n.validate(ac,r)){let a=(i=n.errors)==null?void 0:i.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Oo.EOL);throw new Error(`${ol} is malformed.${Oo.EOL}${a}`)}return r.entries}var Oo,mm,dm,ol,Ew,il=w(()=>{"use strict";Oo=E(require("os"));B();xd();Yr();mm=E(require("ajv"));ie();Tc();pm();dm=1,ol="JSON file supplied to --mock-network-pattern",Ew=(j(),he(Na)).getLogger("prepare runner")});function ym(s,e=process){async function t(r){await ce(ae(hm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{rn.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(rn.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",()=>{rn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw rn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw rn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function Zr(s){hm.push(s)}var rn,hm,sn=w(()=>{"use strict";j();B();rn=A("process-handler"),hm=[]});var G,Sm,Cw,Pw,kw,Em,Lo,ul,M,ge=w(()=>{"use strict";G=E(require("rox-node"));j();B();le();Sm=A("FeatureFlagsService"),Cw=!ke&&!0&&!Fp,Pw=2e4,kw=60*60*24,Em=["labs","disabled","enabled"],Lo=class extends G.default.Variant{constructor(e="disabled"){super(e,Em)}getValue(){let e=super.getValue();return Em.includes(e)?e:(Sm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},ul=class{constructor(){this.flags={useNewWSCLI:new G.default.Flag,useSafariWebdriverVisibilityChecks:new G.default.Flag,useClickimVisibilityChecks:new G.default.Flag,runGetElementCodeInAut:new G.default.Flag,enableFrameSwitchOptimization:new G.default.Flag,maximumJsResultSize:new G.default.Configuration(2e3*1024),skipFileInputClicks:new G.default.Flag,errorMessageOnBadNetwork:new G.default.Flag(!0),warnOnBadNetwork:new G.default.Flag(!1),overrideAzureStorageUrl:new G.default.Flag,useJsInputCodeInSafari:new G.default.Flag,useJsInputCodeInFirefox:new G.default.Flag,useJsInputCodeInEdgeChromium:new G.default.Flag,autoSaveDownloadFileFireFox:new G.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new G.default.Flag(!0),experimentalPreCodeCompilation:new G.default.Flag(!0),experimentalAsyncCustomCode:new G.default.Flag,useSameBrowserForMultiTests:new Lo("labs"),highSpeedMode:new Lo,usePortedHtml5DragDrop:new G.default.Flag,testNamesToBeforeSuiteHook:new G.default.Flag,addCustomCapabilities:new G.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new G.default.Variant("{}"),LTNetworkCapabilities:new G.default.Flag,downloadToBase64:new G.default.Flag,publicGridURL:new G.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new G.default.Flag(!0),unsupportedCapsFields:new G.default.Variant("[]"),useLinkedomToParseHtml:new G.default.Flag,dontFocusOnInit:new G.default.Flag,retryOnSeleniumHubError:new G.default.Flag,enableLambdaTestTunnelNTLM:new G.default.Flag,enableLambdaTestTunnelSkipUpgrade:new G.default.Flag,tdcHsPreventNetworkCapture:new G.default.Flag,headSpinTdcEnableFlagCapability:new G.default.Flag,enableBatchTDC:new G.default.Flag,enableBatchHeadSpin:new G.default.Flag,clearRunnerFileCache:new G.default.Flag,forceTurboModeIfNeeded:new G.default.Flag},G.default.register("default",this.flags)}setProjectId(e){G.default.setCustomStringProperty("projectId",e)}setProjectType(e){G.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){G.default.setCustomStringProperty("productType",e)}setCompanyId(e){G.default.setCustomStringProperty("companyId",e)}setPlanType(e){G.default.setCustomStringProperty("planType",e)}setIsPOC(e){G.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){G.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){G.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Cw)return;let e={fetchIntervalInSec:kw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(G.default.setup(Np,e),Pw).catch(t=>Sm.error("failed to get feature flag status",t))}},M=new ul});function pl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?$p:_r}/extension/testim-firefox-profile${t}`,n=`${e?Wp:_r}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function Im(s){let{chrome:e,firefox:t}=pl(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function Do(s){let e=`${_r}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Mo=w(()=>{"use strict";le()});function Pm(s){ke||(s!=null&&s.userId||(s={anonymousId:Cm}),Am.identify(s))}function dt(s,e){return nn("ci",s,e)}function nn(s,e,t){if(ke)return;let r=s?{userId:s}:{anonymousId:Cm};Am.track(Object.assign(r,{event:e,properties:t}))}var xm,Am,Cm,es=w(()=>{"use strict";le();xm=E(require("analytics-node")),Am=new xm.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),Cm=require("crypto").randomBytes(20).toString("hex")});function km(s){return s.start&&nn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Om(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 C("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=Do(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 _m=w(()=>{"use strict";Mo();es();z()});function Uo(s){let{platform:e}=process;e==="win32"?(0,No.exec)(`start chrome ${s}`):e==="darwin"?(0,No.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,No.exec)(`google-chrome ${s}`)}var No,dl=w(()=>{"use strict";No=require("child_process")});var an={};V(an,{doLogin:()=>hl,getProjectId:()=>_w,getToken:()=>Lw});async function _w(){return Mm("projectId")}async function Lw(){return Mm("token")}function Dm(s,e){return Promise.race([s,ne(e).then(()=>{throw new se("timeout")})])}async function Dw(){let s=(await import("express")).default(),e=async function(){return Dm(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(()=>(be(),Le)),{editorUrl:n}=await r();Uo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function hl({overwriteExisting:s=!0,projects:e=null}={}){let t=ml.homedir(),r=fl.join(t,".testim");if(await fe(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 Dm(Dw(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await Lm(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 Lm(r,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Lm(s,e){await gl.promises.writeFile(s,Fo.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Mm(s){let e=ml.homedir(),t=fl.join(e,".testim"),r=await fe(t),n={};if(r)try{n=Fo.parse((await gl.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var ml,fl,Fo,gl,ts=w(()=>{"use strict";ml=E(require("os")),fl=E(require("path")),Fo=E(require("yaml"));B();gl=require("fs");z();dl()});var $m={};V($m,{process:()=>Ww});var bl,Um,Tl,Fm,$t,Me,Bm,Mw,De,El,Nw,Uw,Nm,jm,Fw,wl,vl,Sl,yl,At,Bw,p,jw,$w,Ww,Wm=w(()=>{"use strict";bl=E(require("ms")),Um=E(require("chalk")),Tl=E(require("fs")),Fm=E(require("url")),$t=E(require("lodash")),Me=E(require("path"));B();Mo();_m();Ut();Bm=require("commander");ie();z();Or();B();ge();Mw=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),De=(s,e)=>(e.push(s),e),El=new Bm.Command,Nw=s=>s.split(","),Uw=(s,e)=>!s||s.length===0?e:s,Nm=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],jm=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}El.help(g=>g.split(`
|
|
16
|
+
4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function nw(){let s=`${_r}/extension/sessionPlayer_LATEST_RELEASE`;return(await Dt(s)).body.toString("utf8")}async function ow(s,e){if(!je(s)||je(s)&&e||ke)return s;let t=await nw();return`${s}-${t}`}function hc(){let s=pt();return Jr.resolve(s,"testim-bin")}function iw(){let s=hc();return Jr.resolve(s,"sessionPlayer.zip")}async function sm(s,e,t=!1){try{return await eo(s,e),await rt(e,hc())}catch(r){if(t)throw r;return await sm(s,e,!0)}}async function yr(s,e){To.info("prepare player",{location:s,canary:e});let t=iw();return dt(async()=>{let r=await ow(s,e);return await sm(r,t),{}},"preparePlayer",rm,[s,e,t])()}var Zd,em,Jr,tm,To,rm,mc,Qd,Yr=w(()=>{"use strict";Zd=E(require("ms")),em=E(require("fs")),Jr=E(require("path"));le();Ut();tm=require("serialize-error");j();lc();z();B();To=A("prepare runner and testim start"),rm=(0,Zd.default)("0.5 day"),mc=16,Qd=`The size of the custom extension is more than ${mc}MB`});function aw(){let s=Js.type().toLowerCase();return s==="darwin"?Js.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?Js.arch()==="x64"?"win64":"win32":"linux"}async function vo(){let s=aw(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new C(`Unsupported platform: ${s}`);let r=parseInt(Ys,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]}/${Ys}/${n[s]}.zip`,a=wo.join(yc,n[s]),c=`${a}.zip`,l=wo.join(a,o[s]);if(await fe(l))return l;if(!await fe(c)){let m=(0,bc.default)("Downloading Chromium").start();try{await nm.promises.mkdir(yc),await ze(i,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,bc.default)("Extracting Chromium").start();try{await rt(c,yc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),l}var nm,Js,wo,bc,Ys,yc,Tc=w(()=>{"use strict";nm=E(require("fs")),Js=E(require("os")),wo=E(require("path")),bc=E(require("ora"));z();B();Ys="1000968",yc=wo.join(Nt,`chrome-${Ys}`)});async function im(s,e){return Eo=s,Sc=e,await wc()}function am(s,e,t){st=s.token,Eo=e,Sc=t,Qs=Ic(st),Zs=s.refreshToken,vc=s.ngrokToken,Ec=s.isNgrokWhitelisted}function cw(s=Eo,e=Sc){return dt(()=>(Xs.info("request to get cli token from server"),We({url:`${me}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",om*10,{projectId:s,token:e})()}async function lw(){Xs.info("request to refresh JWT cli token from server");let s=await We({url:`${me}/auth/refreshToken`,body:{token:st,refreshToken:Zs}});return st=s.token,Qs=Ic(st),s.refreshToken&&(Zs=s.refreshToken),st}async function wc(){try{let s=await cw();return Xs.info("successfully get cli token from server"),st=s.token,Qs=Ic(st),Zs=s.refreshToken,vc=s.ngrokToken,Ec=s.isNgrokWhitelisted,st}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(Xs.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Eo}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function Ic(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Yt(){if(!Qs)return wc();if(Qs<Date.now()+4*om)try{return await lw()}catch(s){return Xs.error("failed to refresh token, executing fallback",s),wc()}return st}function So(){return Zs}function Ft(){return st?{uid:require("jsonwebtoken").decode(st).id,ngrokToken:vc,isNgrokWhitelisted:Ec}:{}}var Xs,st,Qs,Zs,vc,Ec,Eo,Sc,om,xt=w(()=>{"use strict";le();qe();Ut();z();j();Xs=A("testim-custom-token"),Eo=null,Sc=null,om=5*60*1e3});var cm={};V(cm,{isCi:()=>Xr});var Xr,Io=w(()=>{"use strict";Xr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var Le={};V(Le,{addTestRetry:()=>Jc,clearTestResult:()=>qc,deleteCloudflareTunnel:()=>Zc,fetchLambdatestConfig:()=>Vc,forceUpdateCloudflareTunnelRoutes:()=>Qc,getAllGrids:()=>Wc,getAppDetails:()=>Dc,getApplitoolsIntegrationData:()=>Yc,getCloudflareTunnel:()=>Xc,getEditorUrl:()=>hw,getGridById:()=>Ao,getGridByName:()=>jc,getHybridGridProvider:()=>Bc,getLabFeaturesByProjectId:()=>Gc,getMobileDevicesFromGrid:()=>tl,getRealData:()=>Hc,getS3Artifact:()=>en,getS3ArtifactText:()=>xc,getSuiteTestList:()=>Lc,getTestPlan:()=>gw,getTestPlanTestList:()=>_c,getTestResults:()=>Tr,getUsageForCurrentBillingPeriod:()=>Mc,initializeUserWithAuth:()=>$c,isTestResultCompleted:()=>Nc,keepAliveGrid:()=>Uc,loadSfdcCredential:()=>Ac,loadTest:()=>Cc,releaseGridSlot:()=>Fc,reportExecutionFinished:()=>xo,reportExecutionStarted:()=>Oc,saveRemoteStep:()=>zc,saveTestPlanResult:()=>Pc,updateExecutionTests:()=>kc,updateRemoteRunFailure:()=>el,updateTestDataArtifact:()=>Po,updateTestResult:()=>Co,updateTestStatus:()=>br,uploadAppToGrid:()=>rl,uploadRunDataArtifact:()=>Kc});async function Qr(){let s=await Yt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Ye({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await Qr(),i=Object.assign({},t,o);return We({url:`${me}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function dw(s,e,t,r={},n=void 0){let o=await Qr(),i=Object.assign({},r,o);return await Ms(`${me}${s||""}`,e,t,i,n)}async function Ro(s,e){let t=await Qr();return await Ga(`${me}${s||""}`,e,t)}async function mw(s,e){let t=await Qr();return await Ds(`${me}${s||""}`,e,t)}async function fw(s,e){let t=await Qr();return await Ns(`${me}${s||""}`,e||void 0,t)}async function xe(s,e,t,r){let n=await Qr();return await Re(`${me}${s||""}`,e||void 0,n,r,t)}function en(s,e){return(0,Z.default)(()=>xe(`/storage${s}`,null,{isBinary:!0},e),{retries:oe,factor:1})}function xc(s){return(0,Z.default)(()=>fw(`/storage${s}`))}async function gw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,Z.default)(()=>xe("/testPlan",{projectId:s,name:e.join(",")}),{retries:oe,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 Ac({branch:s,projectId:e}){let t=await(0,Z.default)(()=>xe(`/branch/branchData/${s}`,{projectId:e}),{retries:oe,factor:1});return t==null?void 0:t.sfdcCredential}function Cc({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,Z.default)(()=>xe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:oe,factor:1})}function Pc(s,e,t){return(0,Z.default)(()=>Ye({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:oe,factor:1})}function br(s,e,t,r,n,o,i=oe){return(0,Z.default)(()=>Ro("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:uw,...o}),{retries:i,factor:1})}function kc(s,e,t,r,n,o,i,a){return(0,Z.default)(()=>Ro("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:oe,factor:1})}async function Oc({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(()=>(Io(),cm));return Ye({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 xo(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,Z.default)(()=>Ro("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:oe,factor:1})}async function _c(s,e,t,r,n){return(0,Z.default)(()=>Ye({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:oe,factor:1})}function Lc({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)(()=>Ye({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:oe,factor:1})}async function Dc({appId:s,projectId:e}){try{return await(0,Z.default)(()=>xe(`/mobile-app/app/${s}?projectId=${e}`),{retries:oe,factor:1})}catch(t){jt.error("failed getting application details",{appId:s,error:t});return}}async function Mc(s){try{return await(0,Z.default)(()=>xe(`/plan/project/${s}/usage-current-billing-period`),{retries:oe,factor:1})}catch(e){jt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Nc(s,e,t){return(0,Z.default)(()=>xe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:oe,factor:1})}function Tr(s,e,t,r){return(0,Z.default)(()=>xe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:oe,factor:1})}function Uc(s,e){return Ye({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function Fc(s,e,t,r,n){return Ye({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Bc(s){return Ye({url:"/grid/hybrid/provider",body:s})}function jc(s,e,t,r,n){return(0,Z.default)(()=>xe("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:re()}),{retries:oe,factor:1})}function Ao(s,e,t,r,n){return(0,Z.default)(()=>xe(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:re()}),{retries:oe,factor:1})}async function $c({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,gridId:o,grid:i}){var a,c;try{return await(0,Z.default)(()=>We({url:`${me}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,gridId:o,gridName:i}}),{retries:oe,factor:1})}catch(l){throw jt.error("error initializing info from server",l),(a=l==null?void 0:l.message)!=null&&a.includes("Bad Request")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(c=l==null?void 0:l.code)!=null&&c.includes("ENOTFOUND")?new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):l}}async function hw(){if(Ps)return{editorUrl:Ps};try{return await(0,Z.default)(()=>xe("/system-info/editor-url"),{retries:oe,onFailedAttempt:s=>{if(s.attemptNumber>=oe)throw s},factor:1})}catch{return jt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function Wc(s){return(0,Z.default)(()=>xe("/grid",{companyId:s}),{retries:oe,factor:1})}function Hc(s,e,t){return(0,Z.default)(()=>xe(`/real-data/${e}?${t}&projectId=${s}`),{retries:oe,factor:1})}function Co(s,e,t,r,n){return(0,Z.default)(()=>Ye({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:oe,factor:1})}function qc(s,e,t,r){return(0,Z.default)(()=>Ye({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:oe,factor:1})}function zc(s,e,t,r){return(0,Z.default)(()=>Ye({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:oe,factor:1})}function yw(s){return s.startsWith("/")?s:`/${s}`}function bw(s,e,t){let r=yw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function um(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${re()}${i||""}`,c=`${e}/${t}/${a}`,l=bw(c,"test-result-artifacts",s),d=Buffer.from(lm.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,Z.default)(()=>dw(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:oe,factor:1}),l}function Jc({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,Z.default)(()=>Ye({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:oe,factor:1})}async function Yc(s){try{return await xe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return jt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Xc(s,e){try{return await Ro("/tunnel",{companyId:s,routes:e})}catch(t){return jt.warn("could'nt get tunnel.",{err:t}),{}}}async function Qc(s,e){try{return await Ye({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}async function Zc(s,e){try{return await mw(`/tunnel/${e}`,{companyId:s})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}function el(s){return We({url:`${me}/result/remoteRunFailure`,body:s})}async function tl({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${pw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,Z.default)(()=>xe(o,{projectId:s}),{retries:oe,factor:1})}catch(i){return jt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function rl({projectId:s,gridId:e,app:t,timeout:r}){return(0,Z.default)(()=>Ye({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:oe,factor:1})}var Xt,lm,Z,Rc,uw,jt,oe,pw,Vc,Gc,Kc,Po,be=w(()=>{"use strict";Xt=E(require("lodash")),lm=E(require("pako"));B();le();ie();qe();xt();Z=E(require("p-retry")),Rc=E(require("object-hash"));z();j();uw=ut(),jt=A("testim service api"),oe=3,pw="/grid";Vc=async()=>(0,Z.default)(()=>xe("/grid/lt/config"),{retries:oe,factor:1}),Gc=async s=>(0,Z.default)(()=>xe(`/labFeature/v2/project/${s}`),{retries:oe,factor:1});Kc=Xt.memoize(async(s,e,t,r)=>{if(!Xt.isEmpty(r))return await um(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Rc.default)(r)}:${e}:${t}`),Po=Xt.memoize(async(s,e,t,r,n)=>!r||Xt.isEmpty(r)?void 0:await um(s,e,t,JSON.stringify((()=>{let i=Xt.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&Object.assign(i,{[c]:Qa.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Rc.default)(r)}:${e}:${t}`)});var Qt={};V(Qt,{getSessionPlayer:()=>ee,options:()=>nl});var ko,nl,sl,ee,Te=w(()=>{"use strict";ko=require("path"),nl={playerPath:void 0},ee=()=>{if(sl)return sl;let s=(Be(),he(Fe));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Yr(),he(Ks)),t=e(),r=nl.playerPath?(0,ko.resolve)(nl.playerPath,"src/background/sessionPlayerInit.ts"):(0,ko.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),sl=n,n}});function vw(s){process.nextTick(()=>{if([Y.SELENIUM,Y.APPIUM].includes(s))try{(Te(),he(Qt)).getSessionPlayer()}catch{}})}async function tn(s){let{project:e,token:t,lightweightMode:r,useLocalChromeDriver:n,useChromeLauncher:o,mode:i,gridId:a,grid:c}=s,l=Boolean(r==null?void 0:r.general),d=Boolean(n||o),m=l?ww:Tw;N("before initializeUserWithAuth");let u=await dt(async()=>(vw(i),await $c({projectId:e,token:t,branchName:s.branch,lightweightMode:r,localGrid:d,gridId:a,grid:c})),"initializeUserWithAuth",m,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:l,localGrid:d,gridId:a,grid:c})();return N("after initializeUserWithAuth"),am(u.authData,s.project,s.token),u}var Tw,ww,pm=w(()=>{"use strict";Be();be();Ut();xt();ie();Tw=1e3*60*5,ww=1e3*60*60*10});async function fm(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await vo():s.chromeBinaryLocation,e=hr({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 yr(s.playerLocation,s.canary),s.mode===Y.EXTENSION&&!s.ext&&await gc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await fc(s.installCustomExtension,n)}return await e,t}async function gm(s){var i;Ew.info("prepare MockNetwork",{location:s});let e=await Ka(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>dm*1e6)throw new Error(`${ol} exceeded ${dm}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${ol} cannot be parsed.${Oo.EOL}${a}`)}let n=new mm.default;if(!n.validate(ac,r)){let a=(i=n.errors)==null?void 0:i.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Oo.EOL);throw new Error(`${ol} is malformed.${Oo.EOL}${a}`)}return r.entries}var Oo,mm,dm,ol,Ew,il=w(()=>{"use strict";Oo=E(require("os"));B();xd();Yr();mm=E(require("ajv"));ie();Tc();pm();dm=1,ol="JSON file supplied to --mock-network-pattern",Ew=(j(),he(Na)).getLogger("prepare runner")});function ym(s,e=process){async function t(r){await ce(ae(hm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{rn.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(rn.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",()=>{rn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw rn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw rn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function Zr(s){hm.push(s)}var rn,hm,sn=w(()=>{"use strict";j();B();rn=A("process-handler"),hm=[]});var G,Sm,Cw,Pw,kw,Em,Lo,ul,M,ge=w(()=>{"use strict";G=E(require("rox-node"));j();B();le();Sm=A("FeatureFlagsService"),Cw=!ke&&!0&&!Fp,Pw=2e4,kw=60*60*24,Em=["labs","disabled","enabled"],Lo=class extends G.default.Variant{constructor(e="disabled"){super(e,Em)}getValue(){let e=super.getValue();return Em.includes(e)?e:(Sm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},ul=class{constructor(){this.flags={useNewWSCLI:new G.default.Flag,useSafariWebdriverVisibilityChecks:new G.default.Flag,useClickimVisibilityChecks:new G.default.Flag,runGetElementCodeInAut:new G.default.Flag,enableFrameSwitchOptimization:new G.default.Flag,maximumJsResultSize:new G.default.Configuration(2e3*1024),skipFileInputClicks:new G.default.Flag,errorMessageOnBadNetwork:new G.default.Flag(!0),warnOnBadNetwork:new G.default.Flag(!1),overrideAzureStorageUrl:new G.default.Flag,useJsInputCodeInSafari:new G.default.Flag,useJsInputCodeInFirefox:new G.default.Flag,useJsInputCodeInEdgeChromium:new G.default.Flag,autoSaveDownloadFileFireFox:new G.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new G.default.Flag(!0),experimentalPreCodeCompilation:new G.default.Flag(!0),experimentalAsyncCustomCode:new G.default.Flag,useSameBrowserForMultiTests:new Lo("labs"),highSpeedMode:new Lo,usePortedHtml5DragDrop:new G.default.Flag,testNamesToBeforeSuiteHook:new G.default.Flag,addCustomCapabilities:new G.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new G.default.Variant("{}"),LTNetworkCapabilities:new G.default.Flag,downloadToBase64:new G.default.Flag,publicGridURL:new G.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new G.default.Flag(!0),unsupportedCapsFields:new G.default.Variant("[]"),useLinkedomToParseHtml:new G.default.Flag,dontFocusOnInit:new G.default.Flag,retryOnSeleniumHubError:new G.default.Flag,enableLambdaTestTunnelNTLM:new G.default.Flag,enableLambdaTestTunnelSkipUpgrade:new G.default.Flag,tdcHsPreventNetworkCapture:new G.default.Flag,headSpinTdcEnableFlagCapability:new G.default.Flag,enableBatchTDC:new G.default.Flag,enableBatchHeadSpin:new G.default.Flag,clearRunnerFileCache:new G.default.Flag,forceTurboModeIfNeeded:new G.default.Flag},G.default.register("default",this.flags)}setProjectId(e){G.default.setCustomStringProperty("projectId",e)}setProjectType(e){G.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){G.default.setCustomStringProperty("productType",e)}setCompanyId(e){G.default.setCustomStringProperty("companyId",e)}setPlanType(e){G.default.setCustomStringProperty("planType",e)}setIsPOC(e){G.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){G.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){G.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Cw)return;let e={fetchIntervalInSec:kw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(G.default.setup(Np,e),Pw).catch(t=>Sm.error("failed to get feature flag status",t))}},M=new ul});function pl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?$p:_r}/extension/testim-firefox-profile${t}`,n=`${e?Wp:_r}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function Im(s){let{chrome:e,firefox:t}=pl(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function Do(s){let e=`${_r}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Mo=w(()=>{"use strict";le()});function Pm(s){ke||(s!=null&&s.userId||(s={anonymousId:Cm}),Am.identify(s))}function mt(s,e){return nn("ci",s,e)}function nn(s,e,t){if(ke)return;let r=s?{userId:s}:{anonymousId:Cm};Am.track(Object.assign(r,{event:e,properties:t}))}var xm,Am,Cm,es=w(()=>{"use strict";le();xm=E(require("analytics-node")),Am=new xm.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),Cm=require("crypto").randomBytes(20).toString("hex")});function km(s){return s.start&&nn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Om(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 C("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=Do(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 _m=w(()=>{"use strict";Mo();es();z()});function Uo(s){let{platform:e}=process;e==="win32"?(0,No.exec)(`start chrome ${s}`):e==="darwin"?(0,No.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,No.exec)(`google-chrome ${s}`)}var No,dl=w(()=>{"use strict";No=require("child_process")});var an={};V(an,{doLogin:()=>hl,getProjectId:()=>_w,getToken:()=>Lw});async function _w(){return Mm("projectId")}async function Lw(){return Mm("token")}function Dm(s,e){return Promise.race([s,ne(e).then(()=>{throw new se("timeout")})])}async function Dw(){let s=(await import("express")).default(),e=async function(){return Dm(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(()=>(be(),Le)),{editorUrl:n}=await r();Uo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function hl({overwriteExisting:s=!0,projects:e=null}={}){let t=ml.homedir(),r=fl.join(t,".testim");if(await fe(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 Dm(Dw(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await Lm(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 Lm(r,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Lm(s,e){await gl.promises.writeFile(s,Fo.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function Mm(s){let e=ml.homedir(),t=fl.join(e,".testim"),r=await fe(t),n={};if(r)try{n=Fo.parse((await gl.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var ml,fl,Fo,gl,ts=w(()=>{"use strict";ml=E(require("os")),fl=E(require("path")),Fo=E(require("yaml"));B();gl=require("fs");z();dl()});var $m={};V($m,{process:()=>Ww});var bl,Um,Tl,Fm,$t,Me,Bm,Mw,De,El,Nw,Uw,Nm,jm,Fw,wl,vl,Sl,yl,At,Bw,p,jw,$w,Ww,Wm=w(()=>{"use strict";bl=E(require("ms")),Um=E(require("chalk")),Tl=E(require("fs")),Fm=E(require("url")),$t=E(require("lodash")),Me=E(require("path"));B();Mo();_m();Ut();Bm=require("commander");ie();z();Or();B();ge();Mw=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),De=(s,e)=>(e.push(s),e),El=new Bm.Command,Nw=s=>s.split(","),Uw=(s,e)=>!s||s.length===0?e:s,Nm=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],jm=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}El.help(g=>g.split(`
|
|
17
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)&&!u(y)&&!f(y)).join(`
|
|
18
18
|
`))},Fw=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Um.default.yellow(`
|
|
19
19
|
WARNING: ${s} is deprecated. ${t}
|
|
20
|
-
`))},wl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:vl,argv:Sl,exit:yl,cwd:At}=global.process,Bw=["trace","debug","info","warn","error","silent"];tc(Sl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));El.description("Testim.io CLI").option("-h --help","output usage information",jm).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",Nw).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--is-regression-baseline-run","save doms and run results as regression baseline data").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",De,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(vl.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,bl.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,bl.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: ${wl.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",De,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",De,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",De,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).parse(Sl);p=El.opts(),jw=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},$w=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Ww=async()=>{var v,I,b,T,R,k,_,$;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!Sl.slice(2).length)throw jm(),new Dr;if(p.requireCredentials){let S=await Promise.resolve().then(()=>(ts(),an)),x=await S.getProjectId(),D=await S.getToken();(!x||!D)&&await S.doLogin()}if(p.login)return await(await Promise.resolve().then(()=>(ts(),an))).doLogin(),{loginMode:!0};if(p.version){let S="Testim CLI Version: ";vl.npm_package_version&&(console.log(S,vl.npm_package_version),yl(0));let x=lt();x&&(console.log(S,x),yl(0)),console.log("Could not find version, please check the package.json manually"),yl(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Fd(),p.clearFileCache&&qr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let S=Me.resolve(n);Nd(S)}if(p.usePrefechedData&&Bd(),p.playerRequirePath){let S=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",S);let x=Me.join(S,"tsconfig.node.json"),F=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${$t.escapeRegExp(Me.relative(At(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:F.config.options.paths,baseUrl:F.config.options.baseUrl}),(Te(),he(Qt)).options.playerPath=S;let H=require("module"),X=H.prototype.require;H.prototype.require=function(bt){return bt==="rox-alias"?X.call(this,"rox-node"):X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Tl.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent")),p.proxyForGrid&&!p.proxy)throw new C("missing --proxy option");if(km(p))return Om(p);try{let S={};p.configFile?S=require(Me.join(At(),p.configFile)).config:p.optionsFile&&(S=require(Me.join(At(),p.optionsFile))),S&&typeof S.then=="function"&&(S=await S),Object.keys(S).forEach(x=>{let D=Mw(x);p[D]=Uw(p[D],S[x])})}catch(S){throw S.message=`Unable to read options file: ${S.message}`,S}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((v=p.testConfig)==null?void 0:v.length)||((I=p.testConfigId)==null?void 0:I.length),i=((b=p.testPlan)==null?void 0:b.length)||((T=p.testPlanId)==null?void 0:T.length),a=((R=p.suite)==null?void 0:R.length)||((k=p.suiteId)==null?void 0:k.length);if(p.seleniumCapsFile)try{r=require(Me.join(At(),p.seleniumCapsFile))}catch(S){throw new C(`Failed to parse selenium caps file file error: ${S.message}`)}if((_=p.reporters)!=null&&_.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(At(),p.chromeExtraPrefs))}catch(S){throw new C(`Failed to read/open chrome extra prefs file error: ${S.message}`)}if(p.chromeExtraArgs){let S=p.chromeExtraArgs.split(",");for(let x of S){let[D]=x.split("=");Nm.includes(D)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),D==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${D}), allowed values: ${JSON.stringify(Nm)}`)}}if(p.paramsFile)try{s=Object.assign({},s,require(Me.join(At(),p.paramsFile)))}catch(S){throw new C(`Failed to read/open params file error: ${S.message}`)}if(p.params)try{s=Object.assign({},s,JSON.parse(p.params))}catch(S){throw new C(`Failed to parse params string error: ${S.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(jw(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let S=require(Me.join(At(),p.sauceOptions)),x=S.platformName&&["ios","android"].includes(S.platformName.toLowerCase());if(S.browserName){let F=S.browserName.toLowerCase();switch(F){case"microsoftedge":p.browser="edge";break;default:p.browser=F}}p.browser==="edge"&&parseFloat(S.version)>=Ea&&(p.browser="edge-chromium");let D=parseFloat(S.version)<50&&!["dev","beta"].includes(S.version);if(!x&&p.browser==="chrome"&&D)throw new C("The minimum chrome supported version is 50.0");p.saucelabs=Object.assign({},p.saucelabs,S)}catch(S){throw new C(`Failed to parse saucelabs options file error: ${S.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&($w(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let S=require(Me.join(At(),p.browserstackOptions)),x=S.platform&&["mac","android"].includes(S.platform.toLowerCase());if(S.browserName&&(p.browser=S.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(S.browser_version)>=Ea&&(p.browser="edge-chromium"),!x&&parseFloat(S.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack=Object.assign({},p.browserstack,S)}catch(S){throw new C(`Failed to parse browserstack options file error: ${S.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let S=require(Me.join(At(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto=Object.assign({},x,S)}catch(S){throw new C(`Failed to parse perfecto options file error: ${S.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let S=require(Me.join(At(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce=Object.assign({},x,S)}catch(S){throw new C(`Failed to parse test object options file error: ${S.message}`)}if(!p.project){let x=await(await Promise.resolve().then(()=>(ts(),an))).getProjectId();if(x)p.project=x;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}M.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.mode??="extension",p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=p.mode===Y.APPIUM?1:Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let l=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let x=await(await Promise.resolve().then(()=>(ts(),an))).getToken();if(x)p.token=x;else throw new C("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let d=S=>S<=0||!Number.isInteger(S);if(d(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.mode!==Y.SELENIUM&&p.disableNativeEvents)throw new C("disable-native-events is only applicable in selenium mode");if(!p.browser&&!o&&!i&&(p.browser="chrome"),p.appiumLogLevel||(p.appiumLogLevel="silent"),!Bw.includes(p.appiumLogLevel))throw new C(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData)throw new C("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if(($=p.host)!=null&&$.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Fm.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let S=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),S.length)throw new C("A result label cannot exceed 250 characters")}let u=Im(p),f=Do(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||i))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!$t.inRange($t.parseInt(p.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let g="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${g}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${g}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&$t.difference(p.codeCoverageReporter,wl).length){let S=$t.difference(p.codeCoverageReporter,wl);throw new C(`invalid --code-coverage-reporter parameters ${S.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let h={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(h).filter(S=>Boolean(p[S]));if(p.mode!==Y.EXTENSION&&y.length){let S=y.length>1?"are":"is";throw new C(`${y.map(x=>h[x]).join(" and ")} ${S} only applicable in extension mode`)}if(p.tmsFieldFile)try{let S=Tl.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(S)}catch(S){throw new C(`failed to parse field file error: ${S.message}`)}if(p.highSpeed&&(Fw("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.resetOnSessionStartOnly&&!p.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),p.lightweightMode)try{let S={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode=Object.assign({},S,x)}catch(S){throw new C(`failed to parse lightweightMode settings error: ${S.message}`)}else p.turboMode&&p.mode===Y.EXTENSION?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&p.mode===Y.SELENIUM&&console.warn(`
|
|
21
|
-
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new C("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),webpackConfig:p.webpackConfig,reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?fr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userParamsData:s,mode:p.mode,isRegressionBaselineRun:p.isRegressionBaselineRun,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,resetOnSessionStartOnly:p.resetOnSessionStartOnly,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:l,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0},downloadBrowser:p.downloadBrowser}}});var qm={};V(qm,{installAllLazyDependencies:()=>Hw,lazyRequire:()=>Ee});async function Ee(s,e={}){let t=pc(s);if(t)return t;let r;e.silent||(r=(0,Vm.default)(`Installing ${s} before first usage...`).start());try{let n=await Gw(s);return r&&r.succeed(),n}catch(n){Vw.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Hm(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 Gw(s){return rs.has(s)||(rs.set(s,Gm(s)),rs.get(s).catch(()=>{rs.delete(s)})),rs.get(s)}async function Gm(s){let e=pc(s);if(e)return e;let t=Hm(s),r=`${s}@${t}`;return await yo(ut(),r),Jt(s)}async function Hw(){let s=Object.keys(xa);for(let e of s)await Gm(e)}function Hm(s){let e=Object.entries(xa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Vm,Vw,rs,wr=w(()=>{"use strict";Vm=E(require("ora"));zs();j();B();Hn();qs();Vw=A("lazy-require"),rs=new Map});var Km={};V(Km,{preloadTests:()=>cn});async function cn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await pt(async()=>{let t=await ae(s.testId,r=>Cc({...e,testId:r}),{concurrency:2});return zm.keyBy(t,"testData.id")},"loadTests",qw,[e,s.testId])()}var zm,qw,Bo=w(()=>{"use strict";zm=E(require("lodash"));Ut();be();B();qw=1e3*60*60*10});function Il(){return lt()}async function Xm(){if(!ke)try{let s=await ce(Kw(),5e3,"The API call to NPM timed out"),e=Il();e&&Ym.lt(e,s)&&console.log(Jm.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){zw.warn("Failed to get NPM version",{err:s})}}var Jm,Ym,zw,Kw,Rl=w(()=>{"use strict";Jm=E(require("chalk")),Ym=E(require("semver"));B();le();zs();Ut();j();zw=A("npm-driver"),Kw=pt(()=>Vd("@testim/testim-cli"),"getNpmVersion")});var xl,Yw,ss,Qm,Zm,Al,ef,tf=w(()=>{"use strict";B();z();j();wr();xl=A("testimNgrok"),Yw=".whitelisted-ngrok.testim.io",ss="",Zm=async(s,e={})=>{if(!e.ngrokToken)throw new C("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${re()}-${s.projectData.projectId}${Yw}`);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://")?(xl.info("replace https to http"),ss=o.replace("https://","http://")):ss=o,s.tunnelDiagnostics&&Al(),s.baseUrl=ss},Al=async(s=!0)=>{try{let t=(await Ee("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===ss);console.log("ngrok stats",n),xl.info("ngrok stats",{tunnel:n})}catch(e){xl.error("error collecting ngrok stats",{err:e})}s&&(Qm=setTimeout(()=>Al(),1e4))},ef=async s=>{if(!ss)return;clearTimeout(Qm),s.tunnelDiagnostics&&await Al(!1),await(await Ee("ngrok")).disconnect(ss)}});var Zt,Pl,rf,Qw,Zw,Cl,jo,Wo,$o,ev,sf,nf,of=w(()=>{"use strict";Zt=E(require("os")),Pl=E(require("fs")),rf=E(require("child_process"));B();be();Qw="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",Zw={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"}},Cl=Zt.tmpdir(),jo=`${Cl}/cloudflared`,Wo=null,$o=null,ev=async()=>{if(await fe(jo))return;let e=Zw[Zt.platform()+Zt.arch()];if(!e)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let t=e.extract?Cl+e.path:jo;await ze(`${Qw}/${e.path}`,t),e.extract&&await tt(t,Cl),await Pl.promises.chmod(jo,"755")},sf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Xc(s.company.companyId,t),ev()]);Wo=r._id,$o=rf.spawn(jo,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await Qc(s.company.companyId,Wo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Pl.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},nf=async s=>{let e=[];return Wo&&e.push(Zc(s.company.companyId,Wo)),$o&&e.push(new Promise((t,r)=>{$o.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),$o.kill()})),await Promise.all(e)}});var af,cf,Wt,lf,uf,pf,Vo,df,kl,rv,sv,ln,nv,ov,te,Go=w(()=>{"use strict";af=E(require("ms")),cf=E(require("p-retry")),Wt=E(require("os")),lf=E(require("portfinder")),uf=E(require("child_process"));B();qe();be();pf=E(require("fs")),Vo=E(require("fs/promises")),df=require("path");z();j();Mo();ie();ge();B();kl=A("lambdatestService"),rv="https://downloads.lambdatest.com/tunnel/v3",sv={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"},ln=`${Wt.tmpdir()}/LT`,nv=`${ln}/LT`,ov=(0,af.default)("15m"),te=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){te.isLambdatestGrid(e)&&(te.lambdatestConfigPromise||=Vc(),te.lambdatestConfig=await te.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?ov:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await fe(nv))return;let t=sv[Wt.platform()+Wt.arch()];if(!t)throw new Error(`tunnel on ${Wt.platform()+Wt.arch()} platform is not supported.`);let r=`${ln}.zip`;await ze(`${rv}/${t}`,r),await tt(r,ln)}static async chmodLtTunnel(e){if(!(Wt.platform()==="win32"||!await fe(e))){try{await Vo.access(e,pf.constants.X_OK);return}catch{}try{await Vo.chmod(e,"777")}catch(r){throw kl.error("Failed to make LT tunnel executable",{e:r}),r}}}static async connectTunnel(e){if(e.externalLambdatestTunnelId){te.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await lf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;te.tunnelName=re();let l=["--tunnelName",te.tunnelName,"--infoAPIPort",String(t)];if(M.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],i&&a)l=[...l,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(M.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...rc(u)])}if(M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)l=[...l,"--user",n,"--key",o];else throw new C("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ne(3e3),await te.chmodLtTunnel((0,df.join)(ln,"LT")),te.tunnel=uf.spawn("./LT",l,{cwd:ln});let d="",m="";te.tunnel.stdout.on("data",u=>{d+=u.toString()}),te.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,cf.default)(()=>Re(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});kl.info("LT tunnel info",u)}catch(u){throw kl.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!te.tunnel))return new Promise((t,r)=>{te.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),te.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=te.lambdatestConfig.CAPABILITIES[t]||{},a={...te.tunnelName&&{tunnel:!0,tunnelName:te.tunnelName}},c=[],{mode:l,canary:d,ext:m,extensionPath:u,installCustomExtension:f}=e;if(l===Y.EXTENSION&&!m){let g=pl({canary:d},!0);!u&&g[t]&&(c=[...c,g[t]]),u&&je(u)&&(c=[...c,u])}return f&&je(f)&&(c=[...c,f]),{build:r,name:`${n} - ${o}`,platform:te.lambdatestConfig.PLATFORM,selenium_version:te.lambdatestConfig.SELENIUM_VERSION,resolution:te.lambdatestConfig.RESOLUTION,timezone:te.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled(),ntlm:M.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}});var Ol={};V(Ol,{connect:()=>qo,disconnect:()=>zo,serveTunneling:()=>av});var Ho,mf,ff,iv,qo,zo,av,_l=w(()=>{"use strict";tf();sn();of();xt();Ho=E(require("ora"));j();ie();Go();mf=A("tunnel"),ff=s=>{var e;return[O.LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},iv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},qo=async s=>{if(!s.tunnel)return;let e=Ft(),t;try{ff(s)?(t=(0,Ho.default)("Starting testim lambdatest tunnel...").start(),await te.connectTunnel(s)):iv(s)?(t=(0,Ho.default)("Starting testim cloudflare tunnel...").start(),await sf(s)):(t=(0,Ho.default)("Starting testim ngrok tunnel...").start(),await Zm(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw mf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},zo=async s=>{if(s.tunnel)try{ff(s)?await te.disconnectTunnel(s):"tunnelRoutes"in s?await nf(s):await ef(s)}catch(e){let t="catch error - failed to close tunnel";throw mf.error(t,{err:e}),new Error(t)}},av=async(s,e=new Promise(()=>{}))=>(await qo(s),Zr(()=>zo(s)),await e)});function cv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=gf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function lv(s){let e=gf.exec(s);return e==null?void 0:e[3]}function Jo(s){var I,b,T,R,k,_,$,S,x,D,F;let e=s&&lv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&cv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(I=s==null?void 0:s.hybrid)==null?void 0:I.tunnel,c=(b=s==null?void 0:s.external)==null?void 0:b.user,l=(T=s==null?void 0:s.external)==null?void 0:T.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((_=(k=(R=s.hybrid)==null?void 0:R.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:_.user):c,u=d===O.HYBRID?a&&((x=(S=($=s.hybrid)==null?void 0:$.external)==null?void 0:S[s.hybrid.tunnel])==null?void 0:x.key):l,f=s==null?void 0:s.name,g=s&&(s._id||s.gridId),h=s==null?void 0:s.provider,y=(D=s==null?void 0:s.mobileTokens)==null?void 0:D.androidToken,v=(F=s==null?void 0:s.mobileTokens)==null?void 0:F.iosToken;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:g,tunnel:a,user:c,key:l,type:d,name:f,provider:h,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:v}}async function yf(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error($r.UNKNOWN)}if(Xe.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error($r.UNKNOWN);if(o.status==="success"){let i=Jo(o.grid);return uv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new vt($r.NOT_FOUND):o.code==="no-available-slot"?new Nr(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new vt($r.UNKNOWN))}function pv(s,e,t,r,n,o){return yf(t,e,s,n,()=>Ao(e,t,r,n,o))}function dv(s,e,t,r,n,o,i){return yf(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?Ao(e,t,c._id,n,o):jc(e,t,r,n,o)})}function bf(s){return Wc(s)}async function Tf(s,e,t){let n=(t||await bf(s)).find(o=>o._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return Jo(n)}async function mv(s,e,t){let n=(t||await bf(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return Jo(n)}async function Ll(s,e){let t=un[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete un[s],!r){Xe.warn("failed to find grid slot id",{projectId:e});return}Xe.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Fc(i,e,r,n,o)}catch(a){Xe.error("failed to release slot",{projectId:e,err:a})}}async function fv(s){let e=Object.values(un).filter(Boolean);if(e.length!==0){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await Uc(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function gv(s){hf=global.setInterval(fv,1e4,s)}async function hv(s){let e=Object.keys(un);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await ae(e,t=>Ll(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function yv(s){await hv(s),clearInterval(hf)}function bv(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 wf(s){let t=(()=>Ko.isEmpty(s.testobjectSauce)?Ko.isEmpty(s.saucelabs)?Ko.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=bv(t,s),c=Tv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function vf(s,e){let t=s.company.companyId;return await Tf(t,e.gridId,s.allGrids)}async function Ef(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 wf(s);let l=t==null?void 0:t.companyId;if(a)return Tf(l,a,e);if(c)return mv(l,c,e);if(js(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new vt("Missing host or grid configuration")}async function Sf(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(l||d||c)return{mode:"local"};if(n)return wf(t);if(a)return pv(r,u,o,a,s,e);if(i)return dv(r,u,o,i,s,e,t);throw new vt("Missing host or grid configuration")}var Ko,Xe,un,gf,hf,uv,pn,If,ns=w(()=>{"use strict";Ko=E(require("lodash"));be();j();B();ie();z();Xe=A("grid-service"),un={},gf=/(^(https?):\/{2})?(.*)/,hf=null;uv=(s,e,t,r,n)=>{un[s]={gridId:t,companyId:e,slotId:r,browser:n}};pn={start:gv,end:yv};If=async(s={},e={},t={},r={},n={})=>{var g,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===O.LAMBDATEST&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e)),a!==O.HYBRID||!o||!c||!d||!m))return e;let u=await Bc({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:c,usingTunnel:l});Xe.info("handling hybrid grid",{response:u,companyId:o});let f=Jo({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});function mn(){return Yo||"master"}function Rf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Yo="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){Yo=s.branch||s;return}Yo=e?"master":void 0}var Yo,Dl=w(()=>{"use strict";z()});var fn,Ml,wv,Nl,vv,Xo,Qo,Zo,ei,ti,ri=w(()=>{"use strict";B();ie();fn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},Ml=s=>{let{status:e}=s;return e===pe.ABORTED},wv=s=>{let{status:e}=s;return e===pe.PASSED},Nl=s=>s.runnerStatus===Ya.SKIPPED,vv=s=>s.testStatus===Ke.EVALUATING,Xo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Nl(t)&&(Je(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Qo=s=>Object.values(s).filter(e=>fn(e)&&vv(e)).length,Zo=s=>Object.values(s).filter(fn),ei=s=>Object.values(s).filter(wv),ti=s=>Object.values(s).filter(Ml)});function Sv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Ul,si,Ev,ni,Af=w(()=>{"use strict";Ul=E(require("lodash"));j();ri();si=A("debug-reporter"),Ev=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ni=class{constructor(e){this.options=e}onTestStarted(e,t){si.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;si.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Ul.default.omit(this.options,Ev),company:Ul.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let c=Sv(process.argv);si.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,o){let i=ei(e).length,a=Object.keys(e).length-i;si.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Fl,Ct,gn=w(()=>{"use strict";ie();Fl=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===O.DEVICE_FARM}},Ct=new Fl});var jl={};V(jl,{Reporter:()=>Iv});var er,hn,vr,oi,Cf,Bl,Iv,$l=w(()=>{"use strict";er=E(require("chalk")),hn=E(require("lodash"));B();ie();gn();ri();vr={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:oi}=Mt,Cf="device",Bl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${er.default.underline(He(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?pe.PASSED:pe.FAILED,n=`(${e.testId})`,o=vr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${so(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=He(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
|
|
22
|
-
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=Zo(e),a=ei(e),c=ti(e),l=a.length,d=c.length,m=i.length,u="",f="";if(Ct.isTestStatusEnabled){let I=Qo(e);u=` FAILED-EVALUATING: ${I}`,m-=I,f=` SKIPPED: ${Xo(e,this.options)}`}let g=this.buildTestPlanName(o,t),h,y=vr[m?"error":"success"],v=`PASSED: ${l} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${so(r)}`;g.trim()===""||g.trim()==="Anonymous"?h=`Tests completed. ${v} (Execution ID: ${n})`:h=`Test plan${g} completed ${v} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=hn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=hn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=hn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=hn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let c=u=>{u.forEach((f,g)=>{var v;let h=(v=f.testData)!=null&&v.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",g+1,":",`${f.name}${Je(f,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===oi.APPIUM?Cf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(r)}`)}onGetSession(e,t,r){let n=r===oi.APPIUM?Cf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===oi.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===oi.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Iv=Bl});var Gl={};V(Gl,{Reporter:()=>kv});function Rv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function xv(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 Av(s){return`${s.visitedUrlsJson||""}`}async function Cv(s,e,t,r,n,o){function i(u){let f=He(s,t,u.testId,u.resultId,r),g={$:{name:Rv(u),classname:n,time:sc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(fn(u)||Ml(u)){let h=`Step Failed: ${u.failureReason||u.reason}`,y=fn(u)?`${h} More info at: ${f}`:h;g.failure={$:{message:y}}}return Nl(u)&&Je(u,o)&&Ct.isTestStatusEnabled&&(g.skipped={}),o.urls&&(g["visited-urls-list"]=xv(u),g["visited-urls-json"]=Av(u)),g}function a(u){let{results:f,testPlanName:g,configName:h}=u,y=f||{},I={name:(h&&g?`${g} with config '${h}'`:g)||"selenium run",tests:l(y),failures:d(y),timestamp:c(e)};if(Ct.isTestStatusEnabled){I.skipped=Xo(y,o);let b=Qo(y);I.failures-=b,I["failure-evaluating"]=b}return{$:I,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(u){let f=Object.keys(u).map(h=>u[h].startTime),g=Math.min.apply(null,f);return g?new Date(g).toISOString():new Date().toISOString()}function l(u){return Object.keys(u).length}function d(u){return Zo(u).length+ti(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Vl.Builder().buildObject(m)}catch(u){return Pv(u)}}function Pv(s){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:s.message}}}}}};return e.buildObject(t)}var Vl,Pf,Wl,kv,Hl=w(()=>{"use strict";Vl=E(require("xml2js"));B();Pf=require("fs");gn();ri();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,r=this.options.project,n=await Cv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Pf.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)}};kv=Wl});var kf={};V(kf,{Reporter:()=>Ov});function os(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 ql,zl,Ov,Of=w(()=>{"use strict";j();ql=A("team-city-reporter");zl=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 os(n)}onTestStarted(e,t,r,n){if(r){ql.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){ql.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${os(t)}' details='${os(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){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,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${os(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${os(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${os(t)}']`)}},Ov=zl});var _f={};V(_f,{Reporter:()=>_v});var Kl,_v,Lf=w(()=>{"use strict";Kl=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,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}}))}},_v=Kl});var Df={};V(Df,{Reporter:()=>Lv});var Jl,Lv,Mf=w(()=>{"use strict";B();dl();Jl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=He(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Uo(t)}},Lv=Jl});var Ux,Yl,Q,Pt=w(()=>{"use strict";Af();j();Ux=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 r=e.reporters;if(this.reporters.push(new ni(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>($l(),jl));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([r.includes("teamcity")&&Promise.resolve().then(()=>(Of(),kf)),r.includes("console")&&Promise.resolve().then(()=>($l(),jl)),r.includes("junit")&&Promise.resolve().then(()=>(Hl(),Gl)),r.includes("json")&&Promise.resolve().then(()=>(Lf(),_f)),r.includes("chrome")&&Promise.resolve().then(()=>(Mf(),Df))])).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))}}},Q=new Yl});function Uf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Ff({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:u,projectType:f,appSource:g,gridType:h}){let y=Uf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:Nf(l,d),isStartUp:u,projectType:f,gridType:h,...["android","ios"].includes(f)&&g&&{appSource:g}},m);dt("test-run-ci",y)}function Bf({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:u,logger:f,isStartUp:g,projectType:h,appSource:y,gridType:v}){try{let I=Uf({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Nf(d,m),isStartUp:g,projectType:h,gridType:v,...["android","ios"].includes(h)&&y&&{appSource:y}},u);if(n.success){dt("test-run-ci-success",I);return}dt("test-run-ci-fail",Object.assign({},I,{failureReason:n.failureReason}))}catch(I){f.error("failed to update test end analytics",{err:I})}}function jf(s){dt("batch-run-ci",s)}var Nf,Xl=w(()=>{"use strict";es();Io();Nf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Xr&&e?"ci-with-user":Xr?"ci":e?"cli-with-user":s});var Wf,ii,Vf=w(()=>{"use strict";Wf=require("istanbul-lib-report"),ii=class extends Wf.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 Gf,Hf,qf,yn,mt,zf,ai,Ql,Kf,Dv,Jf,Yf,Mv,Nv,Xf,Uv,Fv,Bv,jv,$v,Qf,Zf=w(()=>{"use strict";Gf=E(require("ora")),Hf=E(require("dayjs")),qf=E(require("test-exclude")),yn=E(require("fs")),mt=E(require("path")),zf=E(require("istanbul-reports")),ai=E(require("istanbul-lib-report"));be();z();B();j();wr();Vf();Ql=A("test-run-status"),Kf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Dv=s=>!!Kf(s).search,Jf=s=>s?Kf(s).pathname.substring(1):"",Yf=(s,e)=>{let t=Jf(e);return!new qf.default({relativePath:!1,include:s}).shouldInstrument(t)},Mv=s=>s.substring(0,s.indexOf("?")),Nv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ee("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Xf=(s,e)=>`${mt.resolve(s,Jf(e))}.js`,Uv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ae(o.sources,async(i,a)=>{if(Yf(r,i))return;let c=Xf(e,i);await yn.promises.mkdir(mt.parse(c).dir,{recursive:!0}),await yn.promises.writeFile(c,o.sourcesContent[a])})})},Fv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Dv(e)&&(e=Mv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=mt.dirname(this.getPath(s));return mt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Bv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=ai.createContext({dir:t,coverageMap:e,watermarks:ai.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Xf(r,a);return yn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ii({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Fv}),zf.create(a,c).execute(i)}),o},jv=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=>Yf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},$v=async(s,e)=>{let{mergeProcessCovs:r}=await Ee("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await Hc(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await en(c,9e4);await ae(l,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await xc(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}},Qf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Ql.info("start js coverage process");let n=(0,Gf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=mt.resolve(s.codeCoverageReportPath||"./coverage"),i=mt.resolve(o,`.js/${(0,Hf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?mt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([Ee("istanbul-lib-coverage"),$v(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({}),u={};await ae(l.result,async({url:g,functions:h})=>{let{text:y,sourceMapType:v}=d.get(g),I=await Nv({sourceMapType:v,source:y,sourceMapDir:a});u[g]=I;let b=await jv(s,{source:y,sourceMap:I,functions:h});m.merge(b)}),await Uv(s,i,u);let f=await Bv(s,m,o,i);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Ql.error(l,{err:c})}}});var eg={};V(eg,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>Er});var Ae,Wv,Er,is=w(()=>{"use strict";B();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Wv=["ALL",...Object.values(Ae)],Er=class{constructor(){this.marks=Object.fromEntries(Wv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,io(r,50)],[`${t}_P95`,io(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var ng={};V(ng,{initServer:()=>Hv,mapFilesToLocalDrive:()=>eu});function eu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,ci[t.id]?{screenshot:ci[t.id]}:{})),Object.keys(li).forEach(t=>{s.assets||={},s.assets[sg[t]]=li[t]}),s.assets||={},s.assets.screenshots=Object.values(ci)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Hv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ee("multer"),n=typeof t=="string"?t:Vv;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 u=bn.join(n,m.testResultId);try{await Zl.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(c,l,d){let{fileName:m}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=bn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,rg.default)();i.post("/",o.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(ci[d.stepId]=c.file.path),d.testResultId&&Gv.includes(d.subType)&&(li[d.subType]||=[],li[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(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(u)}}})}var Zl,tg,bn,rg,Vv,ci,li,sg,Gv,tu=w(()=>{"use strict";Zl=E(require("fs")),tg=E(require("os")),bn=E(require("path")),rg=E(require("express"));z();wr();Vv=bn.join(tg.tmpdir(),"testim/rca/"),ci={},li={},sg={"test-log":"consoleLogs","har-file":"networkLogs"},Gv=Object.keys(sg)});var tr,ru,ui,og=w(()=>{"use strict";tr=E(require("lodash"));B();j();ru=A("override-test-data-builder"),ui=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return tr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):ru.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):ru.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}ru.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return tr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(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=re();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 pi(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Sr,Qe,qv,zv,Kv,Jv,di,ig=w(()=>{"use strict";Sr=E(require("lodash"));B();ie();ns();be();z();j();Pt();sn();Zf();is();tu();le();ge();og();gn();Qe=A("test-run-status"),qv=fr(),zv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Kv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Jv=lt();di=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 Er;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Bs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Jn||t.parallel||1,browser:o,gitBranch:qv,gitCommit:zv,gitRepoUrl:Kv,runnerVersion:Jv,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:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:I}=a,b={originalTestResultId:t,previousTestResultId:r,config:Sr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},b,{testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:I}),Jc({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,Q.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 Po(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let c=Sr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,br(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Je(e,this.options))return;let n=this.exportsGlobal;try{let o=await pi(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 Qe.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}),Qe.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===Ke.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ke.EVALUATING} status`);return}if(l){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,He(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);Q.onTestIgnored(e,r,`test in ${Ke.QUARANTINE}`)}monitorMemoryUsage(e){let t=nc();if(t.isOverThreshold){let r=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Qe.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&&eu(i,Qe),i.resultUrl=He(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),Q.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 pi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Qe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await br(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=Za;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,g,h;let c=e.browser?Gs(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Vr(M,n)&&$s(a.nativeApp)&&!e.appId,d=Ws(e)&&(Wr(a.nativeApp,n)||l),m=Je(a,e)||d,u={testId:a.testId,status:m?pe.SKIPPED:pe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ke.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:Object.assign({},this.execConfig,{companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((h=a.testData)==null?void 0:h.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()})};return[a.resultId,u]});return Object.fromEntries(o)}async executionStart(e,t,r,n,o){Qe.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Zr(()=>Promise.all([pn.end(t),xo("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},d=await pi(i.beforeSuite,l),m=new ui(d,Sr.cloneDeep(this.testInfoList),t);this.testInfoList=m.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=d;let{testInfoList:u}=this,f=[],g=[],h=[];for(let v of u){if(v.isBeforeTestPlan){f.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}g.push(v)}let y=async()=>{let v=Sr.cloneDeep(this.testRunStatus);await ae(Object.keys(v),async R=>{var x;let k=v[R],_=(x=k.config)==null?void 0:x.testData,$=k.testId,S=await Po(t,$,R,_,c.defaults);S&&(delete k.config.testData,k.config.testDataUrl=S)});let I=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:I,intersections:i.intersections},T=Oc(b);return this.executionStartedPromise=T,T.catch(R=>Qe.error(R)),T};try{await y()}catch(v){Qe.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:f,tests:g,afterTests:h}}concatSeleniumPerfMarks(e){Sr.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=ic(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===pe.PASSED&&n++,m===pe.SKIPPED&&o++,m===pe.FAILED&&u===Ke.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await pi(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"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Qf(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await xo("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 Qe.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 kc(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function Xv(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function au(s){return lg.readFileSync(s,{encoding:"base64"})}function mg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&je(s))&&s){let r=au(s);as.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${iu(r)} current extension count: ${e.length}`),e.push(r)}}function fg(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}`;as.info(`adding extension: testim unpacked , path: ${l}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=ou.join(process.cwd(),`testim-headless${o}`),a=au(i);as.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${iu(a)} current extension count: ${e.length}`),e.push(a)}function Qv(s,e,t,r,n,o,i){var g,h;let a=t.seleniumName||t.browserValue,c=[],l=[...dg];e.headless&&l.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":su.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":su.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};nu(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-2",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),nu(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"]=su.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(g=e.projectData)==null?void 0:g.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+Xa.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),mg(r,c,i),e.mode===Y.EXTENSION&&fg(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 u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return te.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${f}:${u}`]=d),s}function eE(s,e,t){let r={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":cg.join(","),"browser.helperApps.neverAsk.openFile":cg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Y.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=ou.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=au(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function tE(s){return`${s.width}x${s.height}`}function rE(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,pg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=tE(r.resolution||t.sl.screenResolution),delete i.screenResolution),st.merge(i,o,n)}return st.merge(o,n)}return{}}function sE(s,e,t){return st.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 nE(s){return s.perfecto?s.perfecto:{}}function oE(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 iE(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=Sa(o,i)),a}function mi(s){var v;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:c,lambdatestService:l}=s;if(o.mode==="local"){let I=[],b=[...dg],T={};return t.headless&&b.push("--headless"),t.silentDebuggerExtensionApi&&b.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&b.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>b.push(`--${R}`)),t.chromeBinaryLocation&&(T.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&fg(t,I,b,null,l),mg(i,I,l),{logLevel:ag,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:b,extensions:I,...T},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=iE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:ag,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(l.getSessionTimeout,t.getSessionTimeout),getSessionRetries:l.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!st.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};nu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let g=Number(t.browserTimeout/1e3),h=t.browser||(n==null?void 0:n.browserValue);st.merge(f.desiredCapabilities,rE(t,r,n,e),sE(t,r,n),nE(t),oE(t,h,g),l==null?void 0:l.getCapabilities(t,h,a,c,r));let y=null;switch(!t.ext&&!t.extensionPath&&((v=o.host)!=null&&v.endsWith(".testim.io"))&&!t.canary&&t.mode===Y.EXTENSION&&(y="/opt/testim-headless"),h){case"chrome":case"edge-chromium":f=Zv(f,t,n,i,o,y,l);break;case"firefox":f=eE(f,t,l);break;case"safari":case"safari technology preview":f=Xv(f,h);break;default:break}st.merge(f.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},b=_=>_[o.provider]||_[f.host]||_[I[f.host]],T=_=>{var $,S;return b(_)||_[($=f.desiredCapabilities)==null?void 0:$.browserName]||_[(S=f.desiredCapabilities)==null?void 0:S.version]||_||{}},R=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),k=T(T(R));Object.keys(k).length&&(as.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(f.desiredCapabilities,k))}catch(I){as.error("Failed to load custom capabilities",{error:I,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return f.desiredCapabilities&&!f.capabilities&&(Yv(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,f}var lg,ou,ug,st,pg,as,ag,su,dg,iu,nu,Yv,Zv,cg,cu=w(()=>{"use strict";lg=E(require("fs")),ou=E(require("path")),ug=E(require("crypto")),st=E(require("lodash"));B();le();j();ge();ie();Go();pg=require("lodash"),as=A("testim-desired-capabilities-builder"),ag=Kn?"debug":"silent",su={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},dg=["--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"],iu=(...s)=>ug.createHash("sha256").update(s.join("")).digest("hex"),nu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",Yv=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{as.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};Zv=st.memoize(Qv,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(st.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return iu(i,a,c,r,l,o)}),cg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ne(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function hg(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 lu=w(()=>{"use strict"});function uu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let g=u;g&&g!==u.ownerDocument;g=g.parentNode)if(f(g))return g;return null}function n(u,f){for(let g=u;g&&g!==u.ownerDocument;g=t(g))if(f(g))return g;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let h=window.getComputedStyle(u).getPropertyValue(f);if(h&&h!=="inherit")return h;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let h=o(u,"stroke-width");return!!h&&parseInt(h,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(u){return o(u,"overflow")==="hidden"}function c(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,g=>g.tagName.toUpperCase()==="SELECT");return uu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||c(s))}var yg=w(()=>{"use strict"});var bg,Tg,Vt,aE,cE,fi,wg=w(()=>{"use strict";bg=E(require("promise-queue")),Tg=E(require("webdriverio"));le();Be();B();j();Or();yg();lu();is();Vt=A("WebDriverApi"),aE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},cE={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 Vt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Aa!==void 0&&(e=Aa);let t=1/0;this.queue=new bg.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(),N("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{Vt.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),this.client=await Tg.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ae.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let c of a.slots||[])if(((i=c==null?void 0:c.session)==null?void 0:i.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){Vt.info("grid status is not supported by the grid",{testResultId:e});return}Vt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Vt.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){Vt.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Ne(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Ne(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ae.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,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 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(uu,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ne(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(hg(e,this.isSafari(),Vt))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[cE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Ne(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(aE);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=>Object.hasOwn(va,i)?[va[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(Array.isArray(e))for(let i of e)r=r.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:r})},o=()=>{let i=r.map(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ne(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(_e(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Ne(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Vt.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Vt.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var vg={};V(vg,{doubleClick:()=>lE});var lE,Eg=w(()=>{"use strict";lE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function f(I,b,T){return T>I&&T<b}let g=u.pointerPosition||{},h=r.getBoundingClientRect(),y=g.originX&&f(h.left,h.left+h.width,g.originX)?g.originX:h.left+h.width/2,v=g.originY&&f(h.top,h.top+h.height,g.originY)?g.originY:h.top+h.height/2;return{x:y,y:v}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(u,f,g){if(!window.PointerEvent)return;let h=a(f,g);return new window.PointerEvent(u,h)},l=function(u,f,g){let h=document.createEvent("MouseEvents");return h.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,g,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),g=u.event;return t.includes(g)?c(g,f.x,f.y):l(g,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Tn={};V(Tn,{dispatchFocus:()=>uE});function uE(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 wn=w(()=>{"use strict"});var Ag={};V(Ag,{WebDriver:()=>Rr});async function fE(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 dE(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var cs,Rg,xg,Ue,rr,pE,Sg,dE,sr,mE,Ig,Ir,Rr,vn=w(()=>{"use strict";cs=E(require("lodash"));B();Be();cu();Rg=E(require("p-retry")),xg=E(require("ua-parser-js"));Or();j();lu();wg();z();ge();is();Ue=A("webdriver"),[rr,pE]=[0,2],{extractElementId:Sg,getCdpAddressForHost:dE}=K,sr=()=>(Te(),he(Qt)).getSessionPlayer().codeSnippets,mE=()=>(Te(),he(Qt)).getSessionPlayer().locatorBuilderUtils,Ig=()=>(Te(),he(Qt)).getSessionPlayer().utils,Ir=()=>(Te(),he(Qt)).getSessionPlayer().positionUtils;Rr=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;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var v,I,b,T,R,k,_,$;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:c,executionId:l,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((b=(I=(v=n==null?void 0:n.company)==null?void 0:v.activePlan)==null?void 0:I.premiumFeatures)==null?void 0:b.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=mi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:c,executionId:l,testResultId:d,lambdatestService:f,overrideConfiguration:r});g.desiredCapabilities&&delete g.desiredCapabilities.marionette,g.capabilities&&delete g.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let h=u?0:1500,y=u?()=>null:()=>this.executeJS("window.focus()");try{N("before initClient in webdriver.js init");let S=await this.initClient(g,o,d);N("after initResult before getCdpAddress in init"),this.cdpUrl=await fE(S),N("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await ne(h),M.flags.dontFocusOnInit.isEnabled()||await y(),N("after focus and delay in webdriver.js init")}catch(S){let x=JSON.stringify(cs.omit(g,"capabilities.extensions","capabilities.capabilities.extensions"));Ue.error("failed to init webdriver",{err:S,capabilitiesAsString:x});let D=((R=(T=n==null?void 0:n.company)==null?void 0:T.activePlan)==null?void 0:R.plan)==="free";throw(k=S.stack)!=null&&k.includes("at startWebDriverSession")&&((_=S.message)!=null&&_.startsWith("Failed to create session"))&&(($=S.message)!=null&&$.includes("Timeout awaiting 'request'"))&&D?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):S.message.match(/Invalid username or password/)?new Mr(S.message):S.message.match(/capabilit(y|ies)/)?new Yn(S.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>cs.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=re();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ue.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ue.warn("failed to click on alert",{err:c}));return}if(Ue.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ue.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Sg(r.value);return await this.switchToFrame({ELEMENT:n,[Ht]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new Xn:r}}async getElement(t){var o;let r=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(r,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(`
|
|
20
|
+
`))},wl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:vl,argv:Sl,exit:yl,cwd:At}=global.process,Bw=["trace","debug","info","warn","error","silent"];tc(Sl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));El.description("Testim.io CLI").option("-h --help","output usage information",jm).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",Nw).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--is-regression-baseline-run","save doms and run results as regression baseline data").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",De,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(vl.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,bl.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,bl.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: ${wl.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",De,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",De,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",De,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).parse(Sl);p=El.opts(),jw=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},$w=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Ww=async()=>{var v,I,b,T,R,k,_,$;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!Sl.slice(2).length)throw jm(),new Dr;if(p.requireCredentials){let S=await Promise.resolve().then(()=>(ts(),an)),x=await S.getProjectId(),D=await S.getToken();(!x||!D)&&await S.doLogin()}if(p.login)return await(await Promise.resolve().then(()=>(ts(),an))).doLogin(),{loginMode:!0};if(p.version){let S="Testim CLI Version: ";vl.npm_package_version&&(console.log(S,vl.npm_package_version),yl(0));let x=ut();x&&(console.log(S,x),yl(0)),console.log("Could not find version, please check the package.json manually"),yl(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Fd(),p.clearFileCache&&qr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let S=Me.resolve(n);Nd(S)}if(p.usePrefechedData&&Bd(),p.playerRequirePath){let S=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",S);let x=Me.join(S,"tsconfig.node.json"),F=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${$t.escapeRegExp(Me.relative(At(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:F.config.options.paths,baseUrl:F.config.options.baseUrl}),(Te(),he(Qt)).options.playerPath=S;let H=require("module"),X=H.prototype.require;H.prototype.require=function(Tt){return Tt==="rox-alias"?X.call(this,"rox-node"):X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Tl.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new C("missing --proxy option");if(km(p))return Om(p);try{let S={};p.configFile?S=require(Me.join(At(),p.configFile)).config:p.optionsFile&&(S=require(Me.join(At(),p.optionsFile))),S&&typeof S.then=="function"&&(S=await S),Object.keys(S).forEach(x=>{let D=Mw(x);p[D]=Uw(p[D],S[x])})}catch(S){throw S.message=`Unable to read options file: ${S.message}`,S}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((v=p.testConfig)==null?void 0:v.length)||((I=p.testConfigId)==null?void 0:I.length),i=((b=p.testPlan)==null?void 0:b.length)||((T=p.testPlanId)==null?void 0:T.length),a=((R=p.suite)==null?void 0:R.length)||((k=p.suiteId)==null?void 0:k.length);if(p.seleniumCapsFile)try{r=require(Me.join(At(),p.seleniumCapsFile))}catch(S){throw new C(`Failed to parse selenium caps file file error: ${S.message}`)}if((_=p.reporters)!=null&&_.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(At(),p.chromeExtraPrefs))}catch(S){throw new C(`Failed to read/open chrome extra prefs file error: ${S.message}`)}if(p.chromeExtraArgs){let S=p.chromeExtraArgs.split(",");for(let x of S){let[D]=x.split("=");Nm.includes(D)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),D==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${D}), allowed values: ${JSON.stringify(Nm)}`)}}if(p.paramsFile)try{s=Object.assign({},s,require(Me.join(At(),p.paramsFile)))}catch(S){throw new C(`Failed to read/open params file error: ${S.message}`)}if(p.params)try{s=Object.assign({},s,JSON.parse(p.params))}catch(S){throw new C(`Failed to parse params string error: ${S.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(jw(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let S=require(Me.join(At(),p.sauceOptions)),x=S.platformName&&["ios","android"].includes(S.platformName.toLowerCase());if(S.browserName){let F=S.browserName.toLowerCase();switch(F){case"microsoftedge":p.browser="edge";break;default:p.browser=F}}p.browser==="edge"&&parseFloat(S.version)>=Ea&&(p.browser="edge-chromium");let D=parseFloat(S.version)<50&&!["dev","beta"].includes(S.version);if(!x&&p.browser==="chrome"&&D)throw new C("The minimum chrome supported version is 50.0");p.saucelabs=Object.assign({},p.saucelabs,S)}catch(S){throw new C(`Failed to parse saucelabs options file error: ${S.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&($w(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let S=require(Me.join(At(),p.browserstackOptions)),x=S.platform&&["mac","android"].includes(S.platform.toLowerCase());if(S.browserName&&(p.browser=S.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(S.browser_version)>=Ea&&(p.browser="edge-chromium"),!x&&parseFloat(S.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack=Object.assign({},p.browserstack,S)}catch(S){throw new C(`Failed to parse browserstack options file error: ${S.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let S=require(Me.join(At(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto=Object.assign({},x,S)}catch(S){throw new C(`Failed to parse perfecto options file error: ${S.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let S=require(Me.join(At(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce=Object.assign({},x,S)}catch(S){throw new C(`Failed to parse test object options file error: ${S.message}`)}if(!p.project){let x=await(await Promise.resolve().then(()=>(ts(),an))).getProjectId();if(x)p.project=x;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}M.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.mode??="extension",p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=p.mode===Y.APPIUM?1:Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let l=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let x=await(await Promise.resolve().then(()=>(ts(),an))).getToken();if(x)p.token=x;else throw new C("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let d=S=>S<=0||!Number.isInteger(S);if(d(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.mode!==Y.SELENIUM&&p.disableNativeEvents)throw new C("disable-native-events is only applicable in selenium mode");if(!p.browser&&!o&&!i&&(p.browser="chrome"),p.appiumLogLevel||(p.appiumLogLevel="silent"),!Bw.includes(p.appiumLogLevel))throw new C(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData)throw new C("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if(($=p.host)!=null&&$.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Fm.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let S=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),S.length)throw new C("A result label cannot exceed 250 characters")}let u=Im(p),f=Do(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||i))throw new C("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!$t.inRange($t.parseInt(p.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let g="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${g}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${g}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&$t.difference(p.codeCoverageReporter,wl).length){let S=$t.difference(p.codeCoverageReporter,wl);throw new C(`invalid --code-coverage-reporter parameters ${S.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let h={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(h).filter(S=>Boolean(p[S]));if(p.mode!==Y.EXTENSION&&y.length){let S=y.length>1?"are":"is";throw new C(`${y.map(x=>h[x]).join(" and ")} ${S} only applicable in extension mode`)}if(p.tmsFieldFile)try{let S=Tl.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(S)}catch(S){throw new C(`failed to parse field file error: ${S.message}`)}if(p.highSpeed&&(Fw("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.resetOnSessionStartOnly&&!p.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),p.lightweightMode)try{let S={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode=Object.assign({},S,x)}catch(S){throw new C(`failed to parse lightweightMode settings error: ${S.message}`)}else p.turboMode&&p.mode===Y.EXTENSION?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&p.mode===Y.SELENIUM&&console.warn(`
|
|
21
|
+
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new C("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),webpackConfig:p.webpackConfig,reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?fr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userParamsData:s,mode:p.mode,isRegressionBaselineRun:p.isRegressionBaselineRun,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,resetOnSessionStartOnly:p.resetOnSessionStartOnly,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:l,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0},downloadBrowser:p.downloadBrowser}}});var qm={};V(qm,{installAllLazyDependencies:()=>Hw,lazyRequire:()=>Ee});async function Ee(s,e={}){let t=pc(s);if(t)return t;let r;e.silent||(r=(0,Vm.default)(`Installing ${s} before first usage...`).start());try{let n=await Gw(s);return r&&r.succeed(),n}catch(n){Vw.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Hm(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 Gw(s){return rs.has(s)||(rs.set(s,Gm(s)),rs.get(s).catch(()=>{rs.delete(s)})),rs.get(s)}async function Gm(s){let e=pc(s);if(e)return e;let t=Hm(s),r=`${s}@${t}`;return await yo(pt(),r),Jt(s)}async function Hw(){let s=Object.keys(xa);for(let e of s)await Gm(e)}function Hm(s){let e=Object.entries(xa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Vm,Vw,rs,wr=w(()=>{"use strict";Vm=E(require("ora"));zs();j();B();Hn();qs();Vw=A("lazy-require"),rs=new Map});var Km={};V(Km,{preloadTests:()=>cn});async function cn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await dt(async()=>{let t=await ae(s.testId,r=>Cc({...e,testId:r}),{concurrency:2});return zm.keyBy(t,"testData.id")},"loadTests",qw,[e,s.testId])()}var zm,qw,Bo=w(()=>{"use strict";zm=E(require("lodash"));Ut();be();B();qw=1e3*60*60*10});function Il(){return ut()}async function Xm(){if(!ke)try{let s=await ce(Kw(),5e3,"The API call to NPM timed out"),e=Il();e&&Ym.lt(e,s)&&console.log(Jm.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){zw.warn("Failed to get NPM version",{err:s})}}var Jm,Ym,zw,Kw,Rl=w(()=>{"use strict";Jm=E(require("chalk")),Ym=E(require("semver"));B();le();zs();Ut();j();zw=A("npm-driver"),Kw=dt(()=>Vd("@testim/testim-cli"),"getNpmVersion")});var xl,Yw,ss,Qm,Zm,Al,ef,tf=w(()=>{"use strict";B();z();j();wr();xl=A("testimNgrok"),Yw=".whitelisted-ngrok.testim.io",ss="",Zm=async(s,e={})=>{if(!e.ngrokToken)throw new C("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${re()}-${s.projectData.projectId}${Yw}`);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://")?(xl.info("replace https to http"),ss=o.replace("https://","http://")):ss=o,s.tunnelDiagnostics&&Al(),s.baseUrl=ss},Al=async(s=!0)=>{try{let t=(await Ee("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===ss);console.log("ngrok stats",n),xl.info("ngrok stats",{tunnel:n})}catch(e){xl.error("error collecting ngrok stats",{err:e})}s&&(Qm=setTimeout(()=>Al(),1e4))},ef=async s=>{if(!ss)return;clearTimeout(Qm),s.tunnelDiagnostics&&await Al(!1),await(await Ee("ngrok")).disconnect(ss)}});var Zt,Pl,rf,Qw,Zw,Cl,jo,Wo,$o,ev,sf,nf,of=w(()=>{"use strict";Zt=E(require("os")),Pl=E(require("fs")),rf=E(require("child_process"));B();be();Qw="https://github.com/cloudflare/cloudflared/releases/download/2023.10.0/",Zw={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"}},Cl=Zt.tmpdir(),jo=`${Cl}/cloudflared`,Wo=null,$o=null,ev=async()=>{if(await fe(jo))return;let e=Zw[Zt.platform()+Zt.arch()];if(!e)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let t=e.extract?Cl+e.path:jo;await ze(`${Qw}/${e.path}`,t),e.extract&&await rt(t,Cl),await Pl.promises.chmod(jo,"755")},sf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Xc(s.company.companyId,t),ev()]);Wo=r._id,$o=rf.spawn(jo,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await Qc(s.company.companyId,Wo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Pl.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},nf=async s=>{let e=[];return Wo&&e.push(Zc(s.company.companyId,Wo)),$o&&e.push(new Promise((t,r)=>{$o.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),$o.kill()})),await Promise.all(e)}});var af,cf,Wt,lf,uf,pf,Vo,df,kl,rv,sv,ln,nv,ov,te,Go=w(()=>{"use strict";af=E(require("ms")),cf=E(require("p-retry")),Wt=E(require("os")),lf=E(require("portfinder")),uf=E(require("child_process"));B();qe();be();pf=E(require("fs")),Vo=E(require("fs/promises")),df=require("path");z();j();Mo();ie();ge();B();kl=A("lambdatestService"),rv="https://downloads.lambdatest.com/tunnel/v3",sv={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"},ln=`${Wt.tmpdir()}/LT`,nv=`${ln}/LT`,ov=(0,af.default)("15m"),te=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){te.isLambdatestGrid(e)&&(te.lambdatestConfigPromise||=Vc(),te.lambdatestConfig=await te.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?ov:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await fe(nv))return;let t=sv[Wt.platform()+Wt.arch()];if(!t)throw new Error(`tunnel on ${Wt.platform()+Wt.arch()} platform is not supported.`);let r=`${ln}.zip`;await ze(`${rv}/${t}`,r),await rt(r,ln)}static async chmodLtTunnel(e){if(!(Wt.platform()==="win32"||!await fe(e))){try{await Vo.access(e,pf.constants.X_OK);return}catch{}try{await Vo.chmod(e,"777")}catch(r){throw kl.error("Failed to make LT tunnel executable",{e:r}),r}}}static async connectTunnel(e){if(e.externalLambdatestTunnelId){te.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await lf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;te.tunnelName=re();let l=["--tunnelName",te.tunnelName,"--infoAPIPort",String(t)];if(M.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],i&&a)l=[...l,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(M.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...rc(u)])}if(M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)l=[...l,"--user",n,"--key",o];else throw new C("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ne(3e3),await te.chmodLtTunnel((0,df.join)(ln,"LT")),te.tunnel=uf.spawn("./LT",l,{cwd:ln});let d="",m="";te.tunnel.stdout.on("data",u=>{d+=u.toString()}),te.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,cf.default)(()=>Re(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});kl.info("LT tunnel info",u)}catch(u){throw kl.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!te.tunnel))return new Promise((t,r)=>{te.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),te.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=te.lambdatestConfig.CAPABILITIES[t]||{},a={...te.tunnelName&&{tunnel:!0,tunnelName:te.tunnelName}},c=[],{mode:l,canary:d,ext:m,extensionPath:u,installCustomExtension:f}=e;if(l===Y.EXTENSION&&!m){let g=pl({canary:d},!0);!u&&g[t]&&(c=[...c,g[t]]),u&&je(u)&&(c=[...c,u])}return f&&je(f)&&(c=[...c,f]),{build:r,name:`${n} - ${o}`,platform:te.lambdatestConfig.PLATFORM,selenium_version:te.lambdatestConfig.SELENIUM_VERSION,resolution:te.lambdatestConfig.RESOLUTION,timezone:te.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled(),ntlm:M.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}});var Ol={};V(Ol,{connect:()=>qo,disconnect:()=>zo,serveTunneling:()=>av});var Ho,mf,ff,iv,qo,zo,av,_l=w(()=>{"use strict";tf();sn();of();xt();Ho=E(require("ora"));j();ie();Go();mf=A("tunnel"),ff=s=>{var e;return[O.LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},iv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},qo=async s=>{if(!s.tunnel)return;let e=Ft(),t;try{ff(s)?(t=(0,Ho.default)("Starting testim lambdatest tunnel...").start(),await te.connectTunnel(s)):iv(s)?(t=(0,Ho.default)("Starting testim cloudflare tunnel...").start(),await sf(s)):(t=(0,Ho.default)("Starting testim ngrok tunnel...").start(),await Zm(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw mf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},zo=async s=>{if(s.tunnel)try{ff(s)?await te.disconnectTunnel(s):"tunnelRoutes"in s?await nf(s):await ef(s)}catch(e){let t="catch error - failed to close tunnel";throw mf.error(t,{err:e}),new Error(t)}},av=async(s,e=new Promise(()=>{}))=>(await qo(s),Zr(()=>zo(s)),await e)});function cv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=gf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function lv(s){let e=gf.exec(s);return e==null?void 0:e[3]}function Jo(s){var I,b,T,R,k,_,$,S,x,D,F;let e=s&&lv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&cv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(I=s==null?void 0:s.hybrid)==null?void 0:I.tunnel,c=(b=s==null?void 0:s.external)==null?void 0:b.user,l=(T=s==null?void 0:s.external)==null?void 0:T.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((_=(k=(R=s.hybrid)==null?void 0:R.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:_.user):c,u=d===O.HYBRID?a&&((x=(S=($=s.hybrid)==null?void 0:$.external)==null?void 0:S[s.hybrid.tunnel])==null?void 0:x.key):l,f=s==null?void 0:s.name,g=s&&(s._id||s.gridId),h=s==null?void 0:s.provider,y=(D=s==null?void 0:s.mobileTokens)==null?void 0:D.androidToken,v=(F=s==null?void 0:s.mobileTokens)==null?void 0:F.iosToken;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:g,tunnel:a,user:c,key:l,type:d,name:f,provider:h,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:v}}async function yf(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error($r.UNKNOWN)}if(Xe.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error($r.UNKNOWN);if(o.status==="success"){let i=Jo(o.grid);return uv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new Et($r.NOT_FOUND):o.code==="no-available-slot"?new Nr(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new Et($r.UNKNOWN))}function pv(s,e,t,r,n,o){return yf(t,e,s,n,()=>Ao(e,t,r,n,o))}function dv(s,e,t,r,n,o,i){return yf(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?Ao(e,t,c._id,n,o):jc(e,t,r,n,o)})}function bf(s){return Wc(s)}async function Tf(s,e,t){let n=(t||await bf(s)).find(o=>o._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return Jo(n)}async function mv(s,e,t){let n=(t||await bf(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return Jo(n)}async function Ll(s,e){let t=un[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete un[s],!r){Xe.warn("failed to find grid slot id",{projectId:e});return}Xe.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Fc(i,e,r,n,o)}catch(a){Xe.error("failed to release slot",{projectId:e,err:a})}}async function fv(s){let e=Object.values(un).filter(Boolean);if(e.length!==0){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await Uc(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function gv(s){hf=global.setInterval(fv,1e4,s)}async function hv(s){let e=Object.keys(un);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await ae(e,t=>Ll(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function yv(s){await hv(s),clearInterval(hf)}function bv(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 wf(s){let t=(()=>Ko.isEmpty(s.testobjectSauce)?Ko.isEmpty(s.saucelabs)?Ko.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=bv(t,s),c=Tv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function vf(s,e){let t=s.company.companyId;return await Tf(t,e.gridId,s.allGrids)}async function Ef(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 wf(s);let l=t==null?void 0:t.companyId;if(a)return Tf(l,a,e);if(c)return mv(l,c,e);if(js(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new Et("Missing host or grid configuration")}async function Sf(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(l||d||c)return{mode:"local"};if(n)return wf(t);if(a)return pv(r,u,o,a,s,e);if(i)return dv(r,u,o,i,s,e,t);throw new Et("Missing host or grid configuration")}var Ko,Xe,un,gf,hf,uv,pn,If,ns=w(()=>{"use strict";Ko=E(require("lodash"));be();j();B();ie();z();Xe=A("grid-service"),un={},gf=/(^(https?):\/{2})?(.*)/,hf=null;uv=(s,e,t,r,n)=>{un[s]={gridId:t,companyId:e,slotId:r,browser:n}};pn={start:gv,end:yv};If=async(s={},e={},t={},r={},n={})=>{var g,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===O.LAMBDATEST&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e)),a!==O.HYBRID||!o||!c||!d||!m))return e;let u=await Bc({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:c,usingTunnel:l});Xe.info("handling hybrid grid",{response:u,companyId:o});let f=Jo({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});function mn(){return Yo||"master"}function Rf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Yo="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){Yo=s.branch||s;return}Yo=e?"master":void 0}var Yo,Dl=w(()=>{"use strict";z()});var fn,Ml,wv,Nl,vv,Xo,Qo,Zo,ei,ti,ri=w(()=>{"use strict";B();ie();fn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},Ml=s=>{let{status:e}=s;return e===pe.ABORTED},wv=s=>{let{status:e}=s;return e===pe.PASSED},Nl=s=>s.runnerStatus===Ya.SKIPPED,vv=s=>s.testStatus===Ke.EVALUATING,Xo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Nl(t)&&(Je(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Qo=s=>Object.values(s).filter(e=>fn(e)&&vv(e)).length,Zo=s=>Object.values(s).filter(fn),ei=s=>Object.values(s).filter(wv),ti=s=>Object.values(s).filter(Ml)});function Sv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Ul,si,Ev,ni,Af=w(()=>{"use strict";Ul=E(require("lodash"));j();ri();si=A("debug-reporter"),Ev=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ni=class{constructor(e){this.options=e}onTestStarted(e,t){si.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;si.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Ul.default.omit(this.options,Ev),company:Ul.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let c=Sv(process.argv);si.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,o){let i=ei(e).length,a=Object.keys(e).length-i;si.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Fl,Ct,gn=w(()=>{"use strict";ie();Fl=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===O.DEVICE_FARM}},Ct=new Fl});var jl={};V(jl,{Reporter:()=>Iv});var er,hn,vr,oi,Cf,Bl,Iv,$l=w(()=>{"use strict";er=E(require("chalk")),hn=E(require("lodash"));B();ie();gn();ri();vr={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:oi}=Mt,Cf="device",Bl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${er.default.underline(He(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?pe.PASSED:pe.FAILED,n=`(${e.testId})`,o=vr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${so(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=He(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
|
|
22
|
+
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=Zo(e),a=ei(e),c=ti(e),l=a.length,d=c.length,m=i.length,u="",f="";if(Ct.isTestStatusEnabled){let I=Qo(e);u=` FAILED-EVALUATING: ${I}`,m-=I,f=` SKIPPED: ${Xo(e,this.options)}`}let g=this.buildTestPlanName(o,t),h,y=vr[m?"error":"success"],v=`PASSED: ${l} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${so(r)}`;g.trim()===""||g.trim()==="Anonymous"?h=`Tests completed. ${v} (Execution ID: ${n})`:h=`Test plan${g} completed ${v} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=hn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=hn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=hn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=hn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let c=u=>{u.forEach((f,g)=>{var v;let h=(v=f.testData)!=null&&v.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",g+1,":",`${f.name}${Je(f,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===oi.APPIUM?Cf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(r)}`)}onGetSession(e,t,r){let n=r===oi.APPIUM?Cf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===oi.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===oi.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Iv=Bl});var Gl={};V(Gl,{Reporter:()=>kv});function Rv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function xv(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 Av(s){return`${s.visitedUrlsJson||""}`}async function Cv(s,e,t,r,n,o){function i(u){let f=He(s,t,u.testId,u.resultId,r),g={$:{name:Rv(u),classname:n,time:sc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(fn(u)||Ml(u)){let h=`Step Failed: ${u.failureReason||u.reason}`,y=fn(u)?`${h} More info at: ${f}`:h;g.failure={$:{message:y}}}return Nl(u)&&Je(u,o)&&Ct.isTestStatusEnabled&&(g.skipped={}),o.urls&&(g["visited-urls-list"]=xv(u),g["visited-urls-json"]=Av(u)),g}function a(u){let{results:f,testPlanName:g,configName:h}=u,y=f||{},I={name:(h&&g?`${g} with config '${h}'`:g)||"selenium run",tests:l(y),failures:d(y),timestamp:c(e)};if(Ct.isTestStatusEnabled){I.skipped=Xo(y,o);let b=Qo(y);I.failures-=b,I["failure-evaluating"]=b}return{$:I,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(u){let f=Object.keys(u).map(h=>u[h].startTime),g=Math.min.apply(null,f);return g?new Date(g).toISOString():new Date().toISOString()}function l(u){return Object.keys(u).length}function d(u){return Zo(u).length+ti(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Vl.Builder().buildObject(m)}catch(u){return Pv(u)}}function Pv(s){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:s.message}}}}}};return e.buildObject(t)}var Vl,Pf,Wl,kv,Hl=w(()=>{"use strict";Vl=E(require("xml2js"));B();Pf=require("fs");gn();ri();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,r=this.options.project,n=await Cv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Pf.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)}};kv=Wl});var kf={};V(kf,{Reporter:()=>Ov});function os(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 ql,zl,Ov,Of=w(()=>{"use strict";j();ql=A("team-city-reporter");zl=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 os(n)}onTestStarted(e,t,r,n){if(r){ql.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){ql.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${os(t)}' details='${os(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){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,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${os(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${os(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${os(t)}']`)}},Ov=zl});var _f={};V(_f,{Reporter:()=>_v});var Kl,_v,Lf=w(()=>{"use strict";Kl=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,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}}))}},_v=Kl});var Df={};V(Df,{Reporter:()=>Lv});var Jl,Lv,Mf=w(()=>{"use strict";B();dl();Jl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=He(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Uo(t)}},Lv=Jl});var Ux,Yl,Q,Pt=w(()=>{"use strict";Af();j();Ux=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 r=e.reporters;if(this.reporters.push(new ni(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>($l(),jl));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([r.includes("teamcity")&&Promise.resolve().then(()=>(Of(),kf)),r.includes("console")&&Promise.resolve().then(()=>($l(),jl)),r.includes("junit")&&Promise.resolve().then(()=>(Hl(),Gl)),r.includes("json")&&Promise.resolve().then(()=>(Lf(),_f)),r.includes("chrome")&&Promise.resolve().then(()=>(Mf(),Df))])).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))}}},Q=new Yl});function Uf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Ff({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:u,projectType:f,appSource:g,gridType:h}){let y=Uf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:Nf(l,d),isStartUp:u,projectType:f,gridType:h,...["android","ios"].includes(f)&&g&&{appSource:g}},m);mt("test-run-ci",y)}function Bf({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:u,logger:f,isStartUp:g,projectType:h,appSource:y,gridType:v}){try{let I=Uf({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Nf(d,m),isStartUp:g,projectType:h,gridType:v,...["android","ios"].includes(h)&&y&&{appSource:y}},u);if(n.success){mt("test-run-ci-success",I);return}mt("test-run-ci-fail",Object.assign({},I,{failureReason:n.failureReason}))}catch(I){f.error("failed to update test end analytics",{err:I})}}function jf(s){mt("batch-run-ci",s)}var Nf,Xl=w(()=>{"use strict";es();Io();Nf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Xr&&e?"ci-with-user":Xr?"ci":e?"cli-with-user":s});var Wf,ii,Vf=w(()=>{"use strict";Wf=require("istanbul-lib-report"),ii=class extends Wf.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 Gf,Hf,qf,yn,ft,zf,ai,Ql,Kf,Dv,Jf,Yf,Mv,Nv,Xf,Uv,Fv,Bv,jv,$v,Qf,Zf=w(()=>{"use strict";Gf=E(require("ora")),Hf=E(require("dayjs")),qf=E(require("test-exclude")),yn=E(require("fs")),ft=E(require("path")),zf=E(require("istanbul-reports")),ai=E(require("istanbul-lib-report"));be();z();B();j();wr();Vf();Ql=A("test-run-status"),Kf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Dv=s=>!!Kf(s).search,Jf=s=>s?Kf(s).pathname.substring(1):"",Yf=(s,e)=>{let t=Jf(e);return!new qf.default({relativePath:!1,include:s}).shouldInstrument(t)},Mv=s=>s.substring(0,s.indexOf("?")),Nv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ee("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Xf=(s,e)=>`${ft.resolve(s,Jf(e))}.js`,Uv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ae(o.sources,async(i,a)=>{if(Yf(r,i))return;let c=Xf(e,i);await yn.promises.mkdir(ft.parse(c).dir,{recursive:!0}),await yn.promises.writeFile(c,o.sourcesContent[a])})})},Fv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Dv(e)&&(e=Mv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=ft.dirname(this.getPath(s));return ft.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Bv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=ai.createContext({dir:t,coverageMap:e,watermarks:ai.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Xf(r,a);return yn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ii({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Fv}),zf.create(a,c).execute(i)}),o},jv=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=>Yf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},$v=async(s,e)=>{let{mergeProcessCovs:r}=await Ee("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await Hc(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await en(c,9e4);await ae(l,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await xc(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}},Qf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Ql.info("start js coverage process");let n=(0,Gf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=ft.resolve(s.codeCoverageReportPath||"./coverage"),i=ft.resolve(o,`.js/${(0,Hf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?ft.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:d}]=await Promise.all([Ee("istanbul-lib-coverage"),$v(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({}),u={};await ae(l.result,async({url:g,functions:h})=>{let{text:y,sourceMapType:v}=d.get(g),I=await Nv({sourceMapType:v,source:y,sourceMapDir:a});u[g]=I;let b=await jv(s,{source:y,sourceMap:I,functions:h});m.merge(b)}),await Uv(s,i,u);let f=await Bv(s,m,o,i);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Ql.error(l,{err:c})}}});var eg={};V(eg,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>Er});var Ae,Wv,Er,is=w(()=>{"use strict";B();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Wv=["ALL",...Object.values(Ae)],Er=class{constructor(){this.marks=Object.fromEntries(Wv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,io(r,50)],[`${t}_P95`,io(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var ng={};V(ng,{initServer:()=>Hv,mapFilesToLocalDrive:()=>eu});function eu(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,ci[t.id]?{screenshot:ci[t.id]}:{})),Object.keys(li).forEach(t=>{s.assets||={},s.assets[sg[t]]=li[t]}),s.assets||={},s.assets.screenshots=Object.values(ci)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Hv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ee("multer"),n=typeof t=="string"?t:Vv;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 u=bn.join(n,m.testResultId);try{await Zl.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(c,l,d){let{fileName:m}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=bn.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,rg.default)();i.post("/",o.single("file"),(c,l)=>{let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(ci[d.stepId]=c.file.path),d.testResultId&&Gv.includes(d.subType)&&(li[d.subType]||=[],li[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(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(u)}}})}var Zl,tg,bn,rg,Vv,ci,li,sg,Gv,tu=w(()=>{"use strict";Zl=E(require("fs")),tg=E(require("os")),bn=E(require("path")),rg=E(require("express"));z();wr();Vv=bn.join(tg.tmpdir(),"testim/rca/"),ci={},li={},sg={"test-log":"consoleLogs","har-file":"networkLogs"},Gv=Object.keys(sg)});var tr,ru,ui,og=w(()=>{"use strict";tr=E(require("lodash"));B();j();ru=A("override-test-data-builder"),ui=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return tr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):ru.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):ru.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}ru.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return tr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(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=re();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 pi(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Sr,Qe,qv,zv,Kv,Jv,di,ig=w(()=>{"use strict";Sr=E(require("lodash"));B();ie();ns();be();z();j();Pt();sn();Zf();is();tu();le();ge();og();gn();Qe=A("test-run-status"),qv=fr(),zv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Kv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Jv=ut();di=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 Er;var a,c,l,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Bs(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:Jn||t.parallel||1,browser:o,gitBranch:qv,gitCommit:zv,gitRepoUrl:Kv,runnerVersion:Jv,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:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:I}=a,b={originalTestResultId:t,previousTestResultId:r,config:Sr.cloneDeep(c),testId:l,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},b,{testCreatorName:u,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:I}),Jc({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,Q.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 Po(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let c=Sr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,br(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Je(e,this.options))return;let n=this.exportsGlobal;try{let o=await pi(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 Qe.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}),Qe.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===Ke.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ke.EVALUATING} status`);return}if(l){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,He(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);Q.onTestIgnored(e,r,`test in ${Ke.QUARANTINE}`)}monitorMemoryUsage(e){let t=nc();if(t.isOverThreshold){let r=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Qe.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&&eu(i,Qe),i.resultUrl=He(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),Q.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 pi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Qe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await br(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=Za;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,g,h;let c=e.browser?Gs(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Vr(M,n)&&$s(a.nativeApp)&&!e.appId,d=Ws(e)&&(Wr(a.nativeApp,n)||l),m=Je(a,e)||d,u={testId:a.testId,status:m?pe.SKIPPED:pe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ke.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:Object.assign({},this.execConfig,{companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((g=a.testData)==null?void 0:g.total)||null,testDataIndex:((h=a.testData)==null?void 0:h.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()})};return[a.resultId,u]});return Object.fromEntries(o)}async executionStart(e,t,r,n,o){Qe.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Zr(()=>Promise.all([pn.end(t),xo("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},d=await pi(i.beforeSuite,l),m=new ui(d,Sr.cloneDeep(this.testInfoList),t);this.testInfoList=m.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=d;let{testInfoList:u}=this,f=[],g=[],h=[];for(let v of u){if(v.isBeforeTestPlan){f.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}g.push(v)}let y=async()=>{let v=Sr.cloneDeep(this.testRunStatus);await ae(Object.keys(v),async R=>{var x;let k=v[R],_=(x=k.config)==null?void 0:x.testData,$=k.testId,S=await Po(t,$,R,_,c.defaults);S&&(delete k.config.testData,k.config.testDataUrl=S)});let I=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:I,intersections:i.intersections},T=Oc(b);return this.executionStartedPromise=T,T.catch(R=>Qe.error(R)),T};try{await y()}catch(v){Qe.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:f,tests:g,afterTests:h}}concatSeleniumPerfMarks(e){Sr.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=ic(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===pe.PASSED&&n++,m===pe.SKIPPED&&o++,m===pe.FAILED&&u===Ke.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await pi(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"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Qf(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await xo("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 Qe.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 kc(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function Xv(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function au(s){return lg.readFileSync(s,{encoding:"base64"})}function mg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&je(s))&&s){let r=au(s);as.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${iu(r)} current extension count: ${e.length}`),e.push(r)}}function fg(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}`;as.info(`adding extension: testim unpacked , path: ${l}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=ou.join(process.cwd(),`testim-headless${o}`),a=au(i);as.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${iu(a)} current extension count: ${e.length}`),e.push(a)}function Qv(s,e,t,r,n,o,i){var g,h;let a=t.seleniumName||t.browserValue,c=[],l=[...dg];e.headless&&l.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":su.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":su.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};nu(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-2",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),nu(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"]=su.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(g=e.projectData)==null?void 0:g.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+Xa.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),mg(r,c,i),e.mode===Y.EXTENSION&&fg(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 u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return te.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${f}:${u}`]=d),s}function eE(s,e,t){let r={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":cg.join(","),"browser.helperApps.neverAsk.openFile":cg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Y.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=ou.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=au(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function tE(s){return`${s.width}x${s.height}`}function rE(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,pg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=tE(r.resolution||t.sl.screenResolution),delete i.screenResolution),nt.merge(i,o,n)}return nt.merge(o,n)}return{}}function sE(s,e,t){return nt.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 nE(s){return s.perfecto?s.perfecto:{}}function oE(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 iE(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=Sa(o,i)),a}function mi(s){var v;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:c,lambdatestService:l}=s;if(o.mode==="local"){let I=[],b=[...dg],T={};return t.headless&&b.push("--headless"),t.silentDebuggerExtensionApi&&b.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&b.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>b.push(`--${R}`)),t.chromeBinaryLocation&&(T.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&fg(t,I,b,null,l),mg(i,I,l),{logLevel:ag,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:b,extensions:I,...T},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=iE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:ag,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(l.getSessionTimeout,t.getSessionTimeout),getSessionRetries:l.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!nt.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};nu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let g=Number(t.browserTimeout/1e3),h=t.browser||(n==null?void 0:n.browserValue);nt.merge(f.desiredCapabilities,rE(t,r,n,e),sE(t,r,n),nE(t),oE(t,h,g),l==null?void 0:l.getCapabilities(t,h,a,c,r));let y=null;switch(!t.ext&&!t.extensionPath&&((v=o.host)!=null&&v.endsWith(".testim.io"))&&!t.canary&&t.mode===Y.EXTENSION&&(y="/opt/testim-headless"),h){case"chrome":case"edge-chromium":f=Zv(f,t,n,i,o,y,l);break;case"firefox":f=eE(f,t,l);break;case"safari":case"safari technology preview":f=Xv(f,h);break;default:break}nt.merge(f.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},b=_=>_[o.provider]||_[f.host]||_[I[f.host]],T=_=>{var $,S;return b(_)||_[($=f.desiredCapabilities)==null?void 0:$.browserName]||_[(S=f.desiredCapabilities)==null?void 0:S.version]||_||{}},R=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),k=T(T(R));Object.keys(k).length&&(as.info(`Adding custom capabilities: ${JSON.stringify(k)}`),Object.assign(f.desiredCapabilities,k))}catch(I){as.error("Failed to load custom capabilities",{error:I,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return f.desiredCapabilities&&!f.capabilities&&(Yv(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,f}var lg,ou,ug,nt,pg,as,ag,su,dg,iu,nu,Yv,Zv,cg,cu=w(()=>{"use strict";lg=E(require("fs")),ou=E(require("path")),ug=E(require("crypto")),nt=E(require("lodash"));B();le();j();ge();ie();Go();pg=require("lodash"),as=A("testim-desired-capabilities-builder"),ag=Kn?"debug":"silent",su={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},dg=["--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"],iu=(...s)=>ug.createHash("sha256").update(s.join("")).digest("hex"),nu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",Yv=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{as.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};Zv=nt.memoize(Qv,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(nt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return iu(i,a,c,r,l,o)}),cg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ne(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function hg(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 lu=w(()=>{"use strict"});function uu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let g=u;g&&g!==u.ownerDocument;g=g.parentNode)if(f(g))return g;return null}function n(u,f){for(let g=u;g&&g!==u.ownerDocument;g=t(g))if(f(g))return g;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let h=window.getComputedStyle(u).getPropertyValue(f);if(h&&h!=="inherit")return h;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let h=o(u,"stroke-width");return!!h&&parseInt(h,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(u){return o(u,"overflow")==="hidden"}function c(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,g=>g.tagName.toUpperCase()==="SELECT");return uu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||c(s))}var yg=w(()=>{"use strict"});var bg,Tg,Vt,aE,cE,fi,wg=w(()=>{"use strict";bg=E(require("promise-queue")),Tg=E(require("webdriverio"));le();Be();B();j();Or();yg();lu();is();Vt=A("WebDriverApi"),aE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},cE={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 Vt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Aa!==void 0&&(e=Aa);let t=1/0;this.queue=new bg.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(),N("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{Vt.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),this.client=await Tg.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ae.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let c of a.slots||[])if(((i=c==null?void 0:c.session)==null?void 0:i.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){Vt.info("grid status is not supported by the grid",{testResultId:e});return}Vt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Vt.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){Vt.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Ne(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Ne(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ae.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,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 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(uu,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ne(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(hg(e,this.isSafari(),Vt))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[cE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Ne(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(aE);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=>Object.hasOwn(va,i)?[va[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(Array.isArray(e))for(let i of e)r=r.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:r})},o=()=>{let i=r.map(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ne(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(_e(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Ne(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Vt.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Vt.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var vg={};V(vg,{doubleClick:()=>lE});var lE,Eg=w(()=>{"use strict";lE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function f(I,b,T){return T>I&&T<b}let g=u.pointerPosition||{},h=r.getBoundingClientRect(),y=g.originX&&f(h.left,h.left+h.width,g.originX)?g.originX:h.left+h.width/2,v=g.originY&&f(h.top,h.top+h.height,g.originY)?g.originY:h.top+h.height/2;return{x:y,y:v}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(u,f,g){if(!window.PointerEvent)return;let h=a(f,g);return new window.PointerEvent(u,h)},l=function(u,f,g){let h=document.createEvent("MouseEvents");return h.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,g,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),g=u.event;return t.includes(g)?c(g,f.x,f.y):l(g,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var Tn={};V(Tn,{dispatchFocus:()=>uE});function uE(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 wn=w(()=>{"use strict"});var Ag={};V(Ag,{WebDriver:()=>Rr});async function fE(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 dE(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var cs,Rg,xg,Ue,rr,pE,Sg,dE,sr,mE,Ig,Ir,Rr,vn=w(()=>{"use strict";cs=E(require("lodash"));B();Be();cu();Rg=E(require("p-retry")),xg=E(require("ua-parser-js"));Or();j();lu();wg();z();ge();is();Ue=A("webdriver"),[rr,pE]=[0,2],{extractElementId:Sg,getCdpAddressForHost:dE}=K,sr=()=>(Te(),he(Qt)).getSessionPlayer().codeSnippets,mE=()=>(Te(),he(Qt)).getSessionPlayer().locatorBuilderUtils,Ig=()=>(Te(),he(Qt)).getSessionPlayer().utils,Ir=()=>(Te(),he(Qt)).getSessionPlayer().positionUtils;Rr=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;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var v,I,b,T,R,k,_,$;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:c,executionId:l,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((b=(I=(v=n==null?void 0:n.company)==null?void 0:v.activePlan)==null?void 0:I.premiumFeatures)==null?void 0:b.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=mi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:c,executionId:l,testResultId:d,lambdatestService:f,overrideConfiguration:r});g.desiredCapabilities&&delete g.desiredCapabilities.marionette,g.capabilities&&delete g.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let h=u?0:1500,y=u?()=>null:()=>this.executeJS("window.focus()");try{N("before initClient in webdriver.js init");let S=await this.initClient(g,o,d);N("after initResult before getCdpAddress in init"),this.cdpUrl=await fE(S),N("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await ne(h),M.flags.dontFocusOnInit.isEnabled()||await y(),N("after focus and delay in webdriver.js init")}catch(S){let x=JSON.stringify(cs.omit(g,"capabilities.extensions","capabilities.capabilities.extensions"));Ue.error("failed to init webdriver",{err:S,capabilitiesAsString:x});let D=((R=(T=n==null?void 0:n.company)==null?void 0:T.activePlan)==null?void 0:R.plan)==="free";throw(k=S.stack)!=null&&k.includes("at startWebDriverSession")&&((_=S.message)!=null&&_.startsWith("Failed to create session"))&&(($=S.message)!=null&&$.includes("Timeout awaiting 'request'"))&&D?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):S.message.match(/Invalid username or password/)?new Mr(S.message):S.message.match(/capabilit(y|ies)/)?new Yn(S.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>cs.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=re();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ue.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ue.warn("failed to click on alert",{err:c}));return}if(Ue.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ue.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Sg(r.value);return await this.switchToFrame({ELEMENT:n,[Ht]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new Xn:r}}async getElement(t){var o;let r=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(r,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(`
|
|
23
23
|
var fn = ${sr().getLocatedElementCode};
|
|
24
24
|
return fn.apply(null, arguments);
|
|
25
25
|
`,t)}finally{this.seleniumPerfStats.markEnd(r,Ae.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Ae.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(`
|
|
@@ -213,17 +213,17 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
|
|
|
213
213
|
injectCode(params, args, incomingParams, context, code);
|
|
214
214
|
});
|
|
215
215
|
})();
|
|
216
|
-
`,u=[],f=new Og.Worker(m,{eval:!0});try{return await ce(new Promise(g=>{f.on("message",h=>{if(h.action==="finish"){let{data:y}=h,v=Object.assign({},y,{tstConsoleLogs:u});
|
|
217
|
-
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:Wg,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=yu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Wg,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=yu.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,Vg.default)(()=>ce(n(),kE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&bi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Gg={};V(Gg,{remoteStepServiceSocketIO:()=>OE});var Tu,OE,Hg=w(()=>{"use strict";bu();Tu=class extends ds{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},OE=new Tu});var qg={};V(qg,{remoteStepService:()=>ms});var wu,Sn,vu,ms,Ti=w(()=>{"use strict";yi();ie();ge();({REMOTE_STEP_SAVED:wu}=Rt),vu=class{async init(e){M.flags.useNewWSCLI.isEnabled()||(Sn=(await Promise.resolve().then(()=>(Hg(),Gg))).remoteStepServiceSocketIO,Sn.init(e))}joinToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?gt.addFilter(`${e}:remoteStep`,{resultId:e},[wu]):Sn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(M.flags.useNewWSCLI.isEnabled()){gt.listenTo(`${e}:remoteStep`,[wu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Sn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?(gt.removeFilter(`${e}:remoteStep`,[wu]),Promise.resolve()):Sn.unlistenToRemoteStep(e)}},ms=new vu});var Eu,Cr,zg=w(()=>{"use strict";bu();Eu=class extends ds{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Cr=new Eu});var Jg={};V(Jg,{testResultService:()=>kt});var Kg,Su,kt,wi=w(()=>{"use strict";Kg=require("events");yi();ie();ge();zg();Su=class extends Kg.EventEmitter{init(e,t){if(M.flags.useNewWSCLI.isEnabled()){gt.onConnect=()=>this.emit("socket-connected");return}t>this.getMaxListeners()&&this.setMaxListeners(t),Cr.init(e),Cr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return M.flags.useNewWSCLI.isEnabled()?gt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED]):Cr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(M.flags.useNewWSCLI.isEnabled()){gt.removeFilter(`${e}:testResult`,[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED]);return}await Cr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(M.flags.useNewWSCLI.isEnabled()){gt.listenTo(`${e}:testResult`,[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Cr.listenToTestResult(e,t,r)}getSocket(){if(!M.flags.useNewWSCLI.isEnabled())return Cr.getSocket()}},kt=new Su});var Xg,Qg,Zg,we,_E,eh,Yg,vi,th=w(()=>{"use strict";Xg=E(require("lodash"));B();le();Be();es();xt();be();jg();Qg=E(require("p-retry")),Zg=require("url");j();Bo();is();ie();Ti();wi();we=A("test-run-handler"),_E=3,eh=20*1e3,Yg=s=>JSON.stringify(s).length<eh,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 Er;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._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?Gs(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return $s(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Wr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?to.FROM_DEVICE:to.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 overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Yt(),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:Bp,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&&dt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Yg(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: ${eh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await cn(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&&Yg(e))return;let r=async()=>{try{return await Kc(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(),qc(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){N("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{N("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};N("before Runtime.evaluate"),await(0,Qg.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}),N("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 N("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 Zg.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 Tr(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 kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Tr(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(Ve.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(Ve.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(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||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,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=Xg.debounce(async()=>{try{let i=await Tr(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)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 Nc(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){ms.listenToRemoteStep(this.testResultId,t=>{Bg(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:_E;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=re(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Ei,rh=w(()=>{"use strict";th();Ei=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new vi(e,t,c,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var LE,DE,In,Iu=w(()=>{"use strict";ns();j();LE=A("worker-utils"),DE=async(s,e,t)=>{e&&await Ll(s,t)},In=async(s,e,t,r)=>{LE.info("releasing player",{hasPlayer:Boolean(r)});try{await(r==null?void 0:r.onDone())}finally{await DE(s,e,t)}}});function jE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Ii,ih,xu,Au,ah,ht,sh,nh,oh,Rn,ME,Ru,NE,or,UE,Si,FE,BE,$E,nt,xn=w(()=>{"use strict";Ii=E(require("ms")),ih=E(require("lodash")),xu=E(require("p-retry")),Au=E(require("dayjs")),ah=E(require("dayjs/plugin/duration"));B();Be();ns();be();j();Iu();Pt();Go();ge();Ti();wi();qe();ie();z();Au.default.extend(ah.default);ht=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:sh,TEST_START_TIMEOUT_MSG:nh,TEST_COMPLETE_TIMEOUT_MSG:oh}=Ve,{SETUP_TIMEOUT:Rn,NETWORK_ERROR:ME,GRID_ERROR:Ru,BROWSER_CLOSED:NE,SELENIUM_ERROR:or,UNKNOWN_ERROR:UE,MOBILE_SESSION_ERROR:Si}=Fs,FE=(0,Ii.default)("1s"),BE=1;$E=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],nt=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=nt.getWorkerId();this.lambdatestService=new te;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return BE++}async getGridSlot(e,t){let r=await Sf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Os(!0)}async getBrowserOnce(e,t,r,n){throw new Os(!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(!Je({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,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Vr(M,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={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,i),i}}setSessionTimeout(){var e;return this.options.mode===Y.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===O.BROWSERSTACK?Math.max((0,Ii.default)("600s"),this.options.getSessionTimeout):Math.max((0,Ii.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{N("before getSlotOnce retries");let i=0,a=await(0,xu.default)(async()=>{let d=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ve.GET_BROWSER_TIMEOUT_MSG)}catch(m){let u={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw m instanceof Nr?ht.info("could not get grid slot due to concurrency issue",u):ht.error("error getting grid slot",{error:m,...u}),i++,await ne(this.options.getBrowserTimeout-(Date.now()-d)),m}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});N("after getSlotOnce retries"),N("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,xu.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{a=await If(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 u=this.setSessionTimeout();N("before getBrowserOnce");let f=await ce(this.getBrowserOnce(e,t,m,a),u,Ve.GET_BROWSER_TIMEOUT_MSG);return N("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},g=this.options.mode===Y.APPIUM?"device":"browser";throw ht.error(`error getting ${g} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f}),Q.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(u instanceof wt)&&this.options.mode!==Y.APPIUM&&await ne(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:c-1,minTimeout:0,factor:1}),N("after getBrowserOnce retries")}catch(i){throw await In(this.id,this.releaseSlotOnTestFinished,r,n),[wt,Mr].some(a=>i instanceof a)?i:i instanceof vt?new pr(i,Ru):new pr(i,or)}return n}async runTest(e,t,r){var d;N("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Ws(this.options)&&this.handleMobileTest(e);if(i)return i;N("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 In(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var u,f;let e=()=>process.nextTick(()=>this.run()),t=async(g,h,y)=>{var D,F,J;if(Je(g,this.options)||Vr(M,(D=this.options.gridData)==null?void 0:D.type)&&h.isAppFromDevice&&!this.options.appId||h.isAppForIosVirtualDevice)return e();let v=h.sessionId,I=H=>y==null?void 0:y.message.includes(H),b=y&&y instanceof pr,T=y&&(I(nh)||I(oh)),_=M.flags.retryOnSeleniumHubError.isEnabled()&&!!g.reason&&h.isSeleniumHubNoMatchSessionError(g.reason)&&!h.ignoreSeleniumHubError,$=T&&h.hasMoreTimeoutRetries(),S=h.hasMoreRetries()&&!b&&!T,x=!g.success&&(S||$||_);try{let H=h.retryKey;g.testRetryKey=H;let X=h.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,v,x,X),this.executionQueue.hasMoreTests()&&!((F=this.options.lightweightMode)!=null&&F.general)&&await ne(FE),await this.runTestCleanup(),x){if($&&await h.startNewTimeoutRetry(),_){ht.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:h.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let de=(J=this.options.projectData)==null?void 0:J.projectId,bt=h.testResultId,it=h.testId;await Co(de,bt,it,{show:!1}),h.decreaseSeleniumHubRetry(),h.decreaseRetryCount(),await h.startNewRetry()}return S&&!_&&!$&&await h.startNewRetry(),ht.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:T,testRetryKey:H,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await d(h,x)}return await e()}catch(H){if(H instanceof qt)return;ht.error("failed to process test result",{error:H}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
216
|
+
`,u=[],f=new Og.Worker(m,{eval:!0});try{return await ce(new Promise(g=>{f.on("message",h=>{if(h.action==="finish"){let{data:y}=h,v=Object.assign({},y,{tstConsoleLogs:u});gt.debug("Run code worker response",{messageWithLogs:v,transactionId:s}),g(v)}else h.action==="progress"&&u.push(h.data)}).on("error",h=>{h.message==="malformed data: URI"?gt.error("Run code worker error",{err:h,transactionId:s,fileDataUrl:i}):gt.error("Run code worker error",{err:h,transactionId:s}),g({tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{gt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(g){if(!(g instanceof se))throw g;return gt.warn("timeout to run code",{transactionId:s,err:g}),{tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function TE(s){try{await Cg.promises.rm(s,{recursive:!0,force:!0})}catch(e){gt.warn("failed to remove install npm packages folder",{err:e})}}function _g(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function ls(s,e,t,r,n,o){let i=_g(n,e,s,t),{data:a}=await wE(i,r,o);return a}async function us(s,e,t,r,n,o,i,a,c,l){var g;let d=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(h=>[h.paramName,h.testimPackageLocalLocation]))||[]),m=_g(i,n,e,o);if(l){let h=await en(l);h&&(c=h)}Buffer.isBuffer(c)&&(gt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let u="data:,";c==="data:"&&(gt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=u);let f=await bE(m,t,r,s,d,a,c);return Object.assign({},f,{nodeVersion:process.version})}async function wE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Lg(),o=En.join(n,`/${s}`),i=global.proxyUri;async function a(){let c="";try{if(c=await Hd(o,r,i,t),gt.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=Gd(o,d.packageName);return{...d,packageFullName:`${d.packageName}@${m}`,packageLocalLocation:En.resolve(o,"node_modules",d.packageName)}}),installFolder:o}}catch(l){throw gt.warn("npm package install failed",{transactionId:s,err:l}),l}}try{return await ce(a(),t)}catch(c){throw c instanceof se&>.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Lg(){return En.join(Pg.tmpdir(),"/testim_local_packages")}function Dg(){let s=Lg();return TE(s)}var Cg,Pg,En,kg,Og,gt,xr=w(()=>{"use strict";Cg=E(require("fs")),Pg=E(require("os")),En=E(require("path"));B();zs();kg=E(require("data-uri-to-buffer")),Og=require("worker_threads");z();j();be();gt=A("cli-service")});var nr={};V(nr,{run:()=>EE});function vE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=M.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var EE,Mg=w(()=>{"use strict";xr();z();ge();EE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await us(r,n,o,i,a,c,l,d,m,u);return f&&vE({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof se?new Error("Timeout while running action"):f}}});var fu={};V(fu,{run:()=>SE});var SE,Ng=w(()=>{"use strict";xr();z();SE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await ls(t,r,n,i,o,a),success:!0}}catch(c){if(c instanceof St)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof se)return{success:!1,code:"timeout"};throw c}}});async function Fg(s,e,t,r){try{return await zc(s,e,t,r)}catch{hi.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function RE(s,e,t,r,n){return hi.info("finished to run remote step",{stepId:t,sessionId:n}),await Fg(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Ug(s,e,t,r,n){return hi.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Fg(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Bg(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=IE[i];if(!l)return await Ug(n,r,c,`Failed to find step type ${i}`,a);try{let d=await l.run(e,t,o);return await RE(n,r,c,d,a)}catch(d){return await Ug(n,r,c,d.message,a)}}var hi,IE,jg=w(()=>{"use strict";Mg();be();Ng();j();hi=A("step-playback"),IE={"cli-validation-code-step":nr,"cli-wait-for-code-step":nr,"cli-action-code-step":nr,"cli-api-code-step":nr,"cli-condition-step":nr,"cli-download-code-step":nr,"node-package":fu}});var gu,$g,Ar,AE,hu,ht,yi=w(()=>{"use strict";B();xt();gu=E(require("ws")),$g=require("events");j();le();Ar=A("socket-ng-service"),AE=5e3,hu=class extends $g.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Ar.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),AE)}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){Ar.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(_p);return Yt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new gu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Ar.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Ar.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===gu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Ar.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){Ar.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Ar.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=re(),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})}},ht=new hu});var Vg,yu,CE,PE,kE,Wg,bi,ds,bu=w(()=>{"use strict";Vg=E(require("p-retry")),yu=E(require("socket.io-client"));le();B();j();CE=50,PE=10,kE=5e3,Wg=10*1e3,bi=A("base socket service"),ds=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===PE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=CE)throw new Error(`Can't connect to Testim Servers.
|
|
217
|
+
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:Wg,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=yu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Wg,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=yu.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,Vg.default)(()=>ce(n(),kE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&bi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Gg={};V(Gg,{remoteStepServiceSocketIO:()=>OE});var Tu,OE,Hg=w(()=>{"use strict";bu();Tu=class extends ds{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},OE=new Tu});var qg={};V(qg,{remoteStepService:()=>ms});var wu,Sn,vu,ms,Ti=w(()=>{"use strict";yi();ie();ge();({REMOTE_STEP_SAVED:wu}=Rt),vu=class{async init(e){M.flags.useNewWSCLI.isEnabled()||(Sn=(await Promise.resolve().then(()=>(Hg(),Gg))).remoteStepServiceSocketIO,Sn.init(e))}joinToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?ht.addFilter(`${e}:remoteStep`,{resultId:e},[wu]):Sn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(M.flags.useNewWSCLI.isEnabled()){ht.listenTo(`${e}:remoteStep`,[wu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Sn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?(ht.removeFilter(`${e}:remoteStep`,[wu]),Promise.resolve()):Sn.unlistenToRemoteStep(e)}},ms=new vu});var Eu,Cr,zg=w(()=>{"use strict";bu();Eu=class extends ds{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Cr=new Eu});var Jg={};V(Jg,{testResultService:()=>kt});var Kg,Su,kt,wi=w(()=>{"use strict";Kg=require("events");yi();ie();ge();zg();Su=class extends Kg.EventEmitter{init(e,t){if(M.flags.useNewWSCLI.isEnabled()){ht.onConnect=()=>this.emit("socket-connected");return}t>this.getMaxListeners()&&this.setMaxListeners(t),Cr.init(e),Cr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return M.flags.useNewWSCLI.isEnabled()?ht.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED]):Cr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(M.flags.useNewWSCLI.isEnabled()){ht.removeFilter(`${e}:testResult`,[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED]);return}await Cr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(M.flags.useNewWSCLI.isEnabled()){ht.listenTo(`${e}:testResult`,[Rt.TEST_RESULT_UPDATED,Rt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Cr.listenToTestResult(e,t,r)}getSocket(){if(!M.flags.useNewWSCLI.isEnabled())return Cr.getSocket()}},kt=new Su});var Xg,Qg,Zg,we,_E,eh,Yg,vi,th=w(()=>{"use strict";Xg=E(require("lodash"));B();le();Be();es();xt();be();jg();Qg=E(require("p-retry")),Zg=require("url");j();Bo();is();ie();Ti();wi();we=A("test-run-handler"),_E=3,eh=20*1e3,Yg=s=>JSON.stringify(s).length<eh,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 Er;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._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?Gs(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return $s(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Wr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?to.FROM_DEVICE:to.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 overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Yt(),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:Bp,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&&mt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Yg(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: ${eh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await cn(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&&Yg(e))return;let r=async()=>{try{return await Kc(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(),qc(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){N("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{N("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};N("before Runtime.evaluate"),await(0,Qg.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}),N("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 N("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 Zg.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 Tr(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 kt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Tr(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(Ve.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(Ve.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(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||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,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=Xg.debounce(async()=>{try{let i=await Tr(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)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 Nc(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){ms.listenToRemoteStep(this.testResultId,t=>{Bg(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:_E;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=re(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Ei,rh=w(()=>{"use strict";th();Ei=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new vi(e,t,c,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var LE,DE,In,Iu=w(()=>{"use strict";ns();j();LE=A("worker-utils"),DE=async(s,e,t)=>{e&&await Ll(s,t)},In=async(s,e,t,r)=>{LE.info("releasing player",{hasPlayer:Boolean(r)});try{await(r==null?void 0:r.onDone())}finally{await DE(s,e,t)}}});function jE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Ii,ih,xu,Au,ah,yt,sh,nh,oh,Rn,ME,Ru,NE,or,UE,Si,FE,BE,$E,ot,xn=w(()=>{"use strict";Ii=E(require("ms")),ih=E(require("lodash")),xu=E(require("p-retry")),Au=E(require("dayjs")),ah=E(require("dayjs/plugin/duration"));B();Be();ns();be();j();Iu();Pt();Go();ge();Ti();wi();qe();ie();z();Au.default.extend(ah.default);yt=A("base-worker"),{GET_BROWSER_TIMEOUT_MSG:sh,TEST_START_TIMEOUT_MSG:nh,TEST_COMPLETE_TIMEOUT_MSG:oh}=Ve,{SETUP_TIMEOUT:Rn,NETWORK_ERROR:ME,GRID_ERROR:Ru,BROWSER_CLOSED:NE,SELENIUM_ERROR:or,UNKNOWN_ERROR:UE,MOBILE_SESSION_ERROR:Si}=Fs,FE=(0,Ii.default)("1s"),BE=1;$E=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],ot=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=ot.getWorkerId();this.lambdatestService=new te;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return BE++}async getGridSlot(e,t){let r=await Sf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Os(!0)}async getBrowserOnce(e,t,r,n){throw new Os(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),yt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Je({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,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Vr(M,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={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,i),i}}setSessionTimeout(){var e;return this.options.mode===Y.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===O.BROWSERSTACK?Math.max((0,Ii.default)("600s"),this.options.getSessionTimeout):Math.max((0,Ii.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{N("before getSlotOnce retries");let i=0,a=await(0,xu.default)(async()=>{let d=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ve.GET_BROWSER_TIMEOUT_MSG)}catch(m){let u={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw m instanceof Nr?yt.info("could not get grid slot due to concurrency issue",u):yt.error("error getting grid slot",{error:m,...u}),i++,await ne(this.options.getBrowserTimeout-(Date.now()-d)),m}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});N("after getSlotOnce retries"),N("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,xu.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{a=await If(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 u=this.setSessionTimeout();N("before getBrowserOnce");let f=await ce(this.getBrowserOnce(e,t,m,a),u,Ve.GET_BROWSER_TIMEOUT_MSG);return N("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},g=this.options.mode===Y.APPIUM?"device":"browser";throw yt.error(`error getting ${g} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f}),Q.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(u instanceof vt)&&this.options.mode!==Y.APPIUM&&await ne(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:c-1,minTimeout:0,factor:1}),N("after getBrowserOnce retries")}catch(i){throw await In(this.id,this.releaseSlotOnTestFinished,r,n),[vt,Mr].some(a=>i instanceof a)?i:i instanceof Et?new pr(i,Ru):new pr(i,or)}return n}async runTest(e,t,r){var d;N("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Ws(this.options)&&this.handleMobileTest(e);if(i)return i;N("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 In(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var u,f;let e=()=>process.nextTick(()=>this.run()),t=async(g,h,y)=>{var D,F,J;if(Je(g,this.options)||Vr(M,(D=this.options.gridData)==null?void 0:D.type)&&h.isAppFromDevice&&!this.options.appId||h.isAppForIosVirtualDevice)return e();let v=h.sessionId,I=H=>y==null?void 0:y.message.includes(H),b=y&&y instanceof pr,T=y&&(I(nh)||I(oh)),_=M.flags.retryOnSeleniumHubError.isEnabled()&&!!g.reason&&h.isSeleniumHubNoMatchSessionError(g.reason)&&!h.ignoreSeleniumHubError,$=T&&h.hasMoreTimeoutRetries(),S=h.hasMoreRetries()&&!b&&!T,x=!g.success&&(S||$||_);try{let H=h.retryKey;g.testRetryKey=H;let X=h.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,v,x,X),this.executionQueue.hasMoreTests()&&!((F=this.options.lightweightMode)!=null&&F.general)&&await ne(FE),await this.runTestCleanup(),x){if($&&await h.startNewTimeoutRetry(),_){yt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:h.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let de=(J=this.options.projectData)==null?void 0:J.projectId,Tt=h.testResultId,at=h.testId;await Co(de,Tt,at,{show:!1}),h.decreaseSeleniumHubRetry(),h.decreaseRetryCount(),await h.startNewRetry()}return S&&!_&&!$&&await h.startNewRetry(),yt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:T,testRetryKey:H,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await d(h,x)}return await e()}catch(H){if(H instanceof qt)return;yt.error("failed to process test result",{error:H}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
218
218
|
Please make sure the CLI has stable access to the internet. ${za()?"(Internal: network connectivity test failed)":""}`,n=g=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:v,TIMEOUT_ERROR:I,SAUCELABS_APP_IS_NOT_INSTALLED:b}=ec,T=g instanceof Error?g.message:g;return T.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),T.includes(sh)||T.includes(I)?{errorType:Rn,reason:"timeout while getting device"}:T.includes(y)||T.includes(b)?{errorType:Si,reason:"app doesn't exist on device"}:T.includes(v)?{errorType:Si,reason:"app never started, check app permission or app activity"}:T.includes(h)?{errorType:Si,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Si,reason:T}},o=(g,h)=>{let y=this.options.mode===Y.APPIUM?"device":"browser";if(!h&&M.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:ME,reason:r()};let v=g instanceof Error?g.message:g;if(v.includes(sh))return{errorType:Rn,reason:`Test couldn't get ${y}`};if(v.includes(nh))return{errorType:Rn,reason:"Test couldn't be started"};if(v.includes(oh)){if(!this.testRunTimeout)return{errorType:Rn,reason:"Test timeout reached: test is too long"};let I=Au.default.duration({milliseconds:this.testRunTimeout}),b=Math.floor(I.asMinutes()),T=I.asSeconds(),R=b>0?` ${b} min`:"",k=T>0?` ${T} sec`:"";return{errorType:Rn,reason:`Test timeout reached (timeout:${R}${k}): test is too long`}}if(g instanceof pr&&g.type){if(g.type===Ru)return{errorType:Ru,reason:`Test couldn't get ${y} from grid - ${g.message}`};if(g.type===or)return{errorType:or,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===NE?{errorType:or,reason:`Session terminated, this is often caused to connection
|
|
219
|
-
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:or,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:or,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:or,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:or,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:UE,reason:v}},i=async(g,h)=>{var T;let y=await qa();!y&&M.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),ht.warn("error on run",{err:g});let v=(T=this.userData)==null?void 0:T.projectId,{errorType:I,reason:b}=this.options.mode===Y.APPIUM?n(g):o(g,y);Co(v,this.testResultId,this.testId,{status:Us.COMPLETED,success:!1,reason:b,errorType:I,testRetryKey:h.retryKey,setupStepResult:{status:Us.COMPLETED,success:!1,reason:b,errorType:I}},h.remoteRunId),await t(jE(this.testId,this.testName,this.testResultId,b),h,g)},a=async(g,h)=>{var T;let y=this.testId,v=this.testResultId,I=(T=this.userData)==null?void 0:T.projectId,b=this.branch;if(!y||!v||!I||!b)return ht.warn("Test failed. Not enough data to recover results via API",{err:g}),i(g,h);try{let R=await Tr(y,v,I,b);if(ht.warn("Test failed. Got results via API",{err:g,testResult:ih.default.omit(R,$E)}),R&&R.status===Us.COMPLETED)return await t(R,h);throw g}catch(R){return R!==g&&ht.error("Failed to fetch test results from server",{testId:y,resultId:v,projectId:I,branch:b,err:R}),i(g,h)}},c=this.options.disableSockets||((u=this.options.lightweightMode)==null?void 0:u.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),d=async(g,h)=>{try{await Promise.all([!l&&ms.joinToRemoteStep(this.testResultId),!c&&kt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Y.APPIUM&&g.validateRunConfig();let y=await this.runTest(g,this.customExtensionLocalLocation,h),v=await t(y,g);return N("After onRunComplete"),v}catch(y){return a(y,g)}finally{l||ms.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 Cu,ch,fs,Pu=w(()=>{"use strict";B();Cu=E(require("p-retry"));B();j();z();ch=A("window-utils"),fs=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 ch.warn("selenium navigation failed. retrying to navigate",{err:o}),await ne(1500),r(n-1);throw!o.seleniumStack&&i&&ch.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),ne(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ne(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 ne(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new wt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Cu.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Cu.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var ku,gs,Ou=w(()=>{"use strict";j();ku=A("cookies-utils"),gs=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 ku.error("failed to set cookie",{err:r}),r}}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,Ri,lh=w(()=>{"use strict";_u=E(require("p-retry")),Ri=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,_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,r=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: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 uh(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 WE.warn("missing elementRect",dh.omit(s,"image")),{};let{elementRect:i}=s,a=await hs.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 u=a.bitmap.width,f=a.bitmap.height;if(c+d>u&&(d=u-c),l+m>f&&(m=f-l),m<=0||d<=0)throw new Lu("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,d,m).getBase64Async(hs.default.MIME_PNG)}}async function VE(s,e){let t=await hs.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await hs.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(hs.default.MIME_PNG)}function GE(s,e){return VE(s,e)}async function HE(){}async function qE(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await HE(s[o]);return{key:o,url:i}}let r=await ae(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function ph(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 dh,hs,WE,Lu,xi,mh=w(()=>{"use strict";dh=E(require("lodash"));B();hs=E(require("jimp"));j();WE=A("image-capture-utils"),Lu=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 uh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:ph(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 qE({screenImage:t.image,absoluteScreenHighlight:ph(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=()=>ne(250),o=Boolean(e);async function i(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let g=await r.takeScreenshot(),h=await uh({elementRect:f},g);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:h.elementImage}}async function a(u){let f=[];for(let g of u){let h=await i(g.scrollPos,g.cropData);f.push(h)}return f}function c(u,f){let g=Math.max(u.width,f.width),h=f.width,y=Math.max(u.height,f.height),v=f.height,I=Array.from({length:Math.ceil(g/h)},(T,R)=>({scrollX:Math.min(R*h,g-h),cropX:R*h-Math.min(R*h,g-h),cropW:h-(R*h-Math.min(R*h,g-h))})),b=Array.from({length:Math.ceil(y/v)},(T,R)=>({scrollY:Math.min(R*v,y-v),cropY:R*v-Math.min(R*v,y-v),cropH:v-(R*v-Math.min(R*v,y-v))}));return I.flatMap(T=>b.map(R=>({scrollPos:{x:T.scrollX,y:R.scrollY},cropData:{top:R.cropY,left:T.cropX,width:T.cropW,height:R.cropH}})))}async function l(u,f){let g=await t.getCurrentScrollPosition(),h=c(u,f),y=await a(h);return await t.scrollToPosition(g),GE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var fh,gh,Ai,Ci,hh=w(()=>{"use strict";fh=E(require("p-retry")),gh=E(require("semver"));B();j();Pu();lh();mh();Te();Ai=A("tab-service"),Ci=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=re();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 fs(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 Ri(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 ne(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,fh.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=gh.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 Du,Pi,Mu=w(()=>{"use strict";Du=class{select(){return console.log(`
|
|
219
|
+
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:or,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:or,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:or,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:or,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:UE,reason:v}},i=async(g,h)=>{var T;let y=await qa();!y&&M.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),yt.warn("error on run",{err:g});let v=(T=this.userData)==null?void 0:T.projectId,{errorType:I,reason:b}=this.options.mode===Y.APPIUM?n(g):o(g,y);Co(v,this.testResultId,this.testId,{status:Us.COMPLETED,success:!1,reason:b,errorType:I,testRetryKey:h.retryKey,setupStepResult:{status:Us.COMPLETED,success:!1,reason:b,errorType:I}},h.remoteRunId),await t(jE(this.testId,this.testName,this.testResultId,b),h,g)},a=async(g,h)=>{var T;let y=this.testId,v=this.testResultId,I=(T=this.userData)==null?void 0:T.projectId,b=this.branch;if(!y||!v||!I||!b)return yt.warn("Test failed. Not enough data to recover results via API",{err:g}),i(g,h);try{let R=await Tr(y,v,I,b);if(yt.warn("Test failed. Got results via API",{err:g,testResult:ih.default.omit(R,$E)}),R&&R.status===Us.COMPLETED)return await t(R,h);throw g}catch(R){return R!==g&&yt.error("Failed to fetch test results from server",{testId:y,resultId:v,projectId:I,branch:b,err:R}),i(g,h)}},c=this.options.disableSockets||((u=this.options.lightweightMode)==null?void 0:u.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),d=async(g,h)=>{try{await Promise.all([!l&&ms.joinToRemoteStep(this.testResultId),!c&&kt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Y.APPIUM&&g.validateRunConfig();let y=await this.runTest(g,this.customExtensionLocalLocation,h),v=await t(y,g);return N("After onRunComplete"),v}catch(y){return a(y,g)}finally{l||ms.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 Cu,ch,fs,Pu=w(()=>{"use strict";B();Cu=E(require("p-retry"));B();j();z();ch=A("window-utils"),fs=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 ch.warn("selenium navigation failed. retrying to navigate",{err:o}),await ne(1500),r(n-1);throw!o.seleniumStack&&i&&ch.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),ne(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ne(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 ne(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new vt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Cu.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Cu.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var ku,gs,Ou=w(()=>{"use strict";j();ku=A("cookies-utils"),gs=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 ku.error("failed to set cookie",{err:r}),r}}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,Ri,lh=w(()=>{"use strict";_u=E(require("p-retry")),Ri=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,_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,r=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: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 uh(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 WE.warn("missing elementRect",dh.omit(s,"image")),{};let{elementRect:i}=s,a=await hs.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 u=a.bitmap.width,f=a.bitmap.height;if(c+d>u&&(d=u-c),l+m>f&&(m=f-l),m<=0||d<=0)throw new Lu("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,d,m).getBase64Async(hs.default.MIME_PNG)}}async function VE(s,e){let t=await hs.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await hs.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(hs.default.MIME_PNG)}function GE(s,e){return VE(s,e)}async function HE(){}async function qE(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await HE(s[o]);return{key:o,url:i}}let r=await ae(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function ph(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 dh,hs,WE,Lu,xi,mh=w(()=>{"use strict";dh=E(require("lodash"));B();hs=E(require("jimp"));j();WE=A("image-capture-utils"),Lu=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 uh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:ph(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 qE({screenImage:t.image,absoluteScreenHighlight:ph(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=()=>ne(250),o=Boolean(e);async function i(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let g=await r.takeScreenshot(),h=await uh({elementRect:f},g);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:h.elementImage}}async function a(u){let f=[];for(let g of u){let h=await i(g.scrollPos,g.cropData);f.push(h)}return f}function c(u,f){let g=Math.max(u.width,f.width),h=f.width,y=Math.max(u.height,f.height),v=f.height,I=Array.from({length:Math.ceil(g/h)},(T,R)=>({scrollX:Math.min(R*h,g-h),cropX:R*h-Math.min(R*h,g-h),cropW:h-(R*h-Math.min(R*h,g-h))})),b=Array.from({length:Math.ceil(y/v)},(T,R)=>({scrollY:Math.min(R*v,y-v),cropY:R*v-Math.min(R*v,y-v),cropH:v-(R*v-Math.min(R*v,y-v))}));return I.flatMap(T=>b.map(R=>({scrollPos:{x:T.scrollX,y:R.scrollY},cropData:{top:R.cropY,left:T.cropX,width:T.cropW,height:R.cropH}})))}async function l(u,f){let g=await t.getCurrentScrollPosition(),h=c(u,f),y=await a(h);return await t.scrollToPosition(g),GE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var fh,gh,Ai,Ci,hh=w(()=>{"use strict";fh=E(require("p-retry")),gh=E(require("semver"));B();j();Pu();lh();mh();Te();Ai=A("tab-service"),Ci=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=re();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 fs(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 Ri(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 ne(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,fh.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=gh.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 Du,Pi,Mu=w(()=>{"use strict";Du=class{select(){return console.log(`
|
|
220
220
|
internal error - cant use port selector in selenium!!!!
|
|
221
221
|
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Pi=new Du});var ys,Nu=w(()=>{"use strict";Ou();Te();ys=class{constructor(e,t){this.driver=e;this._abortedSteps=[];this.cookieUtils=t||new gs(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=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function bh(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=yh(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 u="got empty result in frame result, not rejected from locate element player";throw zE.error(u),new Error(u)}let l=await s.switchToLocatedFrame(a),d=yh(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:u}=i.data[r.targetId],g=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:o.frameOffset.top+g.top,left:o.frameOffset.left+g.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=M.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),I=0;for(let b of v)I++,this.currentFrameHandler=await this.locate(b,I,this.currentFrameHandler,o,i,r);return this.currentFrameHandler}}let u=await i.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let g=0,h=u;for(let y of n)g++,h=await this.locate(y,g,h,o,i,r);return h}}return e}var zE,KE,yh,Th=w(()=>{"use strict";j();ge();Te();Or();zE=A("frame-locator"),KE="ELEMENT",yh=s=>s?s[KE]||s[Ht]:null});var ki,Uu=w(()=>{"use strict";le();ki=()=>{try{if(Op)return!1;if(require("inspector").url())return!0}catch{}return!1}});var W,ue=w(()=>{"use strict";Te();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 YE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:M.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?M.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function XE(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 wh.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(YE(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 g=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),h=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,g,!1,n),y;try{y=await s.execute(`return ${h}`)}catch(R){throw Pr.error("failed to execute getVisibilityCode",{err:R}),R}let{value:v}=y||{},I=v.elementVisibilityInfo||JE,[b,T]=v.elementsFromPointResults||[null,null];return d.checkElementVisibility(I,n,T,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=ee();await s.execute(r(t))}}}var wh,Pr,JE,An,vh=w(()=>{"use strict";ue();j();ge();Te();wh=require("linkedom"),Pr=A("locate-step-action"),JE={opacity:1,clientRects:{}};An=class extends W{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return XE(e)}static getFrameIdByTestimFrameId(){throw Pr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw Pr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw Pr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw Pr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw Pr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw Pr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Eh={};V(Eh,{scroll:()=>QE});var QE,Sh=w(()=>{"use strict";QE=function(s,e,t,r,n,o,i,a){function c(I,b){if(!b)return{success:!1};elementScrollTo(b,I.x,I.y);let T=b.scrollLeft,R=b.scrollTop;return{success:Math.abs(R-I.y)<1&&Math.abs(T-I.x)<1,actualX:T,actualY:R}}function l(I,b){if(!t)return{x:n,y:o};let T=getLocatedElement(b);if(r&&!T)return{x:I.scrollWidth,y:I.scrollHeight};if(!T)throw new Error("could not find target element");let R=T.getBoundingClientRect(),k=0,_=0,$=Math.max(window.innerHeight-(R.height+10),0),S=Math.max(window.innerWidth-(R.width+10),0);return k=a?I.scrollTop+R.top-Math.min(o,$):I.scrollTop,_=i?I.scrollLeft+R.left-Math.min(n,S):I.scrollLeft,{x:Math.round(_),y:Math.round(k)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=l(m,e),g=c(f,m);d&&!document.scrollingElement&&!g.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=l(m,e),g=c(f,m));let h=g.actualX,y=g.actualY,v=getLocatedElement(e);if(t&&r&&!v)return{success:!1,expectedPosition:f};if(t){if(!v)throw new Error("could not find target to scroll to");let I=v.getBoundingClientRect();h=I.left,y=I.top}return{success:g.success,actualX:h,actualY:y}}});var Oi,Ih=w(()=>{"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,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:l}=await Promise.resolve().then(()=>(Sh(),Eh)),d=`
|
|
222
222
|
const getLocatedElement = ${n.getLocatedElementCode};
|
|
223
223
|
const elementScrollTo = ${c.toString()};
|
|
224
224
|
const scroll = ${l.toString()};
|
|
225
225
|
return scroll.apply(null, arguments)
|
|
226
|
-
`;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:u,actualX:f,actualY:g}=m.value;return u?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,f,g)}}}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 Rh,xh=w(()=>{"use strict";Rh=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 Ah,Ch=w(()=>{"use strict";Ah=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(x){e({status:"done",result:x,success:!0})}function a(x){x||={},e({status:"failed",result:x,success:!1,keep:!0})}function c(x){return x!=null&&x.toLowerCase?(x=x.toLowerCase(),x==="text"?"text/plain":x==="url"?"text/uri-list":x):x}function l(){try{return new DataTransfer}catch{return{data:{},setData(D,F){o[c(D)]=F},getData(D){return o[c(D)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(x){let D=x;for(;D&&D!==document.documentElement;){if(D.draggable)return D;D=D.parentElement}return null}function g(x,D,F){let J=D.element,{dispatchDragEventsOnClosestDraggable:H}=F;if(d.includes(x.type)&&H){if(!J&&D.lastDraggedElement)return D.lastDraggedElement;let X=f(J);if(X)return D.lastDraggedElement=X,X}return J}function h(x,D,F){function J(it,lr,P){return P>it&&P<lr}let H=x.pointerPosition||{};if(D)return{x:H.originX||0,y:H.originY||0};let X=F.getBoundingClientRect(),de=H.originX&&J(X.left,X.left+X.width,H.originX)?H.originX:X.left+X.width/2,bt=H.originY&&J(X.top,X.top+X.height,H.originY)?H.originY:X.top+X.height/2;return{x:de,y:bt}}function y(x,D,F){let J=(D==null?void 0:D.modifiers)||{},H=h(x,F.isDrag,F.element),X=(D==null?void 0:D.button)||0,de=x.event;return m.includes(de)?I(de,J,H.x,H.y,X):u.includes(de)?T(de,J,H.x,H.y):b(de,J,H.x,H.y,X)}function v(x,D,F){return{screenX:0,screenY:0,clientX:D,clientY:F,ctrlKey:Boolean(x.ctrl),altKey:Boolean(x.alt),shiftKey:Boolean(x.shift),metaKey:Boolean(x.meta),bubbles:!0,cancelable:!0,composed:!0}}function I(x,D,F,J,H){if(n){let de=v(D,F,J);return de.pointerType="mouse",de.isPrimary=!0,new window.PointerEvent(x,de)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(x,!0,!0,document.defaultView,1,0,0,F,J,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),H,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(x,D,F,J,H){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(x,!0,!0,document.defaultView,1,0,0,F,J,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),H,document.body?document.body.parentNode:document.documentElement),X}function T(x,D,F,J){if(x==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let de=document.createEvent("CustomEvent");return de.initCustomEvent(x,!0,!0,null),Object.assign(de,{dataTransfer:window.TSTA.dataTransfer}),de}let H=v(D,F,J),X=new window.DragEvent(x,H);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function R(x,D,F){let J=g(x,D,F);J==null||J.dispatchEvent(x)}function k(x,D){function F(){return x.event==="click"&&D.isDrag&&!D.allEventsOnSameElement}return F()}function _(x,D,F){if(F){let J=Math.min(F.timeStamp-D.timeStamp,40);setTimeout(()=>{$(x)},J)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function $(x){let D,F=x.events[x.eventIndex],J=x.events[++x.eventIndex];try{x.element=getLocatedElement(F.locatedElement),D=y(F,s,x)}catch(H){return a(`exception in get event in drag step:${H.message}`)}if(k(F,x))return _(x,F,J);if(D)try{R(D,x,F)}catch(H){return a(`exception in executeEvent in drag step:${H.message}`)}else return a(`cannot execute event ${F.event}`);_(x,F,J)}let S={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{$(S)}catch(x){a(x)}},0)}});var Ph={};V(Ph,{doClick:()=>ZE});var ZE,kh=w(()=>{"use strict";ZE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,T){var _;function R($){function S(){return o($).find(F=>[...F.classList||[]].includes("Select-control"))}function x(){let F=S();return F?F.querySelector("input"):null}let D=x();D==null||D.focus()}let k=(_=b.quirks)==null?void 0:_.isReactSelect;T.type==="mousedown"&&k&&R(b.element)}function n(b,T){var k;let R=(k=b.quirks)==null?void 0:k.isCKEditorFrame;T.type==="click"&&R&&document.body.focus()}function o(b){let T=[];for(;b!=null&&b.parentNode;)T.push(b),b=b.parentNode;return T}function i(b){let T={status:"done",result:b,success:!0,...I.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(T)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let T=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");T.initEvent("mouseover",!0,!0),b.dispatchEvent(T)}function l(b){let T={},R=b.getBoundingClientRect(),k=R.left+R.width/2,_=R.top+R.height/2,x=f("mousemove",T,k,_,0);b.dispatchEvent(x)}function d(b,T){function R(x,D,F){return F>x&&F<D}let k=b.pointerPosition||{},_=T.getBoundingClientRect(),$=k.originX&&R(_.left,_.left+_.width,k.originX)?k.originX:_.left+_.width/2,S=k.originY&&R(_.top,_.top+_.height,k.originY)?k.originY:_.top+_.height/2;return{x:$,y:S}}function m(b,T,R){return{screenX:0,screenY:0,clientX:T,clientY:R,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,T,R,k){if(!window.PointerEvent)return;let _=m(T,R,k);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(b,_)}function f(b,T,R,k,_){let $=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return $.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,R,k,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),_,document.body?document.body.parentNode:document.documentElement),$}function g(b,T){let R=["pointerup","pointerdown","pointermove"],k=T.modifiers||{},_=d(b,T.element),$=T.button||0,S=b.event;return R.includes(S)?u(S,k,_.x,_.y):f(S,k,_.x,_.y,$)}function h(){var T;let b=document.activeElement;for(;(T=b.shadowRoot)!=null&&T.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(T=>{try{return g(T,b)}catch{return}}).filter(Boolean).forEach(T=>{b.element.dispatchEvent(T),r(b,T),n(b,T)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let I={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!I.element){a("element not found");return}c(I.element),l(I.element);try{y(I);let b=h(),T=I.quirks,R=T==null?void 0:T.isReactSelect,k=T==null?void 0:T.isCKEditorFrame;!R&&!k&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var Oh={};V(Oh,{doDragPath:()=>eS});var eS,_h=w(()=>{"use strict";eS=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 T=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");T.initEvent("mouseover",!0,!0),b.dispatchEvent(T)}function c(b){let T={},R=b.getBoundingClientRect(),k=R.left+R.width/2,_=R.top+R.height/2,x=u("mousemove",T,k,_,0);b.dispatchEvent(x)}function l(b,T){function R(x,D,F){return F>x&&F<D}let k=b.pointerPosition||{};if(I.isDrag)return{x:k.originX||0,y:k.originY||0};let _=T.getBoundingClientRect(),$=k.originX&&R(_.left,_.left+_.width,k.originX)?k.originX:_.left+_.width/2,S=k.originY&&R(_.top,_.top+_.height,k.originY)?k.originY:_.top+_.height/2;return{x:$,y:S}}function d(b,T,R){return{screenX:0,screenY:0,clientX:T,clientY:R,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,T,R,k,_){if(r){let S=d(T,R,k);return S.pointerType="mouse",S.isPrimary=!0,new window.PointerEvent(b,S)}let $=document.createEvent("PointerEvent");return $.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,R,k,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),$}function u(b,T,R,k,_){let $=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return $.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,R,k,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),_,document.body?document.body.parentNode:document.documentElement),$}function f(b,T){let R=["pointerup","pointerdown","pointermove"],k=T.modifiers||{},_=l(b,T.element),$=T.button||0,S=b.event;return R.includes(S)?m(S,k,_.x,_.y,$):u(S,k,_.x,_.y,$)}function g(b,T){function R(){return b.event==="click"&&T.isDrag&&!T.allEventsOnSameElement}return R()}function h(b,T,R){try{let k=f(T.events[b],T);g(k,T)||T.element.dispatchEvent(k)}catch{}if(b+1===T.events.length)R();else{let k=Math.min(T.events[b+1].timeStamp-T.events[b].timeStamp,n);setTimeout(()=>{h(b+1,T,R)},k)}}function y(b,T){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),T()})}let I={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!I.element){i("element not found");return}a(I.element),c(I.element),y(I,()=>{o()})}});var Cn,_i,Lh=w(()=>{"use strict";Cn=E(require("lodash"));ue();xh();ge();Ch();_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(()=>(kh(),Ph)),Promise.resolve().then(()=>(wn(),Tn))]),l=`
|
|
226
|
+
`;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:u,actualX:f,actualY:g}=m.value;return u?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,f,g)}}}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 Rh,xh=w(()=>{"use strict";Rh=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 Ah,Ch=w(()=>{"use strict";Ah=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(x){e({status:"done",result:x,success:!0})}function a(x){x||={},e({status:"failed",result:x,success:!1,keep:!0})}function c(x){return x!=null&&x.toLowerCase?(x=x.toLowerCase(),x==="text"?"text/plain":x==="url"?"text/uri-list":x):x}function l(){try{return new DataTransfer}catch{return{data:{},setData(D,F){o[c(D)]=F},getData(D){return o[c(D)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(x){let D=x;for(;D&&D!==document.documentElement;){if(D.draggable)return D;D=D.parentElement}return null}function g(x,D,F){let J=D.element,{dispatchDragEventsOnClosestDraggable:H}=F;if(d.includes(x.type)&&H){if(!J&&D.lastDraggedElement)return D.lastDraggedElement;let X=f(J);if(X)return D.lastDraggedElement=X,X}return J}function h(x,D,F){function J(at,lr,P){return P>at&&P<lr}let H=x.pointerPosition||{};if(D)return{x:H.originX||0,y:H.originY||0};let X=F.getBoundingClientRect(),de=H.originX&&J(X.left,X.left+X.width,H.originX)?H.originX:X.left+X.width/2,Tt=H.originY&&J(X.top,X.top+X.height,H.originY)?H.originY:X.top+X.height/2;return{x:de,y:Tt}}function y(x,D,F){let J=(D==null?void 0:D.modifiers)||{},H=h(x,F.isDrag,F.element),X=(D==null?void 0:D.button)||0,de=x.event;return m.includes(de)?I(de,J,H.x,H.y,X):u.includes(de)?T(de,J,H.x,H.y):b(de,J,H.x,H.y,X)}function v(x,D,F){return{screenX:0,screenY:0,clientX:D,clientY:F,ctrlKey:Boolean(x.ctrl),altKey:Boolean(x.alt),shiftKey:Boolean(x.shift),metaKey:Boolean(x.meta),bubbles:!0,cancelable:!0,composed:!0}}function I(x,D,F,J,H){if(n){let de=v(D,F,J);return de.pointerType="mouse",de.isPrimary=!0,new window.PointerEvent(x,de)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(x,!0,!0,document.defaultView,1,0,0,F,J,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),H,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function b(x,D,F,J,H){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(x,!0,!0,document.defaultView,1,0,0,F,J,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),H,document.body?document.body.parentNode:document.documentElement),X}function T(x,D,F,J){if(x==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let de=document.createEvent("CustomEvent");return de.initCustomEvent(x,!0,!0,null),Object.assign(de,{dataTransfer:window.TSTA.dataTransfer}),de}let H=v(D,F,J),X=new window.DragEvent(x,H);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function R(x,D,F){let J=g(x,D,F);J==null||J.dispatchEvent(x)}function k(x,D){function F(){return x.event==="click"&&D.isDrag&&!D.allEventsOnSameElement}return F()}function _(x,D,F){if(F){let J=Math.min(F.timeStamp-D.timeStamp,40);setTimeout(()=>{$(x)},J)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function $(x){let D,F=x.events[x.eventIndex],J=x.events[++x.eventIndex];try{x.element=getLocatedElement(F.locatedElement),D=y(F,s,x)}catch(H){return a(`exception in get event in drag step:${H.message}`)}if(k(F,x))return _(x,F,J);if(D)try{R(D,x,F)}catch(H){return a(`exception in executeEvent in drag step:${H.message}`)}else return a(`cannot execute event ${F.event}`);_(x,F,J)}let S={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{$(S)}catch(x){a(x)}},0)}});var Ph={};V(Ph,{doClick:()=>ZE});var ZE,kh=w(()=>{"use strict";ZE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,T){var _;function R($){function S(){return o($).find(F=>[...F.classList||[]].includes("Select-control"))}function x(){let F=S();return F?F.querySelector("input"):null}let D=x();D==null||D.focus()}let k=(_=b.quirks)==null?void 0:_.isReactSelect;T.type==="mousedown"&&k&&R(b.element)}function n(b,T){var k;let R=(k=b.quirks)==null?void 0:k.isCKEditorFrame;T.type==="click"&&R&&document.body.focus()}function o(b){let T=[];for(;b!=null&&b.parentNode;)T.push(b),b=b.parentNode;return T}function i(b){let T={status:"done",result:b,success:!0,...I.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(T)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let T=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");T.initEvent("mouseover",!0,!0),b.dispatchEvent(T)}function l(b){let T={},R=b.getBoundingClientRect(),k=R.left+R.width/2,_=R.top+R.height/2,x=f("mousemove",T,k,_,0);b.dispatchEvent(x)}function d(b,T){function R(x,D,F){return F>x&&F<D}let k=b.pointerPosition||{},_=T.getBoundingClientRect(),$=k.originX&&R(_.left,_.left+_.width,k.originX)?k.originX:_.left+_.width/2,S=k.originY&&R(_.top,_.top+_.height,k.originY)?k.originY:_.top+_.height/2;return{x:$,y:S}}function m(b,T,R){return{screenX:0,screenY:0,clientX:T,clientY:R,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function u(b,T,R,k){if(!window.PointerEvent)return;let _=m(T,R,k);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(b,_)}function f(b,T,R,k,_){let $=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return $.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,R,k,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),_,document.body?document.body.parentNode:document.documentElement),$}function g(b,T){let R=["pointerup","pointerdown","pointermove"],k=T.modifiers||{},_=d(b,T.element),$=T.button||0,S=b.event;return R.includes(S)?u(S,k,_.x,_.y):f(S,k,_.x,_.y,$)}function h(){var T;let b=document.activeElement;for(;(T=b.shadowRoot)!=null&&T.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(T=>{try{return g(T,b)}catch{return}}).filter(Boolean).forEach(T=>{b.element.dispatchEvent(T),r(b,T),n(b,T)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let I={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!I.element){a("element not found");return}c(I.element),l(I.element);try{y(I);let b=h(),T=I.quirks,R=T==null?void 0:T.isReactSelect,k=T==null?void 0:T.isCKEditorFrame;!R&&!k&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var Oh={};V(Oh,{doDragPath:()=>eS});var eS,_h=w(()=>{"use strict";eS=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 T=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");T.initEvent("mouseover",!0,!0),b.dispatchEvent(T)}function c(b){let T={},R=b.getBoundingClientRect(),k=R.left+R.width/2,_=R.top+R.height/2,x=u("mousemove",T,k,_,0);b.dispatchEvent(x)}function l(b,T){function R(x,D,F){return F>x&&F<D}let k=b.pointerPosition||{};if(I.isDrag)return{x:k.originX||0,y:k.originY||0};let _=T.getBoundingClientRect(),$=k.originX&&R(_.left,_.left+_.width,k.originX)?k.originX:_.left+_.width/2,S=k.originY&&R(_.top,_.top+_.height,k.originY)?k.originY:_.top+_.height/2;return{x:$,y:S}}function d(b,T,R){return{screenX:0,screenY:0,clientX:T,clientY:R,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,T,R,k,_){if(r){let S=d(T,R,k);return S.pointerType="mouse",S.isPrimary=!0,new window.PointerEvent(b,S)}let $=document.createEvent("PointerEvent");return $.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,R,k,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),$}function u(b,T,R,k,_){let $=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return $.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,R,k,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),_,document.body?document.body.parentNode:document.documentElement),$}function f(b,T){let R=["pointerup","pointerdown","pointermove"],k=T.modifiers||{},_=l(b,T.element),$=T.button||0,S=b.event;return R.includes(S)?m(S,k,_.x,_.y,$):u(S,k,_.x,_.y,$)}function g(b,T){function R(){return b.event==="click"&&T.isDrag&&!T.allEventsOnSameElement}return R()}function h(b,T,R){try{let k=f(T.events[b],T);g(k,T)||T.element.dispatchEvent(k)}catch{}if(b+1===T.events.length)R();else{let k=Math.min(T.events[b+1].timeStamp-T.events[b].timeStamp,n);setTimeout(()=>{h(b+1,T,R)},k)}}function y(b,T){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),T()})}let I={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!I.element){i("element not found");return}a(I.element),c(I.element),y(I,()=>{o()})}});var Cn,_i,Lh=w(()=>{"use strict";Cn=E(require("lodash"));ue();xh();ge();Ch();_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(()=>(kh(),Ph)),Promise.resolve().then(()=>(wn(),Tn))]),l=`
|
|
227
227
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
228
228
|
var dispatchFocus = ${c.toString()};
|
|
229
229
|
var doClick = ${a.toString()};
|
|
@@ -246,7 +246,7 @@ Please make sure the CLI has stable access to the internet. ${za()?"(Internal: n
|
|
|
246
246
|
var dnd = ${Rh.toString()};
|
|
247
247
|
var eventData = arguments[0];
|
|
248
248
|
return dnd.call(null, eventData);
|
|
249
|
-
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let 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 Pn,Dh=w(()=>{"use strict";ue();Pn=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 Mh,tS,Li,Nh=w(()=>{"use strict";Mh=E(require("lodash"));ue();j();tS=A("evaluate-expression-step-action"),Li=class extends W{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{tS.info("runner running incoming params evaluation");let o=t.incomingParams||{};Mh.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 Uh={};V(Uh,{setText:()=>rS});var rS,Fh=w(()=>{"use strict";rS=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(){
|
|
249
|
+
`,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let 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 Pn,Dh=w(()=>{"use strict";ue();Pn=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 Mh,tS,Li,Nh=w(()=>{"use strict";Mh=E(require("lodash"));ue();j();tS=A("evaluate-expression-step-action"),Li=class extends W{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{tS.info("runner running incoming params evaluation");let o=t.incomingParams||{};Mh.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 Uh={};V(Uh,{setText:()=>rS});var rS,Fh=w(()=>{"use strict";rS=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(){Tt()},window.addEventListener("unload",window.__unloadNavigator);let o=new Set(["keydown","keyup","keypress"]),i=15;function a(P){try{if(!t)return;let L=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return P.eventData&&(L.data=P.eventData.data),L}catch{}}function c(P){try{let L=document.createEvent("TextEvent");L.data=P.eventData.data;let U=1,q=P.eventData.locale||"en-US";return L.initTextEvent("textInput",!0,!0,window,P.eventData.data,U,q),L}catch{}}function l(P){return a(P)||c(P)}function d(P,L,U){try{return new KeyboardEvent(P,{bubbles:!0,cancelable:!0,location:L.location||0,key:L.key||"",ctrlKey:Boolean(U.ctrl),shiftKey:Boolean(U.shift),altKey:Boolean(U.alt),metaKey:Boolean(U.meta)})}catch{}}function m(P,L,U){try{let q=document.createEvent("KeyboardEvent");return q.initKeyEvent(P,!0,!0,null,Boolean(U.ctrl),Boolean(U.alt),Boolean(U.shift),Boolean(U.meta),L.key||"",0),q}catch{}}function u(P,L,U){try{let q=document.createEvent("Events");return q.initEvent(P,!0,!0),Object.assign(q,{altKey:Boolean(U.alt),ctrlKey:Boolean(U.ctrl),metaKey:Boolean(U.meta),shiftKey:Boolean(U.shift),keyCode:L.key||""}),q}catch{}}function f(P,L,U){return d(P,L,U)||m(P,L,U)||u(P,L,U)}function g(P){if(!o.has(P.event))return null;let L=P.eventData,U=L.modifiers||{},q=f(P.event,L,U);return Object.defineProperties(q,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(q,{_keyCode_:L.keyCode,_charCode_:L.charCode||0}),q}function h(P){return P.event==="textInput"?l(P):g(P)}function y(P,L){return(()=>{var q;return P.event==="textInput"&&!((q=L.quirks)!=null&&q.isAuth0Form)})()}function v(P,L){return P.event==="keyup"&&L.event==="keydown"?i:0}function I(P,L){let U=v(P,L);return Math.min(L.timeStamp-P.timeStamp,U)}function b(P){let L=Object.getOwnPropertyDescriptor(P,"value");if(!L)return;let U=P.value;P.value=`${U}#`,L.configurable&&delete P.value,P.value=U;let q=document.createEvent("HTMLEvents");q.initEvent("input",!0,!1),P.dispatchEvent(q),Object.defineProperty(P,"value",L)}function T(P){if(J(P.element))try{if(b(P.element),t)P.element.dispatchEvent(new Event("change"));else{let L=document.createEvent("HTMLEvents");L.initEvent("change",!1,!0),P.element.dispatchEvent(L)}}catch{}}function R(P,L,U){U?setTimeout(()=>{F(P)},I(L,U)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),T(P),Tt())}function k(P,L){return(P==="change"||P==="blur")&&L.element.tagName==="OPTION"}function _(P,L,U){return k(P.type,L)?L.element.parentElement:U.locatedElement?getLocatedElement(U.locatedElement):L.element}function $(P,L){let U=P.firstChild,q;for(;U;){if(U.nodeType===3){if(L.offset--<=0)return U}else if(U.nodeType===1&&(q=$(U,L),q))return q;U=U.nextSibling}return null}function S(P,L){if(!(!P||!L)){if(!isNaN(L.start))Object.assign(P,{selectionStart:L.start,selectionEnd:L.end});else if(!isNaN(L.nodeOffset)){let U;if(P.firstChild?U=$(P,{offset:L.nodeOffset}):U=P,U){let q=window.getSelection(),ct=document.createRange();try{q.removeAllRanges(),ct.setStart(U,L.textOffset),ct.setEnd(U,L.textOffset),q.addRange(ct)}catch{}}}}}function x(P,L){return P==="submit"&&Boolean(L.action)}function D(P,L,U){if(L.isFocusable&&L.isSelectable(P)&&P.type!=="submit")try{S(L.element,U.eventData.selection)}catch{}let q=_(P,L,U);if(!q)throw new Error("could not find element");x(P.type,q)?q.submit():q.dispatchEvent(P)}function F(P){let L,U=P.events[P.eventIndex],q=P.events[++P.eventIndex];try{L=h(U)}catch(ct){return at(`exception in get event in text step:${ct.message}`)}if(y(U,P))return R(P,U,q);if(L)try{D(L,P,U)}catch(ct){return at(`exception in executeEvent in text step:${ct.message}`)}else if(P.noEventExecuter)P.noEventExecuter(P,U);else return at(`cannot execute event ${U.event}`);R(P,U,q)}function J(P){let L=P.tagName;return L==="INPUT"||L==="TEXTAREA"}function H(P){return P.getAttribute?Boolean(P.getAttribute("contenteditable")==="true"):!1}function X(P,L){if(J(P.element)){P.element.value=L.eventData.text;let U=document.createEvent("Event");U.initEvent("input",!0,!1),P.element.dispatchEvent(U)}else P.isContentEditable&&(P.element.innerHTML=L.eventData.text)}function de(){var L;let P=document.activeElement;for(;(L=P.shadowRoot)!=null&&L.activeElement;)P=P.shadowRoot.activeElement;return P}function Tt(P){let L={status:"done",result:P,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}function at(P){P||="";let L={status:"failed",result:P,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(L)}try{let P=J(n.element);n.isContentEditable=H(n.element),!P&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=P||n.isContentEditable,n.isSelectable=L=>L.type!=="keyup",n.noEventExecuter=X}catch(P){at(`exception in set text step:${P.message}`);return}let lr=de();dispatchFocus(s.elementToFocusLocatedElement,lr),F(n)}});var Di,Bh=w(()=>{"use strict";ue();B();Di=class extends W{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(_e(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var g;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(()=>(Fh(),Uh)),Promise.resolve().then(()=>(wn(),Tn))]),u=`
|
|
250
250
|
var getLocatedElement = ${o.codeSnippets.getLocatedElementCode};
|
|
251
251
|
var dispatchFocus = ${m};
|
|
252
252
|
var setText = ${d.toString()};
|
|
@@ -405,12 +405,12 @@ Please make sure the CLI has stable access to the internet. ${za()?"(Internal: n
|
|
|
405
405
|
`;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 Vi.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",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(o)||f.startsWith(i)||f.startsWith(a)||f.includes(u)||f.includes(c)||f.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw Vi.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(_e(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=M.flags.overrideAzureStorageUrl.isEnabled(),n=M.flags.useJsInputCodeInSafari.isEnabled(),o=M.flags.useJsInputCodeInFirefox.isEnabled(),i=M.flags.useJsInputCodeInEdgeChromium.isEnabled(),a=M.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:c,context:l,step:d,stepActionUtils:m,driver:u}=this,f=await c.utils.addTokenToFileUrl(l.project.id,d.fileUrls,m.testimServicesApi,r,Vi),g=u.isSafari()&&(n||f.length>1),h=u.isFirefox()&&(o||f.length>1),y=u.isEdgeChromium()&&(i||f.length>1);if(a&&(f=await Promise.all(f.map(async({name:I,url:b})=>{let T=await Dt(b);return{name:I,url:`data:${T.type};base64,${Buffer.from(T.body).toString("base64")}`}}))),g||h||y){await this.driver.executeJS(`
|
|
406
406
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
407
407
|
const downloadAndUploadFile = ${gS()};
|
|
408
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,f);return}let v=await oy(f,this.uploadFile);await this.uploadFilesAndForceVisibility(v,t)}}});var Hi,qi,cy=w(()=>{"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,ly=w(()=>{"use strict";ue();B();zi=class extends W{async performAction(){await ne(this.step.durationMS||0)}}});var Ki,uy=w(()=>{"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 kn,py=w(()=>{"use strict";ue();kn=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,dy=w(()=>{"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 my,Bu,ju,fy=w(()=>{"use strict";my=E(require("@applitools/spec-driver-webdriverio"));Hn();Te();Bu=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Ap["@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:my.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}},ju=new Bu});var hy,gy,On,yy=w(()=>{"use strict";hy=E(require("lodash"));ue();j();fy();gy=A("pixel-validation-step-action"),On=class extends W{async performAction(){var m,u;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=((u=r.batch)==null?void 0:u.id)||o,c=await ju.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},d;try{let f=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"};hy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),gy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:h}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){gy.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await ju.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ts,$u=w(()=>{"use strict";xr();z();Ni();Ts=class extends ir{async executeCliCode(){var g,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(g=t.company)==null?void 0:g.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},u=t.data.timeToPlayStep,f=await us(o,i,a,m,c,l,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof se?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,by=w(()=>{"use strict";$u();ar=class extends Ts{isFailedResult(e){return e===!1}}});var Yi,Ty=w(()=>{"use strict";$u();Yi=class extends Ts{isFailedResult(e){return!e}}});var Xi,wy=w(()=>{"use strict";xr();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 ls(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof Et?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof se?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var kr,vy=w(()=>{"use strict";ue();kr=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ve,Ey=w(()=>{"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,Sy=w(()=>{"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,Iy=w(()=>{"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 hS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ea(s,e){hS(yS,e),e.registerLocateStepActionUtils(An.getUtils(s))}var yS,Wu=w(()=>{"use strict";vh();Ih();Lh();Dh();Nh();Bh();Wh();Vh();Gh();zh();Kh();Jh();Qh();ty();ay();cy();ly();uy();py();dy();yy();by();Ty();wy();vy();Ey();Sy();Iy();yS={locate:An,scroll:Oi,mouse:_i,submit:Bi,text:Di,"special-key":Ui,"user-code":Gt,"validation-code-step":Gt,"wait-for-code-step":Gt,"action-code-step":Gt,"condition-step":bs,"skip-code-step":bs,"element-code-step":bs,"evaluate-expression":Li,"text-validation":Pn,"wait-for-text-validation":Pn,"select-option":Fi,"drop-file":Wi,"input-file":Gi,hover:ji,navigation:qi,wheel:$i,sleep:zi,refresh:Ki,"api-validation":kn,"api-action":kn,"api-code-step":Gt,"extract-text":Ji,"simple-ui-verification":On,"wait-for-simple-ui-verification":On,"cli-validation-download-file":kr,"cli-wait-for-download-file":kr,"network-validation-step":kr,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Yi,"node-package":Xi,"email-code-step":Gt,"cli-email-code-step":ar,"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,"sfdc-document-validation":kr}});var Ry,bS,ws,Vu=w(()=>{"use strict";Ry=["simple-ui-verification","wait-for-simple-ui-verification"],bS=[...Ry,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation"],ws=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=bS.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 Ry.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 Ay={};V(Ay,{SeleniumTestPlayer:()=>_n});var xy,_n,Gu=w(()=>{"use strict";B();xy=require("@applitools/eyes-sdk-core");vn();z();Ou();hh();Mu();Nu();Th();Uu();Te();Wu();Vu();_n=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new ws(ki());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Rr;let d=new ys(this.driver);this.stepActionFactory=new l(d),ea(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ci(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=bh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new gs(this.driver),FrameLocator:m,portSelector:Pi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:xy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof se&&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 Cy={};V(Cy,{WorkerSelenium:()=>Hu});function wS(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var ta,TS,Hu,Py=w(()=>{"use strict";B();Be();xn();j();Pt();Bo();ie();Pu();z();Gu();Te();ta=A("worker-selenium"),TS=1e9,Hu=class extends nt{initPlayer(t){return new _n(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new fs(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),N("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,TS),await this.windowUtils.validatePageIsAvailable(),N("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 wt||d||m?new wt(`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";Q.onWaitToTestComplete(this.id),wS(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 cn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(f)}),this.testRunTimeout,Ve.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof se&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(ta.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(ta.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),N("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),N("right after super.runTestOnce in workerSelenium");let u=await d();return N("right after runSeleniumTest"),u}catch(u){throw ta.error("failed to run test once",{err:u}),u}}}});var ky,Ge,qu,yt,ra=w(()=>{"use strict";j();ie();le();be();qe();ky=E(require("ora")),Ge=A("mobile-grid-service"),qu=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===O.TESTIM_HEADSPIN?`${Hp}/devices`:e===O.TESTIM_TDC?`${zp}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:o})}catch(i){throw Ge.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Re(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw Ge.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t){let r=await Ns(`${Ca}/access`,void 0,{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`});return JSON.parse(r).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let l=await tl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=l==null?void 0:l[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return(c=e.mobile)==null?void 0:c.version.split("-")[0];if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let l=e.pCloudy_DeviceFullName.split("_");return`${l[0]} ${l[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r){var v;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:c}={},company:{companyId:l=""}={},gridData:{gridId:d="",type:m=""}={}}=r,u=t.capabilities,f=await this.getDeviceNameFromSessionCaps({capabilities:u,gridType:m,projectId:a,projectType:c,companyId:l,gridId:d}),g=u.platformVersion;!g&&m===O.BROWSERSTACK&&(g=(v=u.mobile)==null?void 0:v.version.split("-")[1]),!g&&m===O.TESTIM_TVC&&(g=u.os_version);let h={name:f??"",model:u.deviceModel,osVersion:g,udid:u.udid,osType:u.platformName,scaleFactor:u.pixelRatio,isVirtual:m===O.TESTIM_TVC},y=m===O.TESTIM_TVC&&u.replayUrl;return await br(a,n,o,i,"RUNNING",{device:h,...y&&{remoteResultLink:y}}),Ge.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h,remoteResultLink:y,gridType:m}),h}async getTmaDeviceDetails(e){let t=await Re(`${Zp}/devices`),r=t==null?void 0:t.find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:c}=t;return await br(c,n,o,i,"RUNNING",{device:a}),Ge.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await Dc({appId:e,projectId:t});if(!i)throw Ge.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw Ge.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Gp*60))+1)*60*1e3,Math.max(Vp,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[O.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid",appPath:"testimTvcAppId"},[O.P_CLOUDY]:{name:"pCloudy",appPath:"pCloudyAppId"}},a=i[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,ky.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await rl({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});l.succeed(`app uploaded successfully to ${a}`);let m=i[o].appPath;return d[m]}catch(d){throw l.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:c="",project:l,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f="",host:g=""}=m;if(!c&&e.isAppFromDevice)return n;if(c){Ge.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:i});let I=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:d,executionId:i,testResultId:a});n=I.appUrl,o=I.mobileApp,e.nativeApp=o}else Ge.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,y=this.gridsAppIdGetter[f]({testRunHandler:e,mobileApp:o,gridHost:g}),v=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(y){let I=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:y,gridData:m,projectType:I});b&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:y,projectId:l,testResultId:a,executionId:i,mobileAppId:h}),n=y),!b&&v&&(Ge.info("app not exists on grid, uploading it",{gridAppId:y,projectId:l,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!b&&!v&&Ge.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:i})}return!y&&v&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var l,d;let{accessToken:n,user:o,host:i,key:a,type:c}=t;if(c===O.BROWSERSTACK){let m=`${Yp}/recent_apps`;return(await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a})).some(f=>f.app_url===e)}if(c===O.SAUCELABS){let u=`${i.includes("eu-central-1")?Qp:Xp}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(g=>g.id===e)}if(c===O.TESTIM_HEADSPIN||c===O.TESTIM_TDC){let m=c===O.TESTIM_HEADSPIN?`${qp}/apps`:`${Kp}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(c===O.TESTIM_TVC){let m=`${Jp}/versions/${e}/info`,u=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:m,accessToken:u,authType:"Upload-Token"}),!0}catch(f){return f.status!==404&&Ge.error("error while verifying app exists on TVC",{error:f}),!1}}if(c===O.P_CLOUDY){let m=await this.getPCloudyAuthToken(o,a),u=`${Ca}/drive`,f=await Va({url:u,body:{token:m,filter:"all"},headers:{contentType:null}});return(d=(l=JSON.parse(f).result)==null?void 0:l.files)==null?void 0:d.some(h=>h.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Re(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Re(e,void 0,n)}},yt=new qu});function zu({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!vS.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function ES({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function SS(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 IS(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,c=i?"tdc":"headspin",l=a&&M.flags.enableBatchHeadSpin.isEnabled(),d=i&&(M.flags.enableBatchTDC.isEnabled()||M.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${c}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...o&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:SS(t),[`${c}:enableBatch`]:l||d,...!r&&{"appium:noReset":n}}}function sa(s){return"id"in s?s.id:s.packageName}function RS(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function xS({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a,resetOnSessionStartOnly:c}=t,l={"appium:app":n},d=n==null?void 0:n.startsWith("http");switch(n&&!d&&(l=RS(n,t.gridData.type)),s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":!!i,...!!i&&{"appium:resetOnSessionStartOnly":c},...r&&{"appium:bundleId":sa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":o},...r&&{"appium:appPackage":sa(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Ku({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}){switch(s){case"ios":return{...e,autoAcceptAlerts:!0,platformName:"iOS",automationName:"XCUITest",...t&&{bundleId:sa(t)},...r&&{app:r}};case"android":return{...e,autoGrantPermissions:!0,platformName:"Android",automationName:"UiAutomator2",...n&&{appWaitActivity:n},...t&&{appPackage:sa(t),appActivity:t.activity??".*"},...r&&{app:r}};default:throw Error(`unsupported mobile project ${s}`)}}function _y({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=IS(i.type,o,n);return xS({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Ju({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 Yu({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e;if(s)return s;if(n!=null&&n.deviceName)return r===O.P_CLOUDY?n.deviceUdid:n.deviceName;if(o!=null&&o.deviceNameRegex)return o.deviceNameRegex;if(t==="ios"){if(r===O.BROWSERSTACK)return"iPhone.*";if(r===O.P_CLOUDY)return"apple"}return".*"}function AS(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function CS({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,u=AS(o,s),f=Ju({osVersion:c,mobileConfig:d}),g=Yu({deviceName:l,mobileConfig:d,projectType:s,gridType:m}),h=He(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:g,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":h,"waldo:options":{token:u}};return Ku({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function PS({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)||{},{user:m,key:u,type:f}=o,g=Ju({osVersion:c,mobileConfig:d}),h=Yu({deviceName:l,mobileConfig:d,projectType:s,gridType:f}),y=/^[a-zA-Z]+$/.test(h),v={...g!==".*"&&{pCloudy_DeviceVersion:g},...y&&{pCloudy_DeviceManufacturer:h},...!y&&{pCloudy_DeviceFullName:h}},I={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...v,pCloudy_DurationInMinutes:10,pCloudy_ApplicationName:t,newCommandTimeout:120,fullReset:!0};return t="",Ku({projectType:s,sessionCaps:I,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function kS({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,u=m===O.BROWSERSTACK?"browserstack":"saucelabs",f=Ju({osVersion:c,mobileConfig:d}),g=Yu({deviceName:l,mobileConfig:d,projectType:s,gridType:m}),h={...m===O.BROWSERSTACK&&{os_version:f,device:g,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...m===O.SAUCELABS&&{platformVersion:f,deviceName:g,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${u}.user`]:o.user,[`${u}.key`]:o.key,[`${u}.debug`]:!0,[`${u}.networkLogs`]:!0};return Ku({projectType:s,sessionCaps:h,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Ly(s){return O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type?_y(s):O.TESTIM_TVC===s.gridInfo.type?CS(s):O.P_CLOUDY===s.gridInfo.type?PS(s):kS(s)}function OS(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 Dy(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}`);zu({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=yt.getGridConnection(e),c=Ly(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=OS(r,o==null?void 0:o.mobile);if(!(0,Oy.isEmpty)(m)){let u=Object.entries(m).map(([f,g])=>g.split(",").map(h=>h===".*"||h==="="?"":`${f}:${h}`).join(",")).join(" ").trim();c[`${d}:selector`]=u}}let l=e.type===O.TESTIM_TVC?{alwaysMatch:c}:c;return{...a,desiredCapabilities:c,capabilities:l,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function My(s){var g,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;zu({nativeAppMetadata:r,appPath:o,gridInfo:t}),ES({deviceUdid:l,gridInfo:t,testRunConfig:c});let d=l||((h=(g=c.mobile)==null?void 0:g.staticAllocation)==null?void 0:h.deviceUdid),m=await yt.getGridDirectConnection(t,d),f=_y({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Ny(s){return zu(s),Ly(s)}function Uy(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 Oy,vS,Xu=w(()=>{"use strict";ge();ie();ra();Oy=require("lodash");B();vS=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var na,By=w(()=>{"use strict";na=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,oa,jy=w(()=>{"use strict";j();Qu=A("mobile-frame-locator-mock"),oa=class{foundFrameCallback(){return Qu.info("foundFrameCallback-mock invoked"),{}}locate(){return Qu.info("locate-mock invoked"),{}}async findFrame(){return Qu.info("findFrame-mock invoked"),{}}}});var _S,Wy,$y,vs,Zu=w(()=>{"use strict";_S=E(require("webdriverio")),Wy=require("@applitools/eyes-sdk-core");By();Mu();j();Nu();Uu();Te();Wu();jy();Vu();$y=A("appium-test-player"),vs=class{constructor(e,t,r,n=_S,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new ys(this.driver);this.stepActionFactory=new l(m),ea(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new ws(ki()),this.sessionPlayer=new a(e,{tabService:new na,cookieUtils:void 0,FrameLocator:oa,portSelector:Pi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Wy.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()),$y.info("appium session deleted",o)}catch(i){$y.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 LS(s){return await Re(`${s}/api/status`)}async function Vy(s,e){return await Re(`${s}/api/devices/${e}/status`)}async function Gy(s){if((await LS(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Hy=w(()=>{"use strict";qe()});var qy={};V(qy,{WorkerLocalTma:()=>sp});var ia,ep,tp,rp,sp,zy=w(()=>{"use strict";qe();Xu();xn();B();j();Pt();Zu();Te();Hy();ra();ia=A("worker-appium"),ep=class extends Error{},tp=class extends Error{},rp=class extends Error{},sp=class extends nt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new vs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=ee(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var R;if(Q.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 Gy(i);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=c.type,f=this.options.appId;if(f){let{executionId:k,testResultId:_}=t,{mobileApp:$}=await yt.getMobileAppDataByAppId({appId:f,projectId:l,token:d,executionId:k,testResultId:_});t.nativeApp=$}let g=u==="android"?t.androidActivityWait:null,h=t.nativeAppMetadata,y=t.downloadableAppPublicLink,v=t.appPackageNameOrBundleId;if(!h)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!v)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:I,version:b},T]=await Promise.all([this.getAppStateFromDevice(i,a,v),Vy(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!I&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!I&&y&&await this.installApp(i,a,y);try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(R=this.options.projectData)==null?void 0:R.name}-${this.options.project}`},_=Ny({projectType:u,nativeAppMetadata:h,appPath:y,androidActivityWait:g,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},S=await this.requestNewAppiumSessionFromTma(i,$,h);this.sessionData=S;let x=await m.attach({sessionId:S.sessionId,capabilities:_});this.device=await yt.updateTmaDeviceDetails(a,this.options,t),ia.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:h,sessionCaps:x.capabilities})}catch(k){throw ia.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local"}}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new rp(c):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,c=(await Re(i)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Dt(n);await Ms(`${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 tp(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 ep(`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";Q.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((m,u)=>{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(u)});return await o.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw ia.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw ia.error("failed to run test once",{err:l}),l}}}});var Jy={};V(Jy,{WorkerAppium:()=>np});var Ky,Ln,np,Yy=w(()=>{"use strict";Xu();Ky=require("linkedom");xn();j();Pt();Zu();Te();ra();ie();Ln=A("worker-appium"),np=class extends nt{initPlayer(t){return new vs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,c=await yt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),l=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch},u={projectType:a,nativeAppMetadata:d,appPath:c,androidActivityWait:l,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await yt.lockDevice(o,this.options.deviceUdid),f=await My(u)):f=Dy(u),Ln.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Uy(f)}),this.activeSession=await i.remote(f),this.device=await yt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options),Ln.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Ln.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.TESTIM_TVC?`https://${t}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=r,c=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:v,path:I}=await yt.getHeadSpinDeviceConnection(this.options.gridData,g);l=`${h}://${y}:${v}${I}`}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:(f=this.options.company)==null?void 0:f.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 g=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(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...t.seleniumPerfStats.getStats()}}catch(g){throw Ln.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}};try{return await super.runTestOnce(t,r),await m()}catch(g){throw Ln.error("failed to run test once",{err:g}),g}}}});var aa,Xy=w(()=>{"use strict";B();vn();z();aa=class{constructor(e){this.id=e;this.driver=new Rr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof se&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Qy,ca,Zy=w(()=>{"use strict";Qy=E(require("ws"));B();ca=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 Qy.default(this._cdpUrl,{timeout:e}),r=zt(o=>{t.once("open",o)}),n=zt(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 ua,op,la,eb=w(()=>{"use strict";B();ua=E(require("chrome-launcher"));cu();Zy();sn();op=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ca}async init(e){var u,f,g,h;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:c}=e,l=mi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:c}),d=[...((u=l.desiredCapabilities)==null?void 0:u.chromeOptions.args)??[],...((h=(g=(f=l.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:h.args)??[],...ua.Launcher.defaultFlags().filter(y=>y!=="--disable-extensions")];this.chrome=await ua.launch({chromeFlags:d,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 m=await gr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(m),Zr(()=>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}},la=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new op(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var rb={};V(rb,{WorkerExtension:()=>Dn});function DS(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function tb(s){return DS(s)?s:new Error(s)}var ot,Dn,ip=w(()=>{"use strict";Be();z();xn();B();j();Pt();ie();Xy();eb();ot=A("worker-ext"),Dn=class extends nt{initPlayer(){return this.options.useChromeLauncher?new la(this.id):new aa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService})}catch(a){throw ot.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var 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;N("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Ve.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof se))throw u;return ot.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ot.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var f;if(N("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(g){throw ot.warn("failed to run test via CDP",{err:g}),g}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let g=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,g,u),c(u)]),this.options.testStartTimeout,Ve.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof se))throw v;ot.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let h=new AbortController,y=v=>{e.onCompletedCleanup(),ot.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),v.type=Fs.BROWSER_CLOSED,h.abort(v)};m.registerToClosedBrowser(y);try{let v=ce(e.onCompleted(),this.testRunTimeout,Ve.TEST_COMPLETE_TIMEOUT_MSG),I=await Fa(v,h.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(R){ot.error("Could not update the grid about the test status",{err:R})}m.isAlive()||(ot.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ot.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(v){throw ot.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:o}),tb(v)}finally{m.unregisterToClosedBrowser(y)}}catch(g){throw ot.warn("failed to start url",{err:g}),tb(g)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await l()}catch(d){throw ot.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var sb={};V(sb,{WorkerExtensionSingleBrowser:()=>ap});var MS,NS,ap,nb=w(()=>{"use strict";Be();B();j();Iu();Pt();ip();MS=A("base-worker"),NS=500,ap=class extends Dn{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,r,n,o){return Q.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()&&(MS.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;N("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 ne(NS)}}});function US(s,e){e===0?s():setTimeout(s,e*Up)}var cp,pa,ob=w(()=>{"use strict";vn();le();Be();Xl();xt();mu();z();j();ie();rh();cp=A("parallel-worker-manager"),pa=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(Py(),he(Cy)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(zy(),he(qy)).WorkerLocalTma:(Yy(),he(Jy)).WorkerAppium;default:return gi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(nb(),he(sb)).WorkerExtensionSingleBrowser:(ip(),he(rb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return N("before new Worker",n.mode),new o(t,...r)}finally{N("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,u=f=>new Promise(g=>{var it,lr,P,L,U,q,at,ya;let h=o.project,y=new Ei(r,n,e,o,i,t),v={},I=e.length,b=((it=o.company)==null?void 0:it.ucid)||"",T=(lr=o.company)==null?void 0:lr.companyId,R=(P=o.company)==null?void 0:P.name,k=o.source||"cli",_=o.user,$=(L=o.company)==null?void 0:L.planType,S=(U=o.company)==null?void 0:U.isStartUp,x=(q=o.projectData)==null?void 0:q.name,D=(at=o.projectData)==null?void 0:at.type,F=o.lightweightMode,J=(ya=o.gridData)==null?void 0:ya.type,H=(Ot,ct,ye,ba,Nn,Ta)=>(m++,Ff({executionId:r,projectId:h,testId:ct,resultId:ye,ucid:b,companyId:T,companyName:R,projectName:x,companyPlan:$,source:k,user:_,lightweightMode:F,isStartUp:S,projectType:D,appSource:Ta,gridType:J}),t.testStartAndReport(Ot,r,ye,ba,Nn)),X=async(Ot,ct,ye,ba,Nn,Ta)=>{var wp,vp,Ep;m--;let Ze={...(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?(Ze.gridName=o.grid||((wp=o.gridData)==null?void 0:wp.name),Ze.gridType=(vp=o.gridData)==null?void 0:vp.type,Ze.gridProvider=(Ep=o.gridData)==null?void 0:Ep.provider):o.localTmaUrl?(Ze.gridName="local-tma-from-options",Ze.gridType="local-tma"):o.useLocalChromeDriver?(Ze.gridName="local-chrome-driver-from-options",Ze.gridType="local-chrome"):o.useChromeLauncher?(Ze.gridName="chrome-launcher-from-options",Ze.gridType="local-chrome"):o.browserstack?Ze.gridName="browserstack-from-options":o.saucelabs&&(Ze.gridName="saucelabs-from-options"),await t.testEndAndReport(Ot,ye,r,ba,Nn,Ze).catch(Qb=>cp.error("testEndAndReport threw an error",{err:Qb})),Nn)return;v[ye.resultId]=ye,Bf({executionId:r,projectId:h,testId:ct,resultId:ye.resultId,result:ye,ucid:b,companyId:T,companyName:R,projectName:x,companyPlan:$,source:k,user:_,lightweightMode:F,logger:cp,isStartUp:S,projectType:D,appSource:Ta}),l&&!ye.success&&(y.stop(),d=!0),(Object.keys(v).length===I||d&&m===0)&&g(v)},de=(Ot,ct)=>{v[ct.resultId]=ct,t.onTestIgnored(Ot,ct.resultId),m--,(Object.keys(v).length===I||d&&m===0)&&g(v)},bt=(Ot,ct)=>t.onGridSlot(Ot,ct);o.userData={loginData:Object.assign({},Ft(),{refreshToken:So(),authData:Ft(),token:f}),projectId:o.project,company:o.company,servicesUrl:me},N("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,r,H,X,bt,de).forEach((Ot,ct)=>{N("before schedule worker.run after createWorkers"),US(()=>{N("right before worker.run"),Ot.run()},ct)})});try{let f=await Yt(),g=await u(f);if(d)throw new qt;return g}catch(f){throw cp.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function ab(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Lc({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 lp(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 up(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=ib.difference(Bs(s,e),t);if(r.length>0)throw dt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var ib,cb=w(()=>{"use strict";ib=E(require("lodash"));B();es();be();z()});var Mn,z_,pp,dp,da,lb=w(()=>{"use strict";Mn=E(require("lodash"));B();j();le();ie();Be();ns();Dl();Xl();be();xt();Pt();ig();z();ob();cb();({testRunStatus:z_,CLI_MODE:pp}=Mt),dp=A("test-plan-runner"),da=class{constructor(e){this.startTime=Date.now();this.workerManager=new pa(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},d=Ft(),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)},u=async()=>{let h=Jn||o.parallel,y=!1;N("right before this.workerManager.runTests");let v=await this.workerManager.runTests(t,c,i,a,o,n,d,h,y);N("right after this.workerManager.runTests"),Object.assign(l,v)},f=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)};jf({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await m(),N("right before runTestPlanTests"),await u(),N("right after runTestPlanTests"),await f(),l}catch(h){if(dp.error("error running test plan",{err:h}),h instanceof qt)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await g()}async function g(){var y,v,I,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===pp.SELENIUM){let[{getSessionPlayer:T},{makeSDK:R}]=await Promise.all([Promise.resolve().then(()=>(Te(),Qt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:k}=T();await k.closeBatch(i,R);return}let h;try{if(!((b=(I=(v=o.company)==null?void 0:v.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(h=await Yc(o.project),Mn.default.isEmpty(h)||!i))return;let{runKey:T,url:R}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:R,apiKey:T}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,c){var b,T,R;let l=re(),d=n.project;La(l),e.forEach(k=>Object.assign(k,{isBeforeTestPlan:!0})),r.forEach(k=>Object.assign(k,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new di(m,n,i,a),f=Mn.default.chain(m).map(k=>{var _;return((_=k.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),g=(f==null?void 0:f.length)===1?f[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(k=>k.name),y=(T=n.lightweightMode)!=null&&T.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,d,this.startTime,o,h);N("before testListInfoPromise");let v=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||Q.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,o,l,c,g),N("before runTestAllPhases");let I=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,n,l,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(l),N("after executionEnd"),{results:I,executionId:l,testPlanName:o,configName:g}}async runTestPlans(e,t){dp.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(d){return Mn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await _c(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==pp.APPIUM&&await up(e,r(l)),await ae(c,async d=>{var g;let m=d.testPlanId;n[m]={};let u=Object.assign({},e);u.baseUrl||=d.startUrl,u.appId||=((g=d.mobileApp)==null?void 0:g.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await vf(e,d);let f=u.overrideExecutionName||d.name;return await ae(l[m],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let v=Object.keys(n[m]).map(R=>({executionId:R,status:lp(n[m][R])})),I=Object.keys(n[m]).map(R=>n[m][R]).reduce((R,k)=>Object.assign(R,k),{}),b=lp(I);Object.assign(o,I);let T=b?v[0].executionId:v.find(R=>!R.status).executionId;return await Pc(i,m,{success:b,executions:v,executionId:T}),y})})}async runAnonymousTestPlan(e,t){var a;dp.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),N("before getSuite");let r=await ab(e,t);if(N("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return N("Right before validateConfig + runAnonymousTestPlan tests map"),await ae(r.tests,async c=>{if(e.resultId){let d=c[0];d.resultId=e.resultId,c=[d]}e.mode!==pp.APPIUM&&await up(e,c),N("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);return N("right after runTestPlan"),await Q.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i),l})}async run(e){let t=mn(),r=[];js(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Mn.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var mb={};V(mb,{init:()=>tI,run:()=>ZS});async function FS(s){let e=s.project,t=await Mc(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"),nn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new ks}function BS(s,e){var i,a,c,l,d,m,u;let t=oo(e.activePlan),r=s.parallel;if(t==="free"&&r>pb)throw new C(`The free plan allows only ${pb} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let f=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!f)throw new C("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
409
|
-
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let f=e.tvcLicense.expireAt||1;if(Date.now()>f)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new C(`Your license allows only ${g} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}let n=s.retentionDays;if(!n)return;let o=(u=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:u.resultRetention;if(n>o)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function jS(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await FS(s)}catch(t){if([C,ks].some(r=>t instanceof r))throw t;mp.error("could not validate cli account",{err:t})}}function $S(s){let e=Ft();return Pm({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function WS(s,{disableResults:e=!1,disableRemoteStep:t=!1,maxNumberOfListeners:r}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return
|
|
408
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,f);return}let v=await oy(f,this.uploadFile);await this.uploadFilesAndForceVisibility(v,t)}}});var Hi,qi,cy=w(()=>{"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,ly=w(()=>{"use strict";ue();B();zi=class extends W{async performAction(){await ne(this.step.durationMS||0)}}});var Ki,uy=w(()=>{"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 kn,py=w(()=>{"use strict";ue();kn=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,dy=w(()=>{"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 my,Bu,ju,fy=w(()=>{"use strict";my=E(require("@applitools/spec-driver-webdriverio"));Hn();Te();Bu=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Ap["@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:my.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}},ju=new Bu});var hy,gy,On,yy=w(()=>{"use strict";hy=E(require("lodash"));ue();j();fy();gy=A("pixel-validation-step-action"),On=class extends W{async performAction(){var m,u;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=((u=r.batch)==null?void 0:u.id)||o,c=await ju.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},d;try{let f=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"};hy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),gy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:h}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){gy.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await ju.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ts,$u=w(()=>{"use strict";xr();z();Ni();Ts=class extends ir{async executeCliCode(){var g,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(g=t.company)==null?void 0:g.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},u=t.data.timeToPlayStep,f=await us(o,i,a,m,c,l,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof se?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,by=w(()=>{"use strict";$u();ar=class extends Ts{isFailedResult(e){return e===!1}}});var Yi,Ty=w(()=>{"use strict";$u();Yi=class extends Ts{isFailedResult(e){return!e}}});var Xi,wy=w(()=>{"use strict";xr();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 ls(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof St?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof se?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var kr,vy=w(()=>{"use strict";ue();kr=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ve,Ey=w(()=>{"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,Sy=w(()=>{"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,Iy=w(()=>{"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 hS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ea(s,e){hS(yS,e),e.registerLocateStepActionUtils(An.getUtils(s))}var yS,Wu=w(()=>{"use strict";vh();Ih();Lh();Dh();Nh();Bh();Wh();Vh();Gh();zh();Kh();Jh();Qh();ty();ay();cy();ly();uy();py();dy();yy();by();Ty();wy();vy();Ey();Sy();Iy();yS={locate:An,scroll:Oi,mouse:_i,submit:Bi,text:Di,"special-key":Ui,"user-code":Gt,"validation-code-step":Gt,"wait-for-code-step":Gt,"action-code-step":Gt,"condition-step":bs,"skip-code-step":bs,"element-code-step":bs,"evaluate-expression":Li,"text-validation":Pn,"wait-for-text-validation":Pn,"select-option":Fi,"drop-file":Wi,"input-file":Gi,hover:ji,navigation:qi,wheel:$i,sleep:zi,refresh:Ki,"api-validation":kn,"api-action":kn,"api-code-step":Gt,"extract-text":Ji,"simple-ui-verification":On,"wait-for-simple-ui-verification":On,"cli-validation-download-file":kr,"cli-wait-for-download-file":kr,"network-validation-step":kr,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Yi,"node-package":Xi,"email-code-step":Gt,"cli-email-code-step":ar,"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,"sfdc-document-validation":kr}});var Ry,bS,ws,Vu=w(()=>{"use strict";Ry=["simple-ui-verification","wait-for-simple-ui-verification"],bS=[...Ry,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation"],ws=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=bS.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 Ry.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 Ay={};V(Ay,{SeleniumTestPlayer:()=>_n});var xy,_n,Gu=w(()=>{"use strict";B();xy=require("@applitools/eyes-sdk-core");vn();z();Ou();hh();Mu();Nu();Th();Uu();Te();Wu();Vu();_n=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new ws(ki());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Rr;let d=new ys(this.driver);this.stepActionFactory=new l(d),ea(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ci(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=bh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new gs(this.driver),FrameLocator:m,portSelector:Pi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:xy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof se&&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 Cy={};V(Cy,{WorkerSelenium:()=>Hu});function wS(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var ta,TS,Hu,Py=w(()=>{"use strict";B();Be();xn();j();Pt();Bo();ie();Pu();z();Gu();Te();ta=A("worker-selenium"),TS=1e9,Hu=class extends ot{initPlayer(t){return new _n(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new fs(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),N("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,TS),await this.windowUtils.validatePageIsAvailable(),N("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 vt||d||m?new vt(`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";Q.onWaitToTestComplete(this.id),wS(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 cn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(f)}),this.testRunTimeout,Ve.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof se&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(ta.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(ta.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),N("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),N("right after super.runTestOnce in workerSelenium");let u=await d();return N("right after runSeleniumTest"),u}catch(u){throw ta.error("failed to run test once",{err:u}),u}}}});var ky,Ge,qu,bt,ra=w(()=>{"use strict";j();ie();le();be();qe();ky=E(require("ora")),Ge=A("mobile-grid-service"),qu=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===O.TESTIM_HEADSPIN?`${Hp}/devices`:e===O.TESTIM_TDC?`${zp}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:o})}catch(i){throw Ge.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Re(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw Ge.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t){let r=await Ns(`${Ca}/access`,void 0,{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`});return JSON.parse(r).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let l=await tl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=l==null?void 0:l[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return(c=e.mobile)==null?void 0:c.version.split("-")[0];if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let l=e.pCloudy_DeviceFullName.split("_");return`${l[0]} ${l[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r){var v;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:c}={},company:{companyId:l=""}={},gridData:{gridId:d="",type:m=""}={}}=r,u=t.capabilities,f=await this.getDeviceNameFromSessionCaps({capabilities:u,gridType:m,projectId:a,projectType:c,companyId:l,gridId:d}),g=u.platformVersion;!g&&m===O.BROWSERSTACK&&(g=(v=u.mobile)==null?void 0:v.version.split("-")[1]),!g&&m===O.TESTIM_TVC&&(g=u.os_version);let h={name:f??"",model:u.deviceModel,osVersion:g,udid:u.udid,osType:u.platformName,scaleFactor:u.pixelRatio,isVirtual:m===O.TESTIM_TVC},y=m===O.TESTIM_TVC&&u.replayUrl;return await br(a,n,o,i,"RUNNING",{device:h,...y&&{remoteResultLink:y}}),Ge.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h,remoteResultLink:y,gridType:m}),h}async getTmaDeviceDetails(e){let t=await Re(`${Zp}/devices`),r=t==null?void 0:t.find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:c}=t;return await br(c,n,o,i,"RUNNING",{device:a}),Ge.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await Dc({appId:e,projectId:t});if(!i)throw Ge.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw Ge.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Gp*60))+1)*60*1e3,Math.max(Vp,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[O.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid",appPath:"testimTvcAppId"},[O.P_CLOUDY]:{name:"pCloudy",appPath:"pCloudyAppId"}},a=i[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,ky.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await rl({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});l.succeed(`app uploaded successfully to ${a}`);let m=i[o].appPath;return d[m]}catch(d){throw l.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:c="",project:l,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f="",host:g=""}=m;if(!c&&e.isAppFromDevice)return n;if(c){Ge.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:i});let I=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:d,executionId:i,testResultId:a});n=I.appUrl,o=I.mobileApp,e.nativeApp=o}else Ge.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,y=this.gridsAppIdGetter[f]({testRunHandler:e,mobileApp:o,gridHost:g}),v=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(y){let I=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:y,gridData:m,projectType:I});b&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:y,projectId:l,testResultId:a,executionId:i,mobileAppId:h}),n=y),!b&&v&&(Ge.info("app not exists on grid, uploading it",{gridAppId:y,projectId:l,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!b&&!v&&Ge.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:i})}return!y&&v&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var l,d;let{accessToken:n,user:o,host:i,key:a,type:c}=t;if(c===O.BROWSERSTACK){let m=`${Yp}/recent_apps`;return(await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a})).some(f=>f.app_url===e)}if(c===O.SAUCELABS){let u=`${i.includes("eu-central-1")?Qp:Xp}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(g=>g.id===e)}if(c===O.TESTIM_HEADSPIN||c===O.TESTIM_TDC){let m=c===O.TESTIM_HEADSPIN?`${qp}/apps`:`${Kp}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(c===O.TESTIM_TVC){let m=`${Jp}/versions/${e}/info`,u=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:m,accessToken:u,authType:"Upload-Token"}),!0}catch(f){return f.status!==404&&Ge.error("error while verifying app exists on TVC",{error:f}),!1}}if(c===O.P_CLOUDY){let m=await this.getPCloudyAuthToken(o,a),u=`${Ca}/drive`,f=await Va({url:u,body:{token:m,filter:"all"},headers:{contentType:null}});return(d=(l=JSON.parse(f).result)==null?void 0:l.files)==null?void 0:d.some(h=>h.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Re(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Re(e,void 0,n)}},bt=new qu});function zu({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!vS.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function ES({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function SS(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 IS(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,c=i?"tdc":"headspin",l=a&&M.flags.enableBatchHeadSpin.isEnabled(),d=i&&(M.flags.enableBatchTDC.isEnabled()||M.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${c}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...o&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:SS(t),[`${c}:enableBatch`]:l||d,...!r&&{"appium:noReset":n}}}function sa(s){return"id"in s?s.id:s.packageName}function RS(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function xS({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a,resetOnSessionStartOnly:c}=t,l={"appium:app":n},d=n==null?void 0:n.startsWith("http");switch(n&&!d&&(l=RS(n,t.gridData.type)),s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":!!i,...!!i&&{"appium:resetOnSessionStartOnly":c},...r&&{"appium:bundleId":sa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":o},...r&&{"appium:appPackage":sa(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Ku({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}){switch(s){case"ios":return{...e,autoAcceptAlerts:!0,platformName:"iOS",automationName:"XCUITest",...t&&{bundleId:sa(t)},...r&&{app:r}};case"android":return{...e,autoGrantPermissions:!0,platformName:"Android",automationName:"UiAutomator2",...n&&{appWaitActivity:n},...t&&{appPackage:sa(t),appActivity:t.activity??".*"},...r&&{app:r}};default:throw Error(`unsupported mobile project ${s}`)}}function _y({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=IS(i.type,o,n);return xS({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Ju({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 Yu({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e;if(s)return s;if(n!=null&&n.deviceName)return r===O.P_CLOUDY?n.deviceUdid:n.deviceName;if(o!=null&&o.deviceNameRegex)return o.deviceNameRegex;if(t==="ios"){if(r===O.BROWSERSTACK)return"iPhone.*";if(r===O.P_CLOUDY)return"apple"}return".*"}function AS(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function CS({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,u=AS(o,s),f=Ju({osVersion:c,mobileConfig:d}),g=Yu({deviceName:l,mobileConfig:d,projectType:s,gridType:m}),h=He(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:g,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":h,"waldo:options":{token:u}};return Ku({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function PS({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)||{},{user:m,key:u,type:f}=o,g=Ju({osVersion:c,mobileConfig:d}),h=Yu({deviceName:l,mobileConfig:d,projectType:s,gridType:f}),y=/^[a-zA-Z]+$/.test(h),v={...g!==".*"&&{pCloudy_DeviceVersion:g},...y&&{pCloudy_DeviceManufacturer:h},...!y&&{pCloudy_DeviceFullName:h}},I={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...v,pCloudy_DurationInMinutes:10,pCloudy_ApplicationName:t,newCommandTimeout:120,fullReset:!0};return t="",Ku({projectType:s,sessionCaps:I,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function kS({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,u=m===O.BROWSERSTACK?"browserstack":"saucelabs",f=Ju({osVersion:c,mobileConfig:d}),g=Yu({deviceName:l,mobileConfig:d,projectType:s,gridType:m}),h={...m===O.BROWSERSTACK&&{os_version:f,device:g,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...m===O.SAUCELABS&&{platformVersion:f,deviceName:g,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${u}.user`]:o.user,[`${u}.key`]:o.key,[`${u}.debug`]:!0,[`${u}.networkLogs`]:!0};return Ku({projectType:s,sessionCaps:h,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Ly(s){return O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type?_y(s):O.TESTIM_TVC===s.gridInfo.type?CS(s):O.P_CLOUDY===s.gridInfo.type?PS(s):kS(s)}function OS(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 Dy(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}`);zu({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=bt.getGridConnection(e),c=Ly(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=OS(r,o==null?void 0:o.mobile);if(!(0,Oy.isEmpty)(m)){let u=Object.entries(m).map(([f,g])=>g.split(",").map(h=>h===".*"||h==="="?"":`${f}:${h}`).join(",")).join(" ").trim();c[`${d}:selector`]=u}}let l=e.type===O.TESTIM_TVC?{alwaysMatch:c}:c;return{...a,desiredCapabilities:c,capabilities:l,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function My(s){var g,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;zu({nativeAppMetadata:r,appPath:o,gridInfo:t}),ES({deviceUdid:l,gridInfo:t,testRunConfig:c});let d=l||((h=(g=c.mobile)==null?void 0:g.staticAllocation)==null?void 0:h.deviceUdid),m=await bt.getGridDirectConnection(t,d),f=_y({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Ny(s){return zu(s),Ly(s)}function Uy(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 Oy,vS,Xu=w(()=>{"use strict";ge();ie();ra();Oy=require("lodash");B();vS=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var na,By=w(()=>{"use strict";na=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,oa,jy=w(()=>{"use strict";j();Qu=A("mobile-frame-locator-mock"),oa=class{foundFrameCallback(){return Qu.info("foundFrameCallback-mock invoked"),{}}locate(){return Qu.info("locate-mock invoked"),{}}async findFrame(){return Qu.info("findFrame-mock invoked"),{}}}});var _S,Wy,$y,vs,Zu=w(()=>{"use strict";_S=E(require("webdriverio")),Wy=require("@applitools/eyes-sdk-core");By();Mu();j();Nu();Uu();Te();Wu();jy();Vu();$y=A("appium-test-player"),vs=class{constructor(e,t,r,n=_S,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=ee(),m=new ys(this.driver);this.stepActionFactory=new l(m),ea(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new ws(ki()),this.sessionPlayer=new a(e,{tabService:new na,cookieUtils:void 0,FrameLocator:oa,portSelector:Pi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Wy.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()),$y.info("appium session deleted",o)}catch(i){$y.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 LS(s){return await Re(`${s}/api/status`)}async function Vy(s,e){return await Re(`${s}/api/devices/${e}/status`)}async function Gy(s){if((await LS(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Hy=w(()=>{"use strict";qe()});var qy={};V(qy,{WorkerLocalTma:()=>sp});var ia,ep,tp,rp,sp,zy=w(()=>{"use strict";qe();Xu();xn();B();j();Pt();Zu();Te();Hy();ra();ia=A("worker-appium"),ep=class extends Error{},tp=class extends Error{},rp=class extends Error{},sp=class extends ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new vs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=ee(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var R;if(Q.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 Gy(i);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=c.type,f=this.options.appId;if(f){let{executionId:k,testResultId:_}=t,{mobileApp:$}=await bt.getMobileAppDataByAppId({appId:f,projectId:l,token:d,executionId:k,testResultId:_});t.nativeApp=$}let g=u==="android"?t.androidActivityWait:null,h=t.nativeAppMetadata,y=t.downloadableAppPublicLink,v=t.appPackageNameOrBundleId;if(!h)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!v)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:I,version:b},T]=await Promise.all([this.getAppStateFromDevice(i,a,v),Vy(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!I&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!I&&y&&await this.installApp(i,a,y);try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(R=this.options.projectData)==null?void 0:R.name}-${this.options.project}`},_=Ny({projectType:u,nativeAppMetadata:h,appPath:y,androidActivityWait:g,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},S=await this.requestNewAppiumSessionFromTma(i,$,h);this.sessionData=S;let x=await m.attach({sessionId:S.sessionId,capabilities:_});this.device=await bt.updateTmaDeviceDetails(a,this.options,t),ia.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:h,sessionCaps:x.capabilities})}catch(k){throw ia.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local"}}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new rp(c):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,c=(await Re(i)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Dt(n);await Ms(`${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 tp(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 ep(`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";Q.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((m,u)=>{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(u)});return await o.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw ia.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw ia.error("failed to run test once",{err:l}),l}}}});var Jy={};V(Jy,{WorkerAppium:()=>np});var Ky,Ln,np,Yy=w(()=>{"use strict";Xu();Ky=require("linkedom");xn();j();Pt();Zu();Te();ra();ie();Ln=A("worker-appium"),np=class extends ot{initPlayer(t){return new vs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,c=await bt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),l=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch},u={projectType:a,nativeAppMetadata:d,appPath:c,androidActivityWait:l,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await bt.lockDevice(o,this.options.deviceUdid),f=await My(u)):f=Dy(u),Ln.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Uy(f)}),this.activeSession=await i.remote(f),this.device=await bt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options),Ln.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Ln.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.TESTIM_TVC?`https://${t}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=r,c=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:v,path:I}=await bt.getHeadSpinDeviceConnection(this.options.gridData,g);l=`${h}://${y}:${v}${I}`}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:(f=this.options.company)==null?void 0:f.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 g=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(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...t.seleniumPerfStats.getStats()}}catch(g){throw Ln.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}};try{return await super.runTestOnce(t,r),await m()}catch(g){throw Ln.error("failed to run test once",{err:g}),g}}}});var aa,Xy=w(()=>{"use strict";B();vn();z();aa=class{constructor(e){this.id=e;this.driver=new Rr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof se&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Qy,ca,Zy=w(()=>{"use strict";Qy=E(require("ws"));B();ca=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 Qy.default(this._cdpUrl,{timeout:e}),r=zt(o=>{t.once("open",o)}),n=zt(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 ua,op,la,eb=w(()=>{"use strict";B();ua=E(require("chrome-launcher"));cu();Zy();sn();op=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ca}async init(e){var u,f,g,h;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:c}=e,l=mi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:c}),d=[...((u=l.desiredCapabilities)==null?void 0:u.chromeOptions.args)??[],...((h=(g=(f=l.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:h.args)??[],...ua.Launcher.defaultFlags().filter(y=>y!=="--disable-extensions")];this.chrome=await ua.launch({chromeFlags:d,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 m=await gr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(m),Zr(()=>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}},la=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new op(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var rb={};V(rb,{WorkerExtension:()=>Dn});function DS(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function tb(s){return DS(s)?s:new Error(s)}var it,Dn,ip=w(()=>{"use strict";Be();z();xn();B();j();Pt();ie();Xy();eb();it=A("worker-ext"),Dn=class extends ot{initPlayer(){return this.options.useChromeLauncher?new la(this.id):new aa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService})}catch(a){throw it.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var 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;N("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Ve.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof se))throw u;return it.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw it.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var f;if(N("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(g){throw it.warn("failed to run test via CDP",{err:g}),g}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let g=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,g,u),c(u)]),this.options.testStartTimeout,Ve.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof se))throw v;it.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let h=new AbortController,y=v=>{e.onCompletedCleanup(),it.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),v.type=Fs.BROWSER_CLOSED,h.abort(v)};m.registerToClosedBrowser(y);try{let v=ce(e.onCompleted(),this.testRunTimeout,Ve.TEST_COMPLETE_TIMEOUT_MSG),I=await Fa(v,h.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(R){it.error("Could not update the grid about the test status",{err:R})}m.isAlive()||(it.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(it.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(v){throw it.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:o}),tb(v)}finally{m.unregisterToClosedBrowser(y)}}catch(g){throw it.warn("failed to start url",{err:g}),tb(g)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await l()}catch(d){throw it.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var sb={};V(sb,{WorkerExtensionSingleBrowser:()=>ap});var MS,NS,ap,nb=w(()=>{"use strict";Be();B();j();Iu();Pt();ip();MS=A("base-worker"),NS=500,ap=class extends Dn{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,r,n,o){return Q.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()&&(MS.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;N("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 ne(NS)}}});function US(s,e){e===0?s():setTimeout(s,e*Up)}var cp,pa,ob=w(()=>{"use strict";vn();le();Be();Xl();xt();mu();z();j();ie();rh();cp=A("parallel-worker-manager"),pa=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(Py(),he(Cy)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(zy(),he(qy)).WorkerLocalTma:(Yy(),he(Jy)).WorkerAppium;default:return gi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(nb(),he(sb)).WorkerExtensionSingleBrowser:(ip(),he(rb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return N("before new Worker",n.mode),new o(t,...r)}finally{N("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,u=f=>new Promise(g=>{var at,lr,P,L,U,q,ct,ya;let h=o.project,y=new Ei(r,n,e,o,i,t),v={},I=e.length,b=((at=o.company)==null?void 0:at.ucid)||"",T=(lr=o.company)==null?void 0:lr.companyId,R=(P=o.company)==null?void 0:P.name,k=o.source||"cli",_=o.user,$=(L=o.company)==null?void 0:L.planType,S=(U=o.company)==null?void 0:U.isStartUp,x=(q=o.projectData)==null?void 0:q.name,D=(ct=o.projectData)==null?void 0:ct.type,F=o.lightweightMode,J=(ya=o.gridData)==null?void 0:ya.type,H=(Ot,lt,ye,ba,Nn,Ta)=>(m++,Ff({executionId:r,projectId:h,testId:lt,resultId:ye,ucid:b,companyId:T,companyName:R,projectName:x,companyPlan:$,source:k,user:_,lightweightMode:F,isStartUp:S,projectType:D,appSource:Ta,gridType:J}),t.testStartAndReport(Ot,r,ye,ba,Nn)),X=async(Ot,lt,ye,ba,Nn,Ta)=>{var wp,vp,Ep;m--;let Ze={...(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?(Ze.gridName=o.grid||((wp=o.gridData)==null?void 0:wp.name),Ze.gridType=(vp=o.gridData)==null?void 0:vp.type,Ze.gridProvider=(Ep=o.gridData)==null?void 0:Ep.provider):o.localTmaUrl?(Ze.gridName="local-tma-from-options",Ze.gridType="local-tma"):o.useLocalChromeDriver?(Ze.gridName="local-chrome-driver-from-options",Ze.gridType="local-chrome"):o.useChromeLauncher?(Ze.gridName="chrome-launcher-from-options",Ze.gridType="local-chrome"):o.browserstack?Ze.gridName="browserstack-from-options":o.saucelabs&&(Ze.gridName="saucelabs-from-options"),await t.testEndAndReport(Ot,ye,r,ba,Nn,Ze).catch(Qb=>cp.error("testEndAndReport threw an error",{err:Qb})),Nn)return;v[ye.resultId]=ye,Bf({executionId:r,projectId:h,testId:lt,resultId:ye.resultId,result:ye,ucid:b,companyId:T,companyName:R,projectName:x,companyPlan:$,source:k,user:_,lightweightMode:F,logger:cp,isStartUp:S,projectType:D,appSource:Ta}),l&&!ye.success&&(y.stop(),d=!0),(Object.keys(v).length===I||d&&m===0)&&g(v)},de=(Ot,lt)=>{v[lt.resultId]=lt,t.onTestIgnored(Ot,lt.resultId),m--,(Object.keys(v).length===I||d&&m===0)&&g(v)},Tt=(Ot,lt)=>t.onGridSlot(Ot,lt);o.userData={loginData:Object.assign({},Ft(),{refreshToken:So(),authData:Ft(),token:f}),projectId:o.project,company:o.company,servicesUrl:me},N("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,r,H,X,Tt,de).forEach((Ot,lt)=>{N("before schedule worker.run after createWorkers"),US(()=>{N("right before worker.run"),Ot.run()},lt)})});try{let f=await Yt(),g=await u(f);if(d)throw new qt;return g}catch(f){throw cp.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function ab(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Lc({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 lp(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 up(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=ib.difference(Bs(s,e),t);if(r.length>0)throw mt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var ib,cb=w(()=>{"use strict";ib=E(require("lodash"));B();es();be();z()});var Mn,z_,pp,dp,da,lb=w(()=>{"use strict";Mn=E(require("lodash"));B();j();le();ie();Be();ns();Dl();Xl();be();xt();Pt();ig();z();ob();cb();({testRunStatus:z_,CLI_MODE:pp}=Mt),dp=A("test-plan-runner"),da=class{constructor(e){this.startTime=Date.now();this.workerManager=new pa(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},d=Ft(),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)},u=async()=>{let h=Jn||o.parallel,y=!1;N("right before this.workerManager.runTests");let v=await this.workerManager.runTests(t,c,i,a,o,n,d,h,y);N("right after this.workerManager.runTests"),Object.assign(l,v)},f=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)};jf({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await m(),N("right before runTestPlanTests"),await u(),N("right after runTestPlanTests"),await f(),l}catch(h){if(dp.error("error running test plan",{err:h}),h instanceof qt)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await g()}async function g(){var y,v,I,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===pp.SELENIUM){let[{getSessionPlayer:T},{makeSDK:R}]=await Promise.all([Promise.resolve().then(()=>(Te(),Qt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:k}=T();await k.closeBatch(i,R);return}let h;try{if(!((b=(I=(v=o.company)==null?void 0:v.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(h=await Yc(o.project),Mn.default.isEmpty(h)||!i))return;let{runKey:T,url:R}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:R,apiKey:T}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,c){var b,T,R;let l=re(),d=n.project;La(l),e.forEach(k=>Object.assign(k,{isBeforeTestPlan:!0})),r.forEach(k=>Object.assign(k,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new di(m,n,i,a),f=Mn.default.chain(m).map(k=>{var _;return((_=k.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),g=(f==null?void 0:f.length)===1?f[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(k=>k.name),y=(T=n.lightweightMode)!=null&&T.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,d,this.startTime,o,h);N("before testListInfoPromise");let v=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||Q.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,o,l,c,g),N("before runTestAllPhases");let I=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,n,l,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(l),N("after executionEnd"),{results:I,executionId:l,testPlanName:o,configName:g}}async runTestPlans(e,t){dp.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(d){return Mn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await _c(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==pp.APPIUM&&await up(e,r(l)),await ae(c,async d=>{var g;let m=d.testPlanId;n[m]={};let u=Object.assign({},e);u.baseUrl||=d.startUrl,u.appId||=((g=d.mobileApp)==null?void 0:g.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await vf(e,d);let f=u.overrideExecutionName||d.name;return await ae(l[m],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let v=Object.keys(n[m]).map(R=>({executionId:R,status:lp(n[m][R])})),I=Object.keys(n[m]).map(R=>n[m][R]).reduce((R,k)=>Object.assign(R,k),{}),b=lp(I);Object.assign(o,I);let T=b?v[0].executionId:v.find(R=>!R.status).executionId;return await Pc(i,m,{success:b,executions:v,executionId:T}),y})})}async runAnonymousTestPlan(e,t){var a;dp.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),N("before getSuite");let r=await ab(e,t);if(N("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return N("Right before validateConfig + runAnonymousTestPlan tests map"),await ae(r.tests,async c=>{if(e.resultId){let d=c[0];d.resultId=e.resultId,c=[d]}e.mode!==pp.APPIUM&&await up(e,c),N("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);return N("right after runTestPlan"),await Q.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i),l})}async run(e){let t=mn(),r=[];js(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Mn.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var mb={};V(mb,{init:()=>tI,run:()=>ZS});async function FS(s){let e=s.project,t=await Mc(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"),nn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new ks}function BS(s,e){var i,a,c,l,d,m,u;let t=oo(e.activePlan),r=s.parallel;if(t==="free"&&r>pb)throw new C(`The free plan allows only ${pb} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let f=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!f)throw new C("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
409
|
+
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let f=e.tvcLicense.expireAt||1;if(Date.now()>f)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new C(`Your license allows only ${g} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}let n=s.retentionDays;if(!n)return;let o=(u=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:u.resultRetention;if(n>o)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function jS(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await FS(s)}catch(t){if([C,ks].some(r=>t instanceof r))throw t;mp.error("could not validate cli account",{err:t})}}function $S(s){let e=Ft();return Pm({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function WS(s,{disableResults:e=!1,disableRemoteStep:t=!1,maxNumberOfListeners:r}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return ht.connect(s);if(!t){let{remoteStepService:n}=await Promise.resolve().then(()=>(Ti(),qg));await n.init(s)}if(!e){let{testResultService:n}=await Promise.resolve().then(()=>(wi(),Jg));n.init(s,r)}}function VS(s,e){let{branch:t,autoDetect:r}=s;if(Rf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function GS(s){let{project:e}=s,t=mn();db.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(s.sfdcCredential=await Ac({projectId:e,branch:t}))}function HS(s,e){let{onprem:t,id:r,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:m,extensionPath:u,ext:f,playerPath:g}=s;if([Y.SELENIUM].includes(m)&&!g)throw new C("in selenium on prem mode --player-path must be provided");if(m==="extension"&&!u&&!f)throw new C("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),d=oo(a);d==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<ub?ub:s.newBrowserWaitTimeout),M.setCompanyId(r),M.setIsPOC(c),M.setIsStartUp(l),M.setPlanType(d),Ct.setPlanType(d),s.company={ucid:"",companyId:r,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:d,isPOC:c,isStartUp:l,activePlan:a}}function qS(s,e){s.editorUrl=Ps||e.editorUrl}function zS(s,e){s.allGrids=e}function KS(s,e){s.authData=e}function JS(s,e){let{id:t,name:r,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function YS(s){s.gridData=await Ef(s)}async function XS(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(mt("user-override-file",t),s.mockNetworkRules=await gm(s.overrideMappingFile))}async function QS(s,e){N("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await Xm(),N("in runner.js after checkNpmVersion"),await jS(s),N("in runRunner before tunnel.connect"),await qo(s),N("in runRunner after tunnel.connect");let a=await new da(e).run(s);return N("before tunnel.disconnect"),await zo(s),await pn.end(t),N("after tunnel.disconnect and gridService.keepAlive.end"),a}function eI(s){var e;Ct.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
410
410
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
411
411
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
412
412
|
`)}async function tI(s){var h,y,v;N("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o,parallel:i}=s,a=WS(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep),maxNumberOfListeners:i||1});a.catch(()=>{});let{authData:c,editorConfig:l,companyByProjectId:d,projectById:m,branchName:u,allGrids:f}=await tn(s);if(await a,N("after featureFlagsReady and socketConnected"),qS(s,l),HS(s,d),JS(s,m),VS(s,u),zS(s,f),KS(s,c),await GS(s),await YS(s),BS(s,d),M.flags.clearRunnerFileCache.isEnabled())try{await qr(),mp.info("runner file cache cleared")}catch(I){mp.error("failed to clear runner file cache",{err:I})}(h=s.lightweightMode)!=null&&h.disableLabs||await gi.loadLabFeatures(m.id,d.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(M.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((v=s.lightweightMode)==null?void 0:v.type)==="turboMode"&&console.log(`
|
|
413
|
-
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`),pn.start(e),$S(e),await XS(s),eI(s);let g=mn();await Q.setOptions(s,g)}var db,ub,pb,mp,ZS,fb=w(()=>{"use strict";db=E(require("lodash"));B();Rl();_l();Be();ns();es();Dl();be();xt();Ut();j();Pt();le();ie();z();lb();yi();mu();ge();gn();il();ub=30*60*1e3,pb=1,mp=A("runner");ZS=QS});function gb(s){s.get("/",(e,t)=>{let r=fp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Il()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());hl({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var hb=w(()=>{"use strict";ts();gp();Rl()});var hp,yb,Es,ma,bb=w(()=>{"use strict";hp=E(require("chalk"));xr();yb=require("express");j();z();Es=A("cli-router"),ma=(0,yb.Router)();ma.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 us(t,r,n,o,i,a,c,l,d);m.success||(console.log(hp.default.red(m.result.resultValue)),Es.error("CLI Action Failure",{message:m.result.resultValue})),e.status(200).json({success:!0,data:m})}catch(m){Es.error("failed to run cli code",{err:m}),console.log(hp.default.red("failed to run cli code",m)),e.status(500).json({success:!1,code:"internal-error"})}});ma.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 ls(t,r,n,o,i,a);Es.info("installed packages successfully"),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof
|
|
413
|
+
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`),pn.start(e),$S(e),await XS(s),eI(s);let g=mn();await Q.setOptions(s,g)}var db,ub,pb,mp,ZS,fb=w(()=>{"use strict";db=E(require("lodash"));B();Rl();_l();Be();ns();es();Dl();be();xt();Ut();j();Pt();le();ie();z();lb();yi();mu();ge();gn();il();ub=30*60*1e3,pb=1,mp=A("runner");ZS=QS});function gb(s){s.get("/",(e,t)=>{let r=fp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Il()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());hl({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var hb=w(()=>{"use strict";ts();gp();Rl()});var hp,yb,Es,ma,bb=w(()=>{"use strict";hp=E(require("chalk"));xr();yb=require("express");j();z();Es=A("cli-router"),ma=(0,yb.Router)();ma.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 us(t,r,n,o,i,a,c,l,d);m.success||(console.log(hp.default.red(m.result.resultValue)),Es.error("CLI Action Failure",{message:m.result.resultValue})),e.status(200).json({success:!0,data:m})}catch(m){Es.error("failed to run cli code",{err:m}),console.log(hp.default.red("failed to run cli code",m)),e.status(500).json({success:!1,code:"internal-error"})}});ma.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 ls(t,r,n,o,i,a);Es.info("installed packages successfully"),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof St){Es.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 se){Es.error("timeout installing node package"),e.status(200).json({success:!1,code:"timeout"});return}Es.error("failed to install node packages",{err:c}),e.status(500).json({success:!1,code:"internal-error"})}})});var rI,Tb=w(()=>{"use strict";xr();j();bb();rI=A("cli-service");Dg().catch(s=>rI.warn("failed to clean local package folder",{err:s}))});async function sI(s,e,t="utf8"){let r=Eb.join(vb.tmpdir(),s);return await wb.promises.writeFile(r,e,t),r}async function oI(s){var t;let e=Date.now();try{let r=`
|
|
414
414
|
module.paths = ${JSON.stringify(module.paths)};
|
|
415
415
|
process.on('unhandledRejection', (error) => {
|
|
416
416
|
process.send({type: 'unhandledRejection', error: {message: error.message, stack: error.stack}});
|
|
@@ -423,7 +423,7 @@ Turbo mode will ignore step delays. Test artifacts like screenshots and logs wil
|
|
|
423
423
|
${s};
|
|
424
424
|
`,n=await sI(`tst-playground-${Date.now()}.js`,r),o=nI(n);Ss[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=Ss[e])==null||t.kill(),delete Ss[e]}}async function Ib({code:s,type:e}){if(yp.includes(e))return oI(s);throw new Ur}function Rb(){Object.keys(Ss).forEach(s=>{Ss[s].kill(),delete Ss[s]})}var wb,vb,Eb,Sb,yp,Ss,nI,xb=w(()=>{"use strict";wb=E(require("fs")),vb=E(require("os")),Eb=E(require("path")),Sb=require("child_process");z();yp=["playwright","selenium","puppeteer"],Ss={};nI=s=>{let e,t=new Promise(n=>{e=n}),r=(0,Sb.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 Fr(i.stack)})}),r.on("error",n=>{e({error:n})}),r.on("exit",n=>{e({exitCode:n})}),Object.assign(t,{child:r})}});var Pb,fa,kb,Ab,Cb,iI,Ob=w(()=>{"use strict";Pb=require("express");j();z();le();xb();fa=(0,Pb.Router)(),kb=A("playground-router"),Ab=["localhost","app.testim.io","playground.testim.io","staging.testim.io","app.staging.testim.cc","tta-crm.tricentis.com"],Cb=s=>{if(!s)return{};try{return new URL(s)}catch{return{}}},iI=(s,e,t)=>{if(qn)return t();let{referer:r,origin:n}=s.headers;if(!r&&!n)return e.status(400).send();let o=Cb(r),i=Cb(n);return!Ab.includes(o.hostname)&&!Ab.includes(i.hostname)?e.status(400).send():t()};fa.post("/run",iI,async(s,e)=>{let{code:t,type:r}=s.body;if(!t||!yp.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 Ur){e.status(404).send({success:!1});return}if(n instanceof Fr){e.json({success:!1,type:"playground-error",stack:n.innerStack});return}e.json({success:!1,reason:n.message}),kb.error(n)}});fa.post("/stop",(s,e)=>{try{Rb(),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),kb.error(t)}})});function Lb(s){let e=(0,_b.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 _b,Db=w(()=>{"use strict";_b=require("express")});var Fb={};V(Fb,{orchestrateRoutes:()=>aI});function aI(s,e){let t=(0,Nb.default)();s(t),t.use(bp.default.urlencoded({extended:!1,limit:"50mb"})),t.use((0,Ub.default)()),t.use(bp.default.json({limit:"50mb"}));let n={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:ke||qn?"*":["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,Mb.default)(n)),gb(t),t.use("/playground",fa),t.use("/cliJs",ma),t.use("/standalone-browser",Lb(e)),t.use((o,i)=>{i.status(404).send("Endpoint Not Found")}),t}var Mb,Nb,bp,Ub,Bb=w(()=>{"use strict";Mb=E(require("cors")),Nb=E(require("express")),bp=E(require("body-parser")),Ub=E(require("compression"));hb();Tb();Ob();Db();le()});var $b={};V($b,{init:()=>cI});async function cI({agentPort:s,agentBind:e,project:t,token:r,installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i},a){await uI({installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i,project:t}),await lI({agentPort:s,agentBind:e,project:t,token:r},a)}async function lI({agentPort:s,agentBind:e,project:t,token:r},n){let{orchestrateRoutes:o}=await Promise.resolve().then(()=>(Bb(),Fb));return new Promise((i,a)=>{let c=()=>{};t&&(im(t,r),c=f=>{f.use((g,h,y)=>{Object.assign(g,{project:t}),y()})});let l=o(c,n),d=jb.createServer(l);d.listen(s,e),d.on("error",m),d.on("listening",u);function m(f){if(f.syscall!=="listen")return a(f);switch(f.code){case"EACCES":case"EPERM":return a(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return a(new C(`Port ${s} is already in use, is another Testim instance running?`));default:return a(f)}}function u(){let{port:f}=d.address();console.log(`Running on port: ${f}`),pI()}})}function uI({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"),hr({projectId:r})),Promise.all(n)}async function pI(){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 jb,Wb=w(()=>{"use strict";jb=E(require("http"));xt();z();wr();Yr()});var Jb={};V(Jb,{getStartedWithStart:()=>fp,runAgentMode:()=>gI});async function gI(s){var r;let e;if(await yr(s.playerLocation,s.canary),s.startTestimBrowser){await bI();try{e=await yI(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new C('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(Wb(),$b));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(Gu(),he(Ay)));let o=["webpack"];for(let i of o)await Ee(i,{silent:!0}).catch(()=>null)},6e3),t.init(s,e)}function fp(){return zb}function Vb(s){try{return process.kill(s,0)}catch{return!1}}async function hI(s,e,t){let r=cr.join(Nt,`chrome-${Ys}-process`),n=3e3,o=()=>{Ce.rmSync(r,{recursive:!0}),console.log(`
|
|
425
425
|
|
|
426
|
-
Browser session ended`),process.exit(0)};if(await fe(r)){let f=JSON.parse(Ce.readFileSync(r));if(Vb(f.pid)){let g=()=>Vb(f.pid)?setTimeout(g,n):o();return g(),{webdriverApi:f}}}let i=await vo();await fe(Is)||await Ce.promises.mkdir(Is,{recursive:!0});let c=[...Kb(Is,e,t,i).desiredCapabilities.chromeOptions.args,...ha.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await ha.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Is,chromePath:i,envVars:l}),u={port:m.port,pid:m.pid,cdpUrl:await gr(`localhost:${m.port}`)};return Ce.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",o),m.process.once("close",o),{webdriverApi:u}}async function yI(s){let e=`${jp}/extension/testim-full-master.zip`,t=cr.basename(e),r=cr.join(Nt,t),n=cr.join(Nt,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await fe(r)){let f=await Ce.promises.stat(r);o=Date.now()-mI>f.mtimeMs}if(await Ce.promises.mkdir(Nt,{recursive:!0}),o){let f=(0,Hb.default)("Downloading Testim Editor").start();await ze(e,r);try{await
|
|
426
|
+
Browser session ended`),process.exit(0)};if(await fe(r)){let f=JSON.parse(Ce.readFileSync(r));if(Vb(f.pid)){let g=()=>Vb(f.pid)?setTimeout(g,n):o();return g(),{webdriverApi:f}}}let i=await vo();await fe(Is)||await Ce.promises.mkdir(Is,{recursive:!0});let c=[...Kb(Is,e,t,i).desiredCapabilities.chromeOptions.args,...ha.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await ha.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Is,chromePath:i,envVars:l}),u={port:m.port,pid:m.pid,cdpUrl:await gr(`localhost:${m.port}`)};return Ce.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",o),m.process.once("close",o),{webdriverApi:u}}async function yI(s){let e=`${jp}/extension/testim-full-master.zip`,t=cr.basename(e),r=cr.join(Nt,t),n=cr.join(Nt,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await fe(r)){let f=await Ce.promises.stat(r);o=Date.now()-mI>f.mtimeMs}if(await Ce.promises.mkdir(Nt,{recursive:!0}),o){let f=(0,Hb.default)("Downloading Testim Editor").start();await ze(e,r);try{await rt(r,n)}catch{await Ce.promises.rm(r,{recursive:!0,force:!0}),await ze(e,r);try{await rt(r,n)}catch{throw await Ce.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Ce.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let i=s.extensionPath?null:(await Ce.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await hI(s,i,n);await hr({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=Kb(Is,i,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(vn(),he(Ag)),{SeleniumPerfStats:l}=(is(),he(eg)),d=new c;d.seleniumPerfStats=new l;let m=await d.initClient(a);zb=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await gr(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:dI,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function bI(){if(await fe(ga))try{let{webSocketDebuggerUrl:s}=await TI();await wI(s),await Ce.promises.unlink(ga)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Ce.promises.unlink(ga)}}async function TI(){let s=await Ce.promises.readFile(ga,{encoding:"utf8"}),[e,t]=s.split(`
|
|
427
427
|
`).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 gr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function wI(s,e=100){let t=await vI(s,e);return zt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function vI(s,e=100){let t=new qb.default(s,{timeout:e}),r=zt(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=zt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}var Gb,Hb,qb,Ce,cr,ha,dI,mI,Is,fI,ga,zb,gp=w(()=>{"use strict";Gb=E(require("ms")),Hb=E(require("ora")),qb=E(require("ws")),Ce=E(require("fs")),cr=E(require("path")),ha=E(require("chrome-launcher"));le();Yr();z();wr();Tc();B();dI=Kn?"verbose":"silent",mI=(0,Gb.default)("1h"),Is=cr.join(Nt,"profile"),fI="DevToolsActivePort",ga=cr.join(Is,fI);zb=!1});var NL=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 Ip=require("perf_hooks");var Gn=E(require("os")),xs=E(require("url")),As=E(require("http")),wa=E(require("https")),Fn=E(require("form-data")),Bn=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)}},jn=class extends Bn{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let 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 Fn.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}},$n=class extends Error{},Wn=class extends Error{},Vn=class extends Error{},ur=class extends Error{},Se=class extends Bn{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=As.globalAgent;this.nodejsHttpsAgent=wa.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 (${Gn.type()} ${Gn.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 jn(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&&!xs.parse(r,!1,!0).protocol)throw new $n("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new Vn(`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 ur("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 ur("XHR readyState must be OPENED");if(this._request)throw new ur("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new Wn(`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
|
|
428
428
|
`):""}overrideMimeType(t){if([Se.LOADING,Se.DONE].includes(this.readyState))throw new ur("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new Rs("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new Wn("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:"?As:wa).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 Fn.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 Fn.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=As.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:xs.resolve(this.nodejsBaseUrl,t),a=xs.parse(i,!1,!0);return a.hash=null,a.auth&&(o!=null||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=$n,Pe.ProgressEvent=Rs,Pe.SecurityError=Vn,Pe.XMLHttpRequest=Se,Pe.InvalidStateError=ur,Pe.XMLHttpRequestUpload=jn,Pe.UNSENT=0,Pe.OPENED=1,Pe.HEADERS_RECEIVED=2,Pe.LOADING=3,Pe.DONE=4;Object.assign(global,{xhr2:Pe,XMLHttpRequest:Pe,performance:Ip.performance,...typeof Blob>"u"&&{Blob:require("buffer").Blob}});var Yb=E(require("semver"));Be();il();Ut();Yr();var Tp=E(require("chalk")),Xb=require("events");ie();sn();z();ie();Io();j();var bm=E(require("os")),al=E(require("path")),cl=E(require("chalk")),_o=require("fs");le();function Tm(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=bm.homedir();(0,_o.mkdirSync)(al.resolve(n,".testim_logs"),{recursive:!0});let o=al.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}`),Mp&&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(cl.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(cl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,_o.writeFileSync)(o,`${s}
|
|
429
429
|
${s==null?void 0:s.stack}
|