@testim/testim-cli 4.3.0 → 4.3.1
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 +62 -62
- package/cli.js.map +4 -4
- package/npm-shrinkwrap.json +536 -188
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
"use strict";var ow=Object.create;var zn=Object.defineProperty;var iw=Object.getOwnPropertyDescriptor;var aw=Object.getOwnPropertyNames;var cw=Object.getPrototypeOf,lw=Object.prototype.hasOwnProperty;var T=(r,e)=>()=>(r&&(e=r(r=0)),e);var W=(r,e)=>{for(var t in e)zn(r,t,{get:e[t],enumerable:!0})},Ld=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of aw(e))!lw.call(r,n)&&n!==t&&zn(r,n,{get:()=>e[n],enumerable:!(s=iw(e,n))||s.enumerable});return r};var E=(r,e,t)=>(t=r!=null?ow(cw(r)):{},Ld(e||!r||!r.__esModule?zn(t,"default",{value:r,enumerable:!0}):t,r)),ie=r=>Ld(zn({},"__esModule",{value:!0}),r);var _e={};W(_e,{log:()=>_,measure:()=>dw});function _(...r){if(!Fd)return;let e=Date.now();console.log(`${e-uw} ${e-Md} `,...r),Md=e}function dw(r,e){if(!Fd)return;let t=Date.now();try{r()}finally{console.log(e||r.name,"took",Date.now()-t)}}var Fd,uw,Md,Oe=T(()=>{"use strict";Fd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,uw=Date.now(),Md=Date.now()});var Fa,Hr,Ua,Bs=T(()=>{"use strict";Fa={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"},Hr="element-6066-11e4-a52e-4f735466cecf",Ua=79});function z(r=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let s=0;s<r;s++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function at(r,e,t,s,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${r}/#/project/${e}/branch/${n}/test/${t}`,s&&(o+=`?result-id=${s}`)),o}function ja(r,e){return`Basic ${Buffer.from(`${r}:${e}`).toString("base64")}`}function Ge(r){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(r)||t.test(r)}var Ba=T(()=>{"use strict"});var Wa,Ud,jd,to=T(()=>{Wa={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"},Ud={"@applitools/eyes-sdk-core":"13.11.31","@applitools/spec-driver-webdriverio":"1.4.29","@testim/coralogix-logger":"1.1.27-beta.1","abort-controller":"3.0.0",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",decompress:"4.2.1",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0",glob:"7.2.0","https-proxy-agent":"5.0.0","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.16.2",jsdom:"19.0.0",linkedom:"^0.14.25",jsonwebtoken:"9.0.0",lodash:"4.17.21","memory-fs":"0.5.0",moment:"2.29.4",ms:"2.1.2",npm:"8.19.2","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"5.0.0","rox-node":"4.9.18",semver:"7.3.2","serialize-error":"7.0.1","socket.io-client":"4.5.4","source-map-support":"0.5.19",superagent:"3.8.3","superagent-proxy":"3.0.0","test-exclude":"6.0.0",threads:"0.12.0","ua-parser-js":"0.7.33","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.6.0","winston-transport":"4.5.0",ws:"8.5.0",xml2js:"0.4.23",yaml:"1.10.0"},jd={node:">= 14.0.0"}});var $s,Bd,$d,ro,Wd,so,zr,Gd,
|
|
3
|
-
${u.msg}`));for(let m of hw)a[m]instanceof Error&&(u[m]={message:a[m].message,stack:a[m].stack,name:a[m].name,type:a[m].type,cause:a[m].cause,...a[m]});Object.keys(u).length>0&&(i&&!p&&(u.msg=i),d.text=u),this.logger.addLog(d),s(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Jr.options=t}}});var Ya={};W(Ya,{getLogger:()=>I,setExecutionId:()=>Ka,setProjectId:()=>Ja,setProxyUri:()=>Xa});function bw(){let r=[],e=()=>Promise.resolve();if(!Le){let{CoralogixTransport:t}=(qa(),ie(Va));t.configure(rp);let s=new t({category:"ROOT"});r.push(s),e=()=>s.waitForFlush()}return Vd&&r.push(new vt.transports.Console({format:vt.format.combine(vt.format.colorize(),vt.format.simple())})),[r,e]}function Ka(r){Ha=r}function Ja(r){sp=r}function Xa(r){if(Le||!r)return;let{CoralogixTransport:e}=(qa(),ie(Va));e.configure({...rp,proxyUri:r})}function ep(r){return{projectId:sp,time:new Date().toISOString(),...Ha&&!r&&{executionId:Ha}}}function I(r){return new za(Sw.child({category:r}))}var tp,vt,gw,yw,rp,ww,Tw,vw,Ew,Sw,Ha,sp,za,j=T(()=>{"use strict";tp=E(require("os")),vt=E(require("winston"));le();U();gw=tp.hostname(),yw=ct(),rp={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[ww,Tw]=bw(),vw=qd?"debug":"info",Ew={release:Boolean(!0),branch:"production"},Sw=vt.createLogger({levels:vt.config.syslog.levels,level:vw,transports:ww,defaultMeta:{name:"runner",hostname:gw,nodeVersion:process.version,runnerVersion:yw,...Ew}}),Ha=null,sp=null;za=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,s={}){let{executionId:n}=s;try{this._logger.log(e,Object.assign({meta:s,message:t},ep(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},ep(n)))}catch{}}}waitForFlush(){return Tw()}}});var np={};W(np,{AbortError:()=>Be,ArgError:()=>P,ClientError:()=>gr,GetBrowserError:()=>Vt,GridConcurrencyError:()=>hr,GridError:()=>ut,NoArgsError:()=>mr,NotImplementedError:()=>Yr,NpmPackageError:()=>dt,NpmPermissionsError:()=>br,PageNotAvailableError:()=>lt,PlaygroundCodeError:()=>yr,QuotaDepletedError:()=>Xr,SeleniumCrashError:()=>Gs,SeleniumError:()=>fr,StopRunOnError:()=>_t,TimeoutError:()=>X,WebdriverCapabilitiesError:()=>Ws});var Qa,Be,mr,P,fr,_t,Vt,lt,Ws,X,Xr,ut,hr,dt,Gs,gr,yr,br,Yr,q=T(()=>{"use strict";Qa=require("p-retry"),Be=class extends Error{constructor(t="aborted"){super(t);this.name="AbortError"}},mr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},fr=class extends Error{constructor(t){super(t.orgStatusMessage||t.message);this.name="SeleniumError",this.errorType=t.type}},_t=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},Vt=class extends Error{constructor(t,s){super(t);this.type=s}},lt=class extends Qa.AbortError{},Ws=class extends Qa.AbortError{},X=class extends Error{},Xr=class extends Error{},ut=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},hr=class extends ut{constructor(){super(...arguments);this.name="GridConcurrencyError"}},dt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Gs=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},gr=class extends Error{},yr=class extends Error{},br=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Yr=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function io(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"&&typeof r.catch=="function"}function se(r){return new Promise(e=>{setTimeout(e,r)})}function te(r,e,t="Timeout Error"){so&&!op&&(op=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let s=new X(t);return e=so?Number(so)||6e5:e,Promise.race([r,se(e).then(()=>{throw s})])}async function de(r,e,{concurrency:t}={}){if(t){ip||(ip=(await import("p-limit")).default);let s=ip(t);return await Promise.all(Array.from(r,(n,o)=>s(()=>e(n,o))))}return await Promise.all(Array.from(r,e))}function pt(r){return new Promise((e,t)=>{r((s,n)=>s?t(s):e(n))})}var op,ip,Za=T(()=>{"use strict";q();le();op=!1});var qs,ap,Rw,Vs,cp,Iw,xw,lp,up=T(()=>{"use strict";qs=E(require("lodash"));le();ap=require("dns");j();Za();Rw=I("http-request-counters"),Vs=!1,cp=async()=>{if(Le)return!0;let r=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await de(r,t=>ap.promises.lookup(t)));return e||(Vs=!0),e}catch{return Rw.error("network connectivity test failed"),Vs=!0,!1}},Iw=qs.throttle(cp,10*1e3),xw=60*1e3*15,lp=()=>{let r={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},xw)}function t(n,o=n.name){return async function(...i){e(r.call,o);try{let a=await n.call(null,...i);return e(r.success,o),a}catch(a){throw e(r.fail,o),Vs||Iw(),a}}}async function s(){if(Vs||!await cp())return!1;let n=qs.sum([...r.fail.values()]),o=qs.sum([...r.call.values()]);return n<o*.1}return s.counters=r,t.counters=r,t.isNetworkHealthy=s,t.didNetworkConnectivityTestFail=()=>Vs,t}});var Ot={};W(Ot,{deleteFullRes:()=>_w,deleteReq:()=>Hs,didNetworkConnectivityTestFail:()=>ic,download:()=>nc,get:()=>Tr,getFullRes:()=>Nw,getText:()=>Lw,head:()=>Dw,isNetworkHealthy:()=>oc,post:()=>St,postForm:()=>tc,postFullRes:()=>Ow,put:()=>sc});function Aw(){return global.caFileContent}function Cw(r,e){let t=[];r.on("data",s=>{t.push(s)}),r.on("end",()=>{e(null,Buffer.concat(t))})}function kw(){return!Et.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Et.default),global.proxyUri}function wr(r,e=!1){let t=Aw();t&&r.ca(t);let s=!e&&kw();s&&r.proxy(s)}async function dp(r,e={},t={},s=Qr){let n=Et.default.delete(r).send(e).timeout(s).set(t);return wr(n),await n}async function pp(r,e,t={},s=Qr,n=0){let o=Et.default.post(r).send(e).timeout(s).set(t);wr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=r,i.originalRequestTimeout=s,i.additionalSetHeaders=t,i}}async function rc(r,e,t={},s=Qr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Et.default.get(r).query(e||{}).timeout(s).set(t);return n&&i.buffer(!0),wr(i,o),await i}var Et,ec,qe,Qr,Pw,qt,Hs,_w,St,Ow,tc,Lw,Tr,Nw,Dw,sc,nc,oc,ic,Rt=T(()=>{"use strict";Et=E(require("superagent"));j();up();ec=I("http-request"),qe=lp(),Qr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,Pw=6e4;qt=(r,e,t)=>{throw ec.error(r,{...t,error:e}),e};Hs=qe(async(r,e,t,s)=>{try{let n=await dp(r,e,t,s);return n.type==="text/plain"?n.text:n.body}catch(n){return qt("failed to delete request",n,{url:r})}});_w=qe(dp),St=qe(async({url:r,body:e,headers:t,timeout:s,retry:n})=>{try{let o=await pp(r,e,t,s,n);return o.type==="text/plain"?o.text:o.body}catch(o){return qt("failed to post request",o,{url:r})}});Ow=qe(pp),tc=qe(async(r,e,t,s={},n=Qr)=>{let o=Et.default.post(r).type("form").timeout(n).set(s);o.field(e),Object.keys(t).forEach(i=>{o.attach(i,t[i].buffer,t[i].fileName)}),wr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return qt("failed to post request",i,{url:r})}});Lw=qe(async(r,e,t)=>{try{return(await rc(r,e,t)).text}catch(s){return qt("failed to getText request",s,{url:r,query:e})}}),Tr=qe(async(r,e,t,s,n)=>{try{return(await rc(r,e,t,s,n)).body}catch(o){return qt("failed to get request",o,{url:r,query:e})}}),Nw=qe((r,e,t,s)=>rc(r,e,t,s)),Dw=qe(async r=>{let e=Et.default.head(r).timeout(Qr);wr(e);try{return await e}catch(t){return qt("failed to head request",t,{url:r})}}),sc=qe(async(r,e,t={},s=Qr)=>{let n=Et.default.put(r).send(e).timeout(s).set(t);wr(n);try{return(await n).body}catch(o){return qt("failed to put request",o,{url:r})}}),nc=qe(async r=>{ec.info("start to download",{url:r});let e=Et.default.get(r).timeout(Pw).buffer(!0).parse(Cw);wr(e);try{let t=await e;return ec.info("finished to download",{url:r}),t}catch(t){return qt("failed to download",t,{url:r})}}),oc=qe.isNetworkHealthy,ic=qe.didNetworkConnectivityTestFail});function mt(){let r;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?r=Lt.resolve(__dirname,"../../"):r=Lt.resolve(__dirname,""),r):process.cwd()}function ao(r,e){return Ge(r)?e||Lt.join(process.cwd(),r.replace(/^.*[\\/]/,"")):e||Lt.basename(r)}function ct(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Fw(){try{return jd.node}catch{return""}}async function lo(r,e,t=!0){let s=await He.promises.readdir(r,{withFileTypes:!0});await He.promises.mkdir(e,{recursive:t});for(let n of s){let o=Lt.join(r,n.name),i=Lt.join(e,n.name);n.isDirectory()?await lo(o,i):await He.promises.copyFile(o,i)}}async function be(r){try{return await He.promises.access(r),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Lt,mp,fp,He,Mw,vr,ze,hp,co,ac,tt,cc,lc=T(()=>{"use strict";Lt=E(require("path"));Ba();to();mp=E(require("p-retry")),fp=E(require("decompress")),He=require("fs"),Mw=3;vr=async r=>{let e=await Promise.resolve().then(()=>(Rt(),Ot));return(0,mp.default)(()=>e.download(r),{retries:Mw})},ze=async(r,e)=>{let t=await vr(r);return He.promises.writeFile(e,t.body)},hp=async(r,e)=>new Promise((t,s)=>{try{let n=(0,He.createWriteStream)(e);(0,He.createReadStream)(r).pipe(n),n.on("finish",()=>{n.close(()=>t())})}catch(n){s(n)}});co=async(r,e)=>{let t=ao(r,e);return Ge(r)?ze(r,t):hp(r,t)},ac=async r=>Ge(r)?vr(r):He.promises.readFile(r),tt=async(r,e)=>await(0,fp.default)(r,e),cc=r=>(0,He.statSync)(r).size/1e6});var Dt={};W(Dt,{APPIUM_SESSION_MESSAGE:()=>mc,CLI_MODE:()=>J,MOBILE_APP_SOURCE:()=>uo,gridMessages:()=>Zr,gridTypes:()=>ue,mobileWeb:()=>dc,runnerStatus:()=>uc,runnerTestStatus:()=>pe,sessionType:()=>Nt,socketEventTypes:()=>rt,stepResult:()=>Ks,test:()=>pc,testRunStatus:()=>zs,testStatus:()=>Ke,timeoutMessages:()=>$e});var $e,zs,uc,pe,Ke,Zr,dc,pc,rt,J,Nt,ue,Ks,uo,mc,ae=T(()=>{"use strict";$e={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},zs={COMPLETED:"completed",RUNNING:"running"},uc={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"},Zr={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},dc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},pc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},rt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},J={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},Nt={CODELESS:"codeless",CODEFUL:"codeful"},ue={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin"},Ks={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"},uo={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},mc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow"}});function Er(r){return r.files.length>0?Nt.CODEFUL:Nt.CODELESS}function Js(r,e){var t,s,n;return((t=r.testConfigNames)!=null&&t.length||(s=r.testConfigIds)!=null&&s.length||r.testPlan.length||r.testPlanIds.length)&&!r.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=r.browser)==null?void 0:n.toLowerCase()]}function Uw(){let{argv:r}=process;if(r.includes("--remoteRunId"))return{remoteRunId:r[r.indexOf("--remoteRunId")+1],projectId:r[r.indexOf("--project")+1],token:r[r.indexOf("--token")+1]}}var Xs,gp,Je,jw,Bw,$w,Ww,Gw,Vw,fc,yp=T(()=>{"use strict";ae();Xs=r=>{var e,t;return Boolean(((e=r.testPlan)==null?void 0:e.length)||((t=r.testPlanIds)==null?void 0:t.length))},gp=r=>Boolean(r.resultId&&r.source==="remote-run"),Je=(r,e)=>r.testStatus===Ke.QUARANTINE&&!gp(e)&&!e.runQuarantinedTests;jw=r=>Boolean(r.initCodimMode),Bw=r=>Boolean(r.loginMode),$w=r=>Boolean(r.tunnelOnlyMode),Ww=r=>Boolean(r.createPrefechedData),Gw=r=>Boolean(r.installLazyDepsMode),Vw=r=>Boolean(r.agentMode),fc=(r,e)=>{r.forEach((t,s)=>{e.has(t)&&(r[s]=`--${t}`)})}});function po(r){let e=hc.default.duration(r);return`${e.hours()}:${e.minutes()}:${e.seconds()}.${e.milliseconds()}`}function gc(r){return hc.default.duration(r).asSeconds()}var hc,bp=T(()=>{"use strict";hc=E(require("moment"))});var Ys,es,Qs,wp=T(()=>{"use strict";Ys=r=>!(!r||"fileName"in r),es=r=>{var e;return r&&"fileName"in r?(e=r.fileName)==null?void 0:e.endsWith(".app"):!1},Qs=r=>{var e,t;return((e=r.projectData)==null?void 0:e.type)==="ios"||((t=r.projectData)==null?void 0:t.type)==="android"}});var H={};W(H,{TESTIM_BROWSER_DIR:()=>Mt,TimeoutError:()=>X,buildBasicHeader:()=>ja,calcPercentile:()=>ho,copy:()=>hp,copyDir:()=>lo,delay:()=>se,doesPathExist:()=>be,download:()=>vr,downloadAndSave:()=>ze,extractElementId:()=>De,getArgsOnRemoteRunFailure:()=>Uw,getBrowserInfo:()=>en,getCdpAddressForHost:()=>Ir,getCliLocation:()=>mt,getDuration:()=>po,getDurationSec:()=>gc,getEnginesVersion:()=>Fw,getEnvironmentGitBranch:()=>Rr,getLocalFileSizeInMB:()=>cc,getPlanType:()=>fo,getRunConfigByBrowserName:()=>tn,getRunnerVersion:()=>ct,getSessionType:()=>Er,getSource:()=>co,getSourceAsBuffer:()=>ac,getSourcePath:()=>ao,getTestUrl:()=>at,getUniqBrowsers:()=>Js,groupTestsByRetries:()=>bc,guid:()=>z,hasTestPlanFlag:()=>Xs,isAgentMode:()=>Vw,isAppForVirtualIosDevice:()=>es,isAppFromDevice:()=>Ys,isCreatePrefetchedDataMode:()=>Ww,isInitCodimMode:()=>jw,isInstallLazyDepsMode:()=>Gw,isLoginMode:()=>Bw,isMobileProject:()=>Qs,isPromise:()=>io,isQuarantineAndNotRemoteRun:()=>Je,isRemoteRun:()=>gp,isTunnelOnlyMode:()=>$w,isURL:()=>Ge,promiseFromCallback:()=>pt,promiseMap:()=>de,promiseTimeout:()=>te,removePropertyFromObject:()=>mo,replaceArgsWithNoDashes:()=>fc,unzipFile:()=>tt});function en(r){return r=r.toLowerCase(),yc.find(e=>e.browserValue===r)}function tn(r,e,t){r=r.toLowerCase();let s=yc.find(o=>o.browserName.toLowerCase()===r||r.includes(o.synonyms))||yc[0],n=Zs.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=Zs.find(o=>o.sl.platform===e.platform):e.platformName&&(n=Zs.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=Zs.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=Zs.find(o=>o.bs.platform===t.platform))),Sr.merge(s,n)}function Rr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function mo(r,e,t){for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t(s,e)?delete r[s]:typeof r[s]=="object"&&mo(r[s],e,t))}function De(r){return r.ELEMENT||r[Hr]}function fo(r){r||(r={});let e=Date.now(),t=r.expireAt||r.expireAT;return r.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function bc(r=[]){return Sr.chain(r).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let s=Sr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=Sr.chain(s).last().cloneDeep().value();return n&&(n.retryTestResults=s,e.push(n)),e},[]).compact().value()}async function Ir(r,e){let t=await Promise.resolve().then(()=>(Rt(),Ot));try{return(await t.get(`http://${r}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Tp,Sr,vp,qw,Mt,Zs,yc,ho,U=T(()=>{"use strict";Tp=E(require("os")),Sr=E(require("lodash")),vp=E(require("path"));Bs();lc();yp();bp();Ba();Za();wp();qw=Tp.homedir(),Mt=vp.join(qw,".testim-browser-profile"),Zs=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{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"}}],yc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"94"},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",bs:{browser:"Edge",browser_version:"18"},sl:{browserName:"MicrosoftEdge",version:"18.17763"},browserValue:"edge",eol:!0},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"94"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Internet Explorer 11",bs:{browser:"IE",browser_version:"11"},sl:{browserName:"internet explorer",version:"11.0"},synonyms:["ie11"],browserValue:"ie11",eol:!0},{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"}];ho=(r,e)=>{if(r.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(r=[...r].sort((s,n)=>s-n),e<=0)return r[0];if(e>=100)return r.at(-1);let t=Math.ceil(r.length*(e/100))-1;return r[t]}});var wc={};W(wc,{$schema:()=>Hw,default:()=>Yw,definitions:()=>zw,properties:()=>Xw,required:()=>Jw,type:()=>Kw});var Hw,zw,Kw,Jw,Xw,Yw,Ep=T(()=>{Hw="http://json-schema.org/draft-07/schema#",zw={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}}}},Kw="object",Jw=["entries"],Xw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Yw={$schema:Hw,definitions:zw,type:Kw,required:Jw,properties:Xw}});async function Cp(){try{return await te(go.promises.readFile(To()).then(async r=>{let e=await Ap;return eT(e,r)}),3e4)}catch{return{}}}function eT(r,e){let t=e.slice(0,16),s=e.slice(16),n=Buffer.from(r),o=rs.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(s);return JSON.parse(Buffer.concat([i,o.final()]))}function ft(r,e,t=Qw,s=void 0){return async()=>{if(!Ip)return await r();let n=e;s&&(e+=JSON.stringify(s));let o=await tT(e);if(o)return rn.debug("cache hit:",{fnName:e}),o;if(rn.debug("cache miss:",{fnName:e}),!xp)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await r();return i&&await rT(e,i,t),i}}async function tT(r){let t=(await vo)[r];if(!t)return;let{value:s,expiry:n}=t;if(!(n<Date.now())&&s)return s}async function rT(r,e,t){if(Tc)throw rn.error("calling set after waitForSave is not allowed",{key:r,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let s=await vo;s[r]={value:e,expiry:Date.now()+t},Pp=new Promise(n=>{wo=n}),Zw(s)}catch{rn.error("failed updating cache")}}async function kp(){let r=await vo;Object.keys(r).forEach(e=>{delete r[e]})}function _p(r){Ip=r}function sT(r=!0){xp=r}async function Op(){try{return Tc=!0,await Pp}finally{Tc=!1}}function Lp(r){bo=r,vo=Cp()}var go,yo,rs,Sp,rn,bo,Rp,wo,Ip,xp,Tc,Pp,Ap,Qw,To,vo,Zw,Np,Dp,lI,Mp,Ht=T(()=>{"use strict";go=E(require("fs")),yo=E(require("path")),rs=E(require("crypto"));U();Sp=require("lodash");j();rn=I("local cache"),bo=yo.resolve(mt(),"testim-cache"),Ip=!0,xp=!0,Tc=!1,Pp=new Promise(r=>{wo=r}),Ap=new Promise(r=>{Rp=r}),Qw=1e3*60*60*3,To=()=>yo.resolve(yo.resolve(bo,"testim.cache"));vo=Cp(),Zw=(0,Sp.debounce)(async r=>{let e;try{let t=await Ap,s=rs.randomBytes(16),n=JSON.stringify(r),o=Buffer.from(t),i=rs.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),s),a=Buffer.concat([s,i.update(n),i.final()]);await be(bo)||await go.promises.mkdir(bo,{recursive:!0}),await go.promises.writeFile(To(),a)}catch(t){rn.error("failed saving cache",{err:t}),e=t}wo(e?{success:!1,error:e}:{success:!0})},200);Np=Rp,Dp=_p.bind(void 0,!1),lI=_p.bind(void 0,!0),Mp=()=>sT(!1)});function Eo(){return{cliLocation:mt(),userInfo:ss.userInfo(),platform:ss.platform(),release:ss.release()}}var ss,vc=T(()=>{"use strict";ss=E(require("os"));U()});function nT(r){try{return So.resolve(So.dirname(require.resolve(`${r}/package.json`)),require(`${r}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(r);throw e}}function zt(r){let e=nT(r);return require(e)}var So,sn=T(()=>{"use strict";So=E(require("path"))});async function Bp(r){return(await Up(`npm view ${r} version`)).stdout.trim()}function Sc(r){try{return zt(r)}catch{return!1}}function $p(r,e){return require(ns.join(r,`./node_modules/${e}/package.json`)).version}async function Io(r,e,t){function s(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=ns.join(r,"npm-shrinkwrap.json"),i=ns.join(r,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await be(o)&&(await Ec.promises.rename(o,i),a=!0)}catch{}return await Up(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:r}).catch(c=>{let u=s(c),d=n(c);throw u||d?(jp.info("Failed to install package due to insufficient write access",{...Eo(),package:e,path:u||r}),console.error(`
|
|
2
|
+
"use strict";var ow=Object.create;var zn=Object.defineProperty;var iw=Object.getOwnPropertyDescriptor;var aw=Object.getOwnPropertyNames;var cw=Object.getPrototypeOf,lw=Object.prototype.hasOwnProperty;var T=(r,e)=>()=>(r&&(e=r(r=0)),e);var W=(r,e)=>{for(var t in e)zn(r,t,{get:e[t],enumerable:!0})},Ld=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of aw(e))!lw.call(r,n)&&n!==t&&zn(r,n,{get:()=>e[n],enumerable:!(s=iw(e,n))||s.enumerable});return r};var E=(r,e,t)=>(t=r!=null?ow(cw(r)):{},Ld(e||!r||!r.__esModule?zn(t,"default",{value:r,enumerable:!0}):t,r)),ie=r=>Ld(zn({},"__esModule",{value:!0}),r);var _e={};W(_e,{log:()=>_,measure:()=>dw});function _(...r){if(!Fd)return;let e=Date.now();console.log(`${e-uw} ${e-Md} `,...r),Md=e}function dw(r,e){if(!Fd)return;let t=Date.now();try{r()}finally{console.log(e||r.name,"took",Date.now()-t)}}var Fd,uw,Md,Oe=T(()=>{"use strict";Fd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,uw=Date.now(),Md=Date.now()});var Fa,Hr,Ua,Bs=T(()=>{"use strict";Fa={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"},Hr="element-6066-11e4-a52e-4f735466cecf",Ua=79});function z(r=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let s=0;s<r;s++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function at(r,e,t,s,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${r}/#/project/${e}/branch/${n}/test/${t}`,s&&(o+=`?result-id=${s}`)),o}function ja(r,e){return`Basic ${Buffer.from(`${r}:${e}`).toString("base64")}`}function Ge(r){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(r)||t.test(r)}var Ba=T(()=>{"use strict"});var Wa,Ud,jd,to=T(()=>{Wa={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"},Ud={"@applitools/eyes-sdk-core":"13.11.31","@applitools/spec-driver-webdriverio":"1.4.29","@testim/coralogix-logger":"1.1.27-beta.1","abort-controller":"3.0.0",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",decompress:"4.2.1",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0",glob:"7.2.0","https-proxy-agent":"5.0.0","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.16.2",jsdom:"19.0.0",linkedom:"^0.14.25",jsonwebtoken:"9.0.0",lodash:"4.17.21","memory-fs":"0.5.0",moment:"2.29.4",ms:"2.1.2",npm:"8.19.2","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"5.0.0","rox-node":"4.9.18",semver:"7.3.2","serialize-error":"7.0.1","socket.io-client":"4.5.4","source-map-support":"0.5.19",superagent:"3.8.3","superagent-proxy":"3.0.0","test-exclude":"6.0.0",threads:"0.12.0","ua-parser-js":"0.7.33","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.6.0","winston-transport":"4.5.0",ws:"8.5.0",xml2js:"0.4.23",yaml:"1.10.0"},jd={node:">= 14.0.0"}});var $s,Bd,$d,ro,Wd,so,zr,Gd,he,Vd,qd,no,Le,Ga,UR,oo,Hd,jR,zd,BR,Kd,Jd,Kr,Yd,Xd,Qd,le=T(()=>{"use strict";$s=process.env.SERVICES_HOST||"https://services.testim.io",Bd="https://testimstatic.blob.core.windows.net",$d="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:$s,$s=process.env.SERVICES_HOST);ro=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Wd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),so=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),zr=process.env.EDITOR_URL,Gd=process.env.WEBSOCKET_HOST||`${$s}/ws`,he=$s,Vd=parseInt(process.env.LOGGER_CONSOLE||"0",10),qd=parseInt(process.env.LOGGER_DEBUG||"0",10),no=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),Le=parseInt(process.env.IS_ON_PREM||"0",10),Ga=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,UR=parseInt(process.env.DEBUG_MODE||"0",10),oo=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Hd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",jR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),zd=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),BR=process.env.APPIUM_VERSION||"1.10.1",Kd=process.env.GATEWAY_URL,Jd=process.env.EXTENSION_SERVICES_HOST||$s,Kr=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Bd,Yd=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:$d,Xd=Bd,Qd=$d});var Va={};W(Va,{CoralogixTransport:()=>Jr});var Ie,Zd,fw,gw,Jr,qa=T(()=>{"use strict";Ie=require("@testim/coralogix-logger"),Zd=E(require("winston-transport")),fw={silly:Ie.Severity.verbose,verbose:Ie.Severity.verbose,info:Ie.Severity.info,http:Ie.Severity.info,warn:Ie.Severity.warning,warning:Ie.Severity.warning,error:Ie.Severity.error,silent:Ie.Severity.verbose,critical:Ie.Severity.critical,crit:Ie.Severity.critical,debug:Ie.Severity.debug},gw=["err","error","reason","e"],Jr=class extends Zd.default{constructor(t){t=Object.assign({},Jr.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,s){let{category:n,level:o,message:i,meta:a={},...c}=t,u=Object.assign({},a,this.options.extraFields,c),d=new Ie.Log;d.severity=fw[o],d.text=i,d.category=n,u.className&&(d.className=u.className),u.methodName&&(d.methodName=u.methodName),u.threadId&&(d.threadId=u.threadId),delete u.className,delete u.methodName,delete u.threadId,delete u.category,delete u.level,delete u.message;let p=!1;a instanceof Error&&(p=!0,u.msg=a.message+a.stack,i&&(u.msg=`${i}
|
|
3
|
+
${u.msg}`));for(let m of gw)a[m]instanceof Error&&(u[m]={message:a[m].message,stack:a[m].stack,name:a[m].name,type:a[m].type,cause:a[m].cause,...a[m]});Object.keys(u).length>0&&(i&&!p&&(u.msg=i),d.text=u),this.logger.addLog(d),s(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Jr.options=t}}});var Xa={};W(Xa,{getLogger:()=>x,setExecutionId:()=>Ka,setProjectId:()=>Ja,setProxyUri:()=>Ya});function bw(){let r=[],e=()=>Promise.resolve();if(!Le){let{CoralogixTransport:t}=(qa(),ie(Va));t.configure(rp);let s=new t({category:"ROOT"});r.push(s),e=()=>s.waitForFlush()}return Vd&&r.push(new vt.transports.Console({format:vt.format.combine(vt.format.colorize(),vt.format.simple())})),[r,e]}function Ka(r){Ha=r}function Ja(r){sp=r}function Ya(r){if(Le||!r)return;let{CoralogixTransport:e}=(qa(),ie(Va));e.configure({...rp,proxyUri:r})}function ep(r){return{projectId:sp,time:new Date().toISOString(),...Ha&&!r&&{executionId:Ha}}}function x(r){return new za(Sw.child({category:r}))}var tp,vt,hw,yw,rp,ww,Tw,vw,Ew,Sw,Ha,sp,za,j=T(()=>{"use strict";tp=E(require("os")),vt=E(require("winston"));le();U();hw=tp.hostname(),yw=ct(),rp={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[ww,Tw]=bw(),vw=qd?"debug":"info",Ew={release:Boolean(!0),branch:"production"},Sw=vt.createLogger({levels:vt.config.syslog.levels,level:vw,transports:ww,defaultMeta:{name:"runner",hostname:hw,nodeVersion:process.version,runnerVersion:yw,...Ew}}),Ha=null,sp=null;za=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,s={}){let{executionId:n}=s;try{this._logger.log(e,Object.assign({meta:s,message:t},ep(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},ep(n)))}catch{}}}waitForFlush(){return Tw()}}});var np={};W(np,{AbortError:()=>Be,ArgError:()=>P,ClientError:()=>hr,GetBrowserError:()=>Vt,GridConcurrencyError:()=>gr,GridError:()=>ut,NoArgsError:()=>mr,NotImplementedError:()=>Xr,NpmPackageError:()=>dt,NpmPermissionsError:()=>br,PageNotAvailableError:()=>lt,PlaygroundCodeError:()=>yr,QuotaDepletedError:()=>Yr,SeleniumCrashError:()=>Gs,SeleniumError:()=>fr,StopRunOnError:()=>_t,TimeoutError:()=>Y,WebdriverCapabilitiesError:()=>Ws});var Qa,Be,mr,P,fr,_t,Vt,lt,Ws,Y,Yr,ut,gr,dt,Gs,hr,yr,br,Xr,q=T(()=>{"use strict";Qa=require("p-retry"),Be=class extends Error{constructor(t="aborted"){super(t);this.name="AbortError"}},mr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},fr=class extends Error{constructor(t){super(t.orgStatusMessage||t.message);this.name="SeleniumError",this.errorType=t.type}},_t=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},Vt=class extends Error{constructor(t,s){super(t);this.type=s}},lt=class extends Qa.AbortError{},Ws=class extends Qa.AbortError{},Y=class extends Error{},Yr=class extends Error{},ut=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},gr=class extends ut{constructor(){super(...arguments);this.name="GridConcurrencyError"}},dt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Gs=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},hr=class extends Error{},yr=class extends Error{},br=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Xr=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function io(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"&&typeof r.catch=="function"}function se(r){return new Promise(e=>{setTimeout(e,r)})}function te(r,e,t="Timeout Error"){so&&!op&&(op=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let s=new Y(t);return e=so?Number(so)||6e5:e,Promise.race([r,se(e).then(()=>{throw s})])}async function de(r,e,{concurrency:t}={}){if(t){ip||(ip=(await import("p-limit")).default);let s=ip(t);return await Promise.all(Array.from(r,(n,o)=>s(()=>e(n,o))))}return await Promise.all(Array.from(r,e))}function pt(r){return new Promise((e,t)=>{r((s,n)=>s?t(s):e(n))})}var op,ip,Za=T(()=>{"use strict";q();le();op=!1});var qs,ap,Rw,Vs,cp,Iw,xw,lp,up=T(()=>{"use strict";qs=E(require("lodash"));le();ap=require("dns");j();Za();Rw=x("http-request-counters"),Vs=!1,cp=async()=>{if(Le)return!0;let r=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await de(r,t=>ap.promises.lookup(t)));return e||(Vs=!0),e}catch{return Rw.error("network connectivity test failed"),Vs=!0,!1}},Iw=qs.throttle(cp,10*1e3),xw=60*1e3*15,lp=()=>{let r={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},xw)}function t(n,o=n.name){return async function(...i){e(r.call,o);try{let a=await n.call(null,...i);return e(r.success,o),a}catch(a){throw e(r.fail,o),Vs||Iw(),a}}}async function s(){if(Vs||!await cp())return!1;let n=qs.sum([...r.fail.values()]),o=qs.sum([...r.call.values()]);return n<o*.1}return s.counters=r,t.counters=r,t.isNetworkHealthy=s,t.didNetworkConnectivityTestFail=()=>Vs,t}});var Ot={};W(Ot,{deleteFullRes:()=>_w,deleteReq:()=>Hs,didNetworkConnectivityTestFail:()=>ic,download:()=>nc,get:()=>Tr,getFullRes:()=>Dw,getText:()=>Lw,head:()=>Nw,isNetworkHealthy:()=>oc,post:()=>St,postForm:()=>tc,postFullRes:()=>Ow,put:()=>sc});function Aw(){return global.caFileContent}function Cw(r,e){let t=[];r.on("data",s=>{t.push(s)}),r.on("end",()=>{e(null,Buffer.concat(t))})}function kw(){return!Et.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Et.default),global.proxyUri}function wr(r,e=!1){let t=Aw();t&&r.ca(t);let s=!e&&kw();s&&r.proxy(s)}async function dp(r,e={},t={},s=Qr){let n=Et.default.delete(r).send(e).timeout(s).set(t);return wr(n),await n}async function pp(r,e,t={},s=Qr,n=0){let o=Et.default.post(r).send(e).timeout(s).set(t);wr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=r,i.originalRequestTimeout=s,i.additionalSetHeaders=t,i}}async function rc(r,e,t={},s=Qr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Et.default.get(r).query(e||{}).timeout(s).set(t);return n&&i.buffer(!0),wr(i,o),await i}var Et,ec,qe,Qr,Pw,qt,Hs,_w,St,Ow,tc,Lw,Tr,Dw,Nw,sc,nc,oc,ic,Rt=T(()=>{"use strict";Et=E(require("superagent"));j();up();ec=x("http-request"),qe=lp(),Qr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,Pw=6e4;qt=(r,e,t)=>{throw ec.error(r,{...t,error:e}),e};Hs=qe(async(r,e,t,s)=>{try{let n=await dp(r,e,t,s);return n.type==="text/plain"?n.text:n.body}catch(n){return qt("failed to delete request",n,{url:r})}});_w=qe(dp),St=qe(async({url:r,body:e,headers:t,timeout:s,retry:n})=>{try{let o=await pp(r,e,t,s,n);return o.type==="text/plain"?o.text:o.body}catch(o){return qt("failed to post request",o,{url:r})}});Ow=qe(pp),tc=qe(async(r,e,t,s={},n=Qr)=>{let o=Et.default.post(r).type("form").timeout(n).set(s);o.field(e),Object.keys(t).forEach(i=>{o.attach(i,t[i].buffer,t[i].fileName)}),wr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return qt("failed to post request",i,{url:r})}});Lw=qe(async(r,e,t)=>{try{return(await rc(r,e,t)).text}catch(s){return qt("failed to getText request",s,{url:r,query:e})}}),Tr=qe(async(r,e,t,s,n)=>{try{return(await rc(r,e,t,s,n)).body}catch(o){return qt("failed to get request",o,{url:r,query:e})}}),Dw=qe((r,e,t,s)=>rc(r,e,t,s)),Nw=qe(async r=>{let e=Et.default.head(r).timeout(Qr);wr(e);try{return await e}catch(t){return qt("failed to head request",t,{url:r})}}),sc=qe(async(r,e,t={},s=Qr)=>{let n=Et.default.put(r).send(e).timeout(s).set(t);wr(n);try{return(await n).body}catch(o){return qt("failed to put request",o,{url:r})}}),nc=qe(async r=>{ec.info("start to download",{url:r});let e=Et.default.get(r).timeout(Pw).buffer(!0).parse(Cw);wr(e);try{let t=await e;return ec.info("finished to download",{url:r}),t}catch(t){return qt("failed to download",t,{url:r})}}),oc=qe.isNetworkHealthy,ic=qe.didNetworkConnectivityTestFail});function mt(){let r;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?r=Lt.resolve(__dirname,"../../"):r=Lt.resolve(__dirname,""),r):process.cwd()}function ao(r,e){return Ge(r)?e||Lt.join(process.cwd(),r.replace(/^.*[\\/]/,"")):e||Lt.basename(r)}function ct(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Fw(){try{return jd.node}catch{return""}}async function lo(r,e,t=!0){let s=await He.promises.readdir(r,{withFileTypes:!0});await He.promises.mkdir(e,{recursive:t});for(let n of s){let o=Lt.join(r,n.name),i=Lt.join(e,n.name);n.isDirectory()?await lo(o,i):await He.promises.copyFile(o,i)}}async function be(r){try{return await He.promises.access(r),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Lt,mp,fp,He,Mw,vr,ze,gp,co,ac,tt,cc,lc=T(()=>{"use strict";Lt=E(require("path"));Ba();to();mp=E(require("p-retry")),fp=E(require("decompress")),He=require("fs"),Mw=3;vr=async r=>{let e=await Promise.resolve().then(()=>(Rt(),Ot));return(0,mp.default)(()=>e.download(r),{retries:Mw,factor:1})},ze=async(r,e)=>{let t=await vr(r);return He.promises.writeFile(e,t.body)},gp=async(r,e)=>new Promise((t,s)=>{try{let n=(0,He.createWriteStream)(e);(0,He.createReadStream)(r).pipe(n),n.on("finish",()=>{n.close(()=>t())})}catch(n){s(n)}});co=async(r,e)=>{let t=ao(r,e);return Ge(r)?ze(r,t):gp(r,t)},ac=async r=>Ge(r)?vr(r):He.promises.readFile(r),tt=async(r,e)=>await(0,fp.default)(r,e),cc=r=>(0,He.statSync)(r).size/1e6});var Nt={};W(Nt,{APPIUM_SESSION_MESSAGE:()=>mc,CLI_MODE:()=>J,MOBILE_APP_SOURCE:()=>uo,gridMessages:()=>Zr,gridTypes:()=>ue,mobileWeb:()=>dc,runnerStatus:()=>uc,runnerTestStatus:()=>pe,sessionType:()=>Dt,socketEventTypes:()=>rt,stepResult:()=>Ks,test:()=>pc,testRunStatus:()=>zs,testStatus:()=>Ke,timeoutMessages:()=>$e});var $e,zs,uc,pe,Ke,Zr,dc,pc,rt,J,Dt,ue,Ks,uo,mc,ae=T(()=>{"use strict";$e={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},zs={COMPLETED:"completed",RUNNING:"running"},uc={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"},Zr={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},dc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},pc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},rt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},J={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},Dt={CODELESS:"codeless",CODEFUL:"codeful"},ue={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin"},Ks={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"},uo={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},mc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow"}});function Er(r){return r.files.length>0?Dt.CODEFUL:Dt.CODELESS}function Js(r,e){var t,s,n;return((t=r.testConfigNames)!=null&&t.length||(s=r.testConfigIds)!=null&&s.length||r.testPlan.length||r.testPlanIds.length)&&!r.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=r.browser)==null?void 0:n.toLowerCase()]}function Uw(){let{argv:r}=process;if(r.includes("--remoteRunId"))return{remoteRunId:r[r.indexOf("--remoteRunId")+1],projectId:r[r.indexOf("--project")+1],token:r[r.indexOf("--token")+1]}}var Ys,hp,Je,jw,Bw,$w,Ww,Gw,Vw,fc,yp=T(()=>{"use strict";ae();Ys=r=>{var e,t;return Boolean(((e=r.testPlan)==null?void 0:e.length)||((t=r.testPlanIds)==null?void 0:t.length))},hp=r=>Boolean(r.resultId&&r.source==="remote-run"),Je=(r,e)=>r.testStatus===Ke.QUARANTINE&&!hp(e)&&!e.runQuarantinedTests;jw=r=>Boolean(r.initCodimMode),Bw=r=>Boolean(r.loginMode),$w=r=>Boolean(r.tunnelOnlyMode),Ww=r=>Boolean(r.createPrefechedData),Gw=r=>Boolean(r.installLazyDepsMode),Vw=r=>Boolean(r.agentMode),fc=(r,e)=>{r.forEach((t,s)=>{e.has(t)&&(r[s]=`--${t}`)})}});function po(r){let e=gc.default.duration(r);return`${e.hours()}:${e.minutes()}:${e.seconds()}.${e.milliseconds()}`}function hc(r){return gc.default.duration(r).asSeconds()}var gc,bp=T(()=>{"use strict";gc=E(require("moment"))});var Xs,es,Qs,wp=T(()=>{"use strict";Xs=r=>!(!r||"fileName"in r),es=r=>{var e;return r&&"fileName"in r?(e=r.fileName)==null?void 0:e.endsWith(".app"):!1},Qs=r=>{var e,t;return((e=r.projectData)==null?void 0:e.type)==="ios"||((t=r.projectData)==null?void 0:t.type)==="android"}});var H={};W(H,{TESTIM_BROWSER_DIR:()=>Mt,TimeoutError:()=>Y,buildBasicHeader:()=>ja,calcPercentile:()=>go,copy:()=>gp,copyDir:()=>lo,delay:()=>se,doesPathExist:()=>be,download:()=>vr,downloadAndSave:()=>ze,extractElementId:()=>Ne,getArgsOnRemoteRunFailure:()=>Uw,getBrowserInfo:()=>en,getCdpAddressForHost:()=>Ir,getCliLocation:()=>mt,getDuration:()=>po,getDurationSec:()=>hc,getEnginesVersion:()=>Fw,getEnvironmentGitBranch:()=>Rr,getLocalFileSizeInMB:()=>cc,getPlanType:()=>fo,getRunConfigByBrowserName:()=>tn,getRunnerVersion:()=>ct,getSessionType:()=>Er,getSource:()=>co,getSourceAsBuffer:()=>ac,getSourcePath:()=>ao,getTestUrl:()=>at,getUniqBrowsers:()=>Js,groupTestsByRetries:()=>bc,guid:()=>z,hasTestPlanFlag:()=>Ys,isAgentMode:()=>Vw,isAppForVirtualIosDevice:()=>es,isAppFromDevice:()=>Xs,isCreatePrefetchedDataMode:()=>Ww,isInitCodimMode:()=>jw,isInstallLazyDepsMode:()=>Gw,isLoginMode:()=>Bw,isMobileProject:()=>Qs,isPromise:()=>io,isQuarantineAndNotRemoteRun:()=>Je,isRemoteRun:()=>hp,isTunnelOnlyMode:()=>$w,isURL:()=>Ge,promiseFromCallback:()=>pt,promiseMap:()=>de,promiseTimeout:()=>te,removePropertyFromObject:()=>mo,replaceArgsWithNoDashes:()=>fc,unzipFile:()=>tt});function en(r){return r=r.toLowerCase(),yc.find(e=>e.browserValue===r)}function tn(r,e,t){r=r.toLowerCase();let s=yc.find(o=>o.browserName.toLowerCase()===r||r.includes(o.synonyms))||yc[0],n=Zs.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=Zs.find(o=>o.sl.platform===e.platform):e.platformName&&(n=Zs.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=Zs.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=Zs.find(o=>o.bs.platform===t.platform))),Sr.merge(s,n)}function Rr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function mo(r,e,t){for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t(s,e)?delete r[s]:typeof r[s]=="object"&&mo(r[s],e,t))}function Ne(r){return r.ELEMENT||r[Hr]}function fo(r){r||(r={});let e=Date.now(),t=r.expireAt||r.expireAT;return r.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function bc(r=[]){return Sr.chain(r).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let s=Sr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=Sr.chain(s).last().cloneDeep().value();return n&&(n.retryTestResults=s,e.push(n)),e},[]).compact().value()}async function Ir(r,e){let t=await Promise.resolve().then(()=>(Rt(),Ot));try{return(await t.get(`http://${r}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var Tp,Sr,vp,qw,Mt,Zs,yc,go,U=T(()=>{"use strict";Tp=E(require("os")),Sr=E(require("lodash")),vp=E(require("path"));Bs();lc();yp();bp();Ba();Za();wp();qw=Tp.homedir(),Mt=vp.join(qw,".testim-browser-profile"),Zs=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{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"}}],yc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"94"},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",bs:{browser:"Edge",browser_version:"18"},sl:{browserName:"MicrosoftEdge",version:"18.17763"},browserValue:"edge",eol:!0},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"94"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Internet Explorer 11",bs:{browser:"IE",browser_version:"11"},sl:{browserName:"internet explorer",version:"11.0"},synonyms:["ie11"],browserValue:"ie11",eol:!0},{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"}];go=(r,e)=>{if(r.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(r=[...r].sort((s,n)=>s-n),e<=0)return r[0];if(e>=100)return r.at(-1);let t=Math.ceil(r.length*(e/100))-1;return r[t]}});var wc={};W(wc,{$schema:()=>Hw,default:()=>Xw,definitions:()=>zw,properties:()=>Yw,required:()=>Jw,type:()=>Kw});var Hw,zw,Kw,Jw,Yw,Xw,Ep=T(()=>{Hw="http://json-schema.org/draft-07/schema#",zw={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}}}},Kw="object",Jw=["entries"],Yw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Xw={$schema:Hw,definitions:zw,type:Kw,required:Jw,properties:Yw}});async function Cp(){try{return await te(ho.promises.readFile(To()).then(async r=>{let e=await Ap;return eT(e,r)}),3e4)}catch{return{}}}function eT(r,e){let t=e.slice(0,16),s=e.slice(16),n=Buffer.from(r),o=rs.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(s);return JSON.parse(Buffer.concat([i,o.final()]))}function ft(r,e,t=Qw,s=void 0){return async()=>{if(!Ip)return await r();let n=e;s&&(e+=JSON.stringify(s));let o=await tT(e);if(o)return rn.debug("cache hit:",{fnName:e}),o;if(rn.debug("cache miss:",{fnName:e}),!xp)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await r();return i&&await rT(e,i,t),i}}async function tT(r){let t=(await vo)[r];if(!t)return;let{value:s,expiry:n}=t;if(!(n<Date.now())&&s)return s}async function rT(r,e,t){if(Tc)throw rn.error("calling set after waitForSave is not allowed",{key:r,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let s=await vo;s[r]={value:e,expiry:Date.now()+t},Pp=new Promise(n=>{wo=n}),Zw(s)}catch{rn.error("failed updating cache")}}async function kp(){let r=await vo;Object.keys(r).forEach(e=>{delete r[e]})}function _p(r){Ip=r}function sT(r=!0){xp=r}async function Op(){try{return Tc=!0,await Pp}finally{Tc=!1}}function Lp(r){bo=r,vo=Cp()}var ho,yo,rs,Sp,rn,bo,Rp,wo,Ip,xp,Tc,Pp,Ap,Qw,To,vo,Zw,Dp,Np,lI,Mp,Ht=T(()=>{"use strict";ho=E(require("fs")),yo=E(require("path")),rs=E(require("crypto"));U();Sp=require("lodash");j();rn=x("local cache"),bo=yo.resolve(mt(),"testim-cache"),Ip=!0,xp=!0,Tc=!1,Pp=new Promise(r=>{wo=r}),Ap=new Promise(r=>{Rp=r}),Qw=1e3*60*60*3,To=()=>yo.resolve(yo.resolve(bo,"testim.cache"));vo=Cp(),Zw=(0,Sp.debounce)(async r=>{let e;try{let t=await Ap,s=rs.randomBytes(16),n=JSON.stringify(r),o=Buffer.from(t),i=rs.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),s),a=Buffer.concat([s,i.update(n),i.final()]);await be(bo)||await ho.promises.mkdir(bo,{recursive:!0}),await ho.promises.writeFile(To(),a)}catch(t){rn.error("failed saving cache",{err:t}),e=t}wo(e?{success:!1,error:e}:{success:!0})},200);Dp=Rp,Np=_p.bind(void 0,!1),lI=_p.bind(void 0,!0),Mp=()=>sT(!1)});function Eo(){return{cliLocation:mt(),userInfo:ss.userInfo(),platform:ss.platform(),release:ss.release()}}var ss,vc=T(()=>{"use strict";ss=E(require("os"));U()});function nT(r){try{return So.resolve(So.dirname(require.resolve(`${r}/package.json`)),require(`${r}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(r);throw e}}function zt(r){let e=nT(r);return require(e)}var So,sn=T(()=>{"use strict";So=E(require("path"))});async function Bp(r){return(await Up(`npm view ${r} version`)).stdout.trim()}function Sc(r){try{return zt(r)}catch{return!1}}function $p(r,e){return require(ns.join(r,`./node_modules/${e}/package.json`)).version}async function Io(r,e,t){function s(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=ns.join(r,"npm-shrinkwrap.json"),i=ns.join(r,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await be(o)&&(await Ec.promises.rename(o,i),a=!0)}catch{}return await Up(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:r}).catch(c=>{let u=s(c),d=n(c);throw u||d?(jp.info("Failed to install package due to insufficient write access",{...Eo(),package:e,path:u||r}),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 ${u||r}
|
|
8
8
|
|
|
9
|
-
`),new br(u||r)):c})}finally{if(a)try{await Ec.promises.rename(i,o)}catch{}}}function Wp(r,e,t,s){return new Promise((n,o)=>{let i=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",u="",d="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),p=(0,Ro.spawn)("node",[oT,"i","--prefix",r,...d,...e,...i],a);p.stderr.pipe(process.stderr),p.stdout.pipe(process.stdout),p.stdout.on("data",m=>{c+=m}),p.stderr.on("data",m=>{u+=m}),p.on("close",m=>{var
|
|
10
|
-
stdout: ${c} stderr: ${u}`}jp.debug(`Npm Install closed with exit code ${m}`,{message:f}),o(new dt(f))}else n(c)}),setTimeout(()=>{try{p.kill()}finally{o(new
|
|
9
|
+
`),new br(u||r)):c})}finally{if(a)try{await Ec.promises.rename(i,o)}catch{}}}function Wp(r,e,t,s){return new Promise((n,o)=>{let i=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",u="",d="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),p=(0,Ro.spawn)("node",[oT,"i","--prefix",r,...d,...e,...i],a);p.stderr.pipe(process.stderr),p.stdout.pipe(process.stdout),p.stdout.on("data",m=>{c+=m}),p.stderr.on("data",m=>{u+=m}),p.on("close",m=>{var g;if(m){let f;try{let h=(g=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(u))==null?void 0:g[1];f=`404 Not Found - GET https://registry.npmjs.org/${h==null?void 0:h.split("@")[0]} - Not found`}catch{f=`Npm Install closed with exit code ${m}
|
|
10
|
+
stdout: ${c} stderr: ${u}`}jp.debug(`Npm Install closed with exit code ${m}`,{message:f}),o(new dt(f))}else n(c)}),setTimeout(()=>{try{p.kill()}finally{o(new Y)}},s)})}var Ec,ns,Fp,Ro,Up,jp,oT,nn=T(()=>{"use strict";Ec=E(require("fs")),ns=E(require("path"));U();Fp=require("util"),Ro=require("child_process");j();vc();sn();q();Up=(0,Fp.promisify)(Ro.exec),jp=x("cli-service");oT=ns.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var zp={};W(zp,{install:()=>aT,isReady:()=>lT,start:()=>cT});var Gp,Vp,qp,Hp,Rc,iT,aT,cT,lT,Kp=T(()=>{"use strict";Gp=E(require("fkill")),Vp=E(require("p-retry"));nn();Rt();U();sn();qp="chromedriver",Hp=9515,Rc=`http://localhost:${Hp}/wd/hub`,iT=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],aT=async()=>{await Io(mt(),`${qp} --detect_chromedriver_version`)},cT=async()=>{process.env.NODE_OPTIONS="",await(0,Gp.default)(`:${Hp}`,{silent:!0}),await zt(qp).start(iT,!0)},lT=async({chromeBinaryLocation:r})=>{await(0,Vp.default)(async()=>{var n;let e=await Tr(`${Rc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...r&&{binary:r}},s=await St({url:`${Rc}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!s||s.status!==0||!s.sessionId)throw new Error("create session failed");await Hs(`${Rc}/session/${s.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var on={};W(on,{getSessionPlayerFolder:()=>Ac,prepareChromeDriver:()=>Pr,prepareCustomExtension:()=>xc,prepareExtension:()=>Pc,preparePlayer:()=>Ar});async function xc(r,e=!1){if(!r)return;if(Ge(r)){let n=os.join(process.cwd(),r.replace(/^.*[\\/]/,""));if(await uT(r)>Ic&&!e)throw new P(Jp);return await ze(r,n),n}let t=os.resolve(r);if(!Xp.existsSync(t))throw new P(`Failed to find custom extension in location: ${t}`);if(cc(t)>Ic&&!e)throw new P(Jp);return t}async function uT(r){let e=(Rt(),ie(Ot));try{let s=(await e.head(r)).headers["content-length"];return(s?parseInt(s,10):0)/1e6}catch(t){throw Po.warn("failed to download custom extension",{err:t}),new P(`Failed to download custom extension from location: ${r}`)}}function Pc(r){Po.info("prepare extension",{locations:r});let e=r.map(t=>({location:t,path:ao(t)}));return ft(()=>de(e,({location:t,path:s})=>co(t,s)),"prepareExtension",Zp,e)()}async function Pr(r={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=await Promise.resolve().then(()=>(Kp(),zp));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||(Po.error(a,{...r,...Eo(),error:(0,Qp.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 dT(){let r=`${Kr}/extension/sessionPlayer_LATEST_RELEASE`;return(await vr(r)).body.toString("utf8")}async function pT(r,e){if(!Ge(r)||Ge(r)&&e||Le)return r;let t=await dT();return`${r}-${t}`}function Ac(){let r=mt();return os.resolve(r,"testim-bin")}function mT(){let r=Ac();return os.resolve(r,"sessionPlayer.zip")}async function em(r,e,t=!1){try{return await co(r,e),await tt(e,Ac())}catch(s){if(t)throw s;return await em(r,e,!0)}}async function Ar(r,e){Po.info("prepare player",{location:r,canary:e});let t=mT();return ft(async()=>{let s=await pT(r,e);return await em(s,t),{}},"preparePlayer",Zp,[r,e,t])()}var Xp,Yp,os,Qp,Po,Zp,Ic,Jp,is=T(()=>{"use strict";Xp=E(require("ms")),Yp=E(require("fs")),os=E(require("path"));le();Ht();Qp=require("serialize-error");j();vc();q();U();Po=I("prepare runner and testim start"),Zp=(0,Xp.default)("0.5 day"),Ic=16,Jp=`The size of the custom extension is more than ${Ic}MB`});function fT(){let r=an.type().toLowerCase();return r==="darwin"?an.arch()==="arm"?"mac_arm":"mac":r==="windows_nt"?an.arch()==="x64"?"win64":"win32":"linux"}async function Co(){let r=fT(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(r in t))throw new P(`Unsupported platform: ${r}`);let s=parseInt(cn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:s,win64:s},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[r]}/${cn}/${n[r]}.zip`,a=Ao.join(Cc,n[r]),c=`${a}.zip`,u=Ao.join(a,o[r]);if(await be(u))return u;if(!await be(c)){let p=(0,kc.default)("Downloading Chromium").start();try{await tm.promises.mkdir(Cc),await ze(i,c)}catch(m){let h=`Failed to download Chromium: ${m.message}`;throw p.fail(h),new Error(h)}p.succeed()}let d=(0,kc.default)("Extracting Chromium").start();try{await tt(c,Cc)}catch(p){let m=`Failed to extract Chromium: ${p.message}`;throw d.fail(m),new Error(m)}return d.succeed(),u}var tm,an,Ao,kc,cn,Cc,_c=T(()=>{"use strict";tm=E(require("fs")),an=E(require("os")),Ao=E(require("path")),kc=E(require("ora"));q();U();cn="1000968",Cc=Ao.join(Mt,`chrome-${cn}`)});async function sm(r,e){return _o=r,Dc=e,await Oc()}function nm(r,e,t){st=r.token,_o=e,Dc=t,un=Mc(st),ko=r.refreshToken,Lc=r.ngrokToken,Nc=r.isNgrokWhitelisted}function hT(r=_o,e=Dc){return ft(()=>(ln.info("request to get cli token from server"),St({url:`${ge}/auth/token`,body:{projectId:r,token:e}})),"getTokenV3",rm*10,{projectId:r,token:e})()}async function gT(){return ln.info("request to refresh JWT cli token from server"),st=(await St({url:`${ge}/auth/refreshToken`,body:{token:st,refreshToken:ko}})).token,un=Mc(st),st}async function Oc(){try{let r=await hT();return ln.info("successfully get cli token from server"),st=r.token,un=Mc(st),ko=r.refreshToken,Lc=r.ngrokToken,Nc=r.isNgrokWhitelisted,st}catch(r){throw r.message.includes("Unauthorized")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(ln.error(`While trying to retrieve CLI token. caught error: ${r}`,{projectId:_o}),new P(`While trying to retrieve CLI token, caught error: ${r}`))}}function Mc(r){return require("jsonwebtoken").decode(r).exp*1e3}async function Kt(){if(!un)return Oc();if(un<Date.now()+4*rm)try{return await gT()}catch(r){return ln.error("failed to refresh token, executing fallback",r),Oc()}return st}function Oo(){return ko}function Ft(){return st?{uid:require("jsonwebtoken").decode(st).id,ngrokToken:Lc,isNgrokWhitelisted:Nc}:{}}var ln,st,un,ko,Lc,Nc,_o,Dc,rm,It=T(()=>{"use strict";le();Rt();Ht();q();j();ln=I("testim-custom-token"),_o=null,Dc=null,rm=5*60*1e3});var om={};W(om,{isCi:()=>as});var as,Lo=T(()=>{"use strict";as=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var ve={};W(ve,{addTestRetry:()=>il,clearTestResult:()=>sl,deleteCloudflareTunnel:()=>ul,fetchLambdatestConfig:()=>el,forceUpdateCloudflareTunnelRoutes:()=>ll,getAllGrids:()=>Zc,getAppDetails:()=>qc,getApplitoolsIntegrationData:()=>al,getCloudflareTunnel:()=>cl,getEditorUrl:()=>ET,getGridById:()=>Mo,getGridByName:()=>Yc,getHybridGridProvider:()=>Xc,getLabFeaturesByProjectId:()=>tl,getMobileDevicesFromGrid:()=>pl,getRealData:()=>mn,getS3Artifact:()=>pn,getSuiteTestList:()=>Vc,getTestPlan:()=>vT,getTestPlanTestList:()=>Gc,getTestResults:()=>Cr,getUsageForCurrentBillingPeriod:()=>Hc,initializeUserWithAuth:()=>Qc,isTestResultCompleted:()=>zc,keepAliveGrid:()=>Kc,loadSfdcCredential:()=>Uc,loadTest:()=>jc,releaseGridSlot:()=>Jc,reportExecutionFinished:()=>Do,reportExecutionStarted:()=>Wc,saveRemoteStep:()=>nl,saveTestPlanResult:()=>Bc,updateExecutionTests:()=>$c,updateRemoteRunFailure:()=>dl,updateTestDataArtifact:()=>Fo,updateTestResult:()=>rl,updateTestStatus:()=>cs,uploadRunDataArtifact:()=>ol});async function dn(){let r=await Kt();if(!r)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${r}`}}async function nt({url:r,body:e,headers:t={},timeout:s,retry:n}){let o=await dn(),i=Object.assign({},t,o);return St({url:`${ge}${r||""}`,body:e,headers:i,timeout:s,retry:n})}async function wT(r,e,t,s={},n=void 0){let o=await dn(),i=Object.assign({},s,o);return await tc(`${ge}${r||""}`,e,t,i,n)}async function No(r,e){let t=await dn();return await sc(`${ge}${r||""}`,e,t)}async function TT(r,e){let t=await dn();return await Hs(`${ge}${r||""}`,e,t)}async function xe(r,e,t,s){let n=await dn();return await Tr(`${ge}${r||""}`,e||void 0,n,s,t)}function pn(r,e){return(0,oe.default)(()=>xe(`/storage${r}`,null,{isBinary:!0},e),{retries:ne})}async function vT(r,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,oe.default)(()=>xe("/testPlan",{projectId:r,name:e.join(",")}),{retries:ne})).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 Uc({branch:r,projectId:e}){let t=await(0,oe.default)(()=>xe(`/branch/branchData/${r}`,{projectId:e}),{retries:ne});return t==null?void 0:t.sfdcCredential}function jc({testId:r,branch:e,projectId:t,skipSharedSteps:s=!1,useBranchMap:n=!0}){return(0,oe.default)(()=>xe(`/test/${r}`,{projectId:t,branch:e,skipSharedSteps:s,useBranchMap:n}),{retries:ne})}function Bc(r,e,t){return(0,oe.default)(()=>nt({url:"/testPlan/result",body:{projectId:r,testPlanId:e,result:t}}),{retries:ne})}function cs(r,e,t,s,n,o,i=ne){return(0,oe.default)(()=>No("/result/run/test",{runId:e,testId:t,resultId:s,status:n,projectId:r,runnerVersion:yT,...o}),{retries:i})}function $c(r,e,t,s,n,o,i,a){return(0,oe.default)(()=>No("/result/run/tests",{runId:r,runnerStatuses:e,status:t,reason:s,success:n,startTime:o,endTime:i,projectId:a}),{retries:ne})}async function Wc({executionId:r,projectId:e,labels:t,startTime:s,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:c,isLocalRun:u,intersections:d}){let{isCi:p}=await Promise.resolve().then(()=>(Lo(),om));return nt({timeout:9e4,url:"/result/run",body:{runId:r,projectId:e,labels:t,startTime:s,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:p,localRunUserId:c,isLocalRun:u}},retry:3})}function Do(r,e,t,s,n={},o=void 0,i=void 0){let a=Date.now();return(0,oe.default)(()=>No("/result/run",{runId:e,projectId:t,endTime:a,status:r,success:s,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ne})}async function Gc(r,e,t,s,n){return(0,oe.default)(()=>nt({url:"/testPlan/list",body:{projectId:r,names:e,planIds:t,branch:s,intersections:n},timeout:12e4}),{retries:ne})}function Vc({projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:u,intersections:d}){return(0,oe.default)(()=>nt({url:"/suite/v2/list",body:{projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:u,intersections:d}}),{retries:ne,factor:1})}async function qc({appId:r,projectId:e}){try{return await(0,oe.default)(()=>xe(`/mobile-app/app/${r}?projectId=${e}`),{retries:ne,factor:1})}catch(t){jt.error("failed getting application details",{appId:r,error:t});return}}async function Hc(r){try{return await(0,oe.default)(()=>xe(`/plan/project/${r}/usage-current-billing-period`),{retries:ne})}catch(e){jt.error("failed getting usage for current billing period",{projectId:r,error:e});return}}function zc(r,e,t){return(0,oe.default)(()=>xe(`/result/${r}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ne})}function Cr(r,e,t,s){return(0,oe.default)(()=>xe(`/test/v2/${r}/result/${e}`,{projectId:t,branch:s}),{retries:ne,factor:1})}function Kc(r,e){return nt({url:`/grid/keep-alive?reqId=${z()}`,body:{projectId:r,slots:e},timeout:1e4})}function Jc(r,e,t,s,n){return nt({url:`/grid/release?reqId=${z()}`,body:{companyId:r,projectId:e,slotId:t,gridId:s,browser:n}})}function Xc(r){return nt({url:"/grid/hybrid/provider",body:r})}function Yc(r,e,t,s,n){return(0,oe.default)(()=>xe("/grid/name",{companyId:r,projectId:e,name:t,browser:s,executionId:n,reqId:z()}),{retries:ne})}function Mo(r,e,t,s,n){return(0,oe.default)(()=>xe(`/grid/${t}`,{companyId:r,projectId:e,browser:s,executionId:n,reqId:z()}),{retries:ne})}async function Qc({projectId:r,token:e,branchName:t,lightweightMode:s,localGrid:n}){var o,i;try{return await(0,oe.default)(()=>St({url:`${ge}/executions/initialize`,body:{projectId:r,token:e,branchName:t||"master",lightweightMode:s,localGrid:n}}),{retries:ne})}catch(a){throw jt.error("error initializing info from server",a),(o=a==null?void 0:a.message)!=null&&o.includes("Bad Request")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(i=a==null?void 0:a.code)!=null&&i.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):a}}async function ET(){if(zr)return{editorUrl:zr};try{return await(0,oe.default)(()=>xe("/system-info/editor-url"),{retries:ne,onFailedAttempt:r=>{if(r.attemptNumber>=ne)throw r}})}catch{return jt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function Zc(r){return(0,oe.default)(()=>xe("/grid",{companyId:r}),{retries:ne})}function mn(r,e,t){return(0,oe.default)(()=>xe(`/real-data/${e}?${t}&projectId=${r}`),{retries:ne})}function rl(r,e,t,s,n){return(0,oe.default)(()=>nt({url:"/result/test",body:{projectId:r,resultId:e,testId:t,testResult:s,remoteRunId:n}}),{retries:ne})}function sl(r,e,t,s){return(0,oe.default)(()=>nt({url:"/result/test/clear",body:{projectId:r,resultId:e,testId:t,testResult:s}}),{retries:ne})}function nl(r,e,t,s){return(0,oe.default)(()=>nt({url:"/remoteStep",body:{projectId:r,resultId:e,stepId:t,remoteStep:s}}),{retries:ne})}function ST(r){return r.startsWith("/")?r:`/${r}`}function RT(r,e,t){let s=ST(r);return t&&(s=`/${t}${s}`),e&&(s=`/${e}${s}`),s}async function am(r,e,t,s,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${z()}${i||""}`,c=`${e}/${t}/${a}`,u=RT(c,"test-result-artifacts",r),d=Buffer.from(im.gzip(s,{level:3})),p={file:{fileName:a,buffer:d}};return await(0,oe.default)(()=>wT(`/storage${u}`,{},p,{"X-Asset-Encoding":"gzip"}),{retries:ne,factor:1}),u}function il({projectId:r,runId:e,testId:t,newResultId:s,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,oe.default)(()=>nt({url:"/result/test/retry",body:{projectId:r,newResultId:s,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ne})}async function al(r){try{return await xe(`/integration/applitools/v3/connected?projectId=${r}`)}catch(e){return jt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function cl(r,e){try{return await No("/tunnel",{companyId:r,routes:e})}catch(t){return jt.warn("could'nt get tunnel.",{err:t}),{}}}async function ll(r,e){try{return await nt({url:`/tunnel/${e}`,body:{companyId:r}})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}async function ul(r,e){try{return await TT(`/tunnel/${e}`,{companyId:r})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}function dl(r){return St({url:`${ge}/result/remoteRunFailure`,body:r})}async function pl({projectId:r,projectType:e,gridId:t,companyId:s,selectors:n}){let o=`${bT}/mobileDevices/${t}/${s}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,oe.default)(()=>xe(o,{projectId:r}),{retries:ne})}catch(i){return jt.warn("could'nt get devices from headspin grid.",{err:i}),null}}var Jt,im,oe,Fc,yT,jt,ne,bT,el,tl,ol,Fo,Te=T(()=>{"use strict";Jt=E(require("lodash")),im=E(require("pako"));U();le();ae();Rt();It();oe=E(require("p-retry")),Fc=E(require("object-hash"));q();j();yT=ct(),jt=I("testim service api"),ne=3,bT="/grid";el=async()=>(0,oe.default)(()=>xe("/grid/lt/config"),{retries:ne}),tl=async r=>(0,oe.default)(()=>xe(`/labFeature/v2/project/${r}`),{retries:ne});ol=Jt.memoize(async(r,e,t,s)=>{if(!Jt.isEmpty(s))return await am(r,e,t,JSON.stringify(s),"test-run-data","application/json")},(r,e,t,s)=>`${(0,Fc.default)(s)}:${e}:${t}`),Fo=Jt.memoize(async(r,e,t,s,n)=>!s||Jt.isEmpty(s)?void 0:await am(r,e,t,JSON.stringify((()=>{let i=Jt.clone(s);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&Object.assign(i,{[c]:pc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(r,e,t,s)=>`${(0,Fc.default)(s)}:${e}:${t}`)});var kr={};W(kr,{getSessionPlayer:()=>re,options:()=>fl});var Uo,fl,ml,re,Ee=T(()=>{"use strict";Uo=require("path"),fl={playerPath:void 0},re=()=>{if(ml)return ml;let r=(Oe(),ie(_e));r.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(is(),ie(on)),t=e(),s=fl.playerPath?(0,Uo.resolve)(fl.playerPath,"src/background/sessionPlayerInit.ts"):(0,Uo.join)(t,"sessionPlayer.js"),n=require(s);return r.log("getSessionPlayerRequire end"),ml=n,n}});function PT(r){process.nextTick(()=>{if([J.SELENIUM,J.APPIUM].includes(r))try{(Ee(),ie(kr)).getSessionPlayer(),require("jsdom")}catch{}})}async function fn(r){let{project:e,token:t,lightweightMode:s,useLocalChromeDriver:n,useChromeLauncher:o,mode:i}=r,a=Boolean(s==null?void 0:s.general),c=Boolean(n||o),u=a?xT:IT;_("before initializeUserWithAuth");let d=await ft(async()=>(PT(i),await Qc({projectId:e,token:t,branchName:r.branch,lightweightMode:s,localGrid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:r.branch,lightweightModeGeneral:a,localGrid:c})();return _("after initializeUserWithAuth"),nm(d.authData,r.project,r.token),d}var IT,xT,cm=T(()=>{"use strict";Oe();Te();Ht();It();ae();IT=1e3*60*5,xT=1e3*60*60*10});async function dm(r){var o;let e=Promise.resolve(),t=!r.host&&!r.gridId&&!r.grid&&(!r.testPlan||r.testPlan.length===0),s=r.files.length!==0;(t&&s||r.useLocalChromeDriver)&&(r.chromeBinaryLocation=r.downloadBrowser?await Co():r.chromeBinaryLocation,e=Pr({projectId:r.project,userId:r.user},{chromeBinaryLocation:r.chromeBinaryLocation},Boolean((o=r.lightweightMode)==null?void 0:o.general)),r.useLocalChromeDriver=!0),!r.playerRequirePath&&r.mode!==J.EXTENSION&&await Ar(r.playerLocation,r.canary),r.mode===J.EXTENSION&&!r.ext&&await Pc(r.extensionLocation);let n;if(r.installCustomExtension){let i=Boolean(r.useLocalChromeDriver||r.useChromeLauncher);n=await xc(r.installCustomExtension,i)}return await e,n}async function pm(r){var i;AT.info("prepare MockNetwork",{location:r});let e=await ac(r),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>lm*1e6)throw new Error(`${hl} exceeded ${lm}MB`);let s;try{s=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${hl} cannot be parsed.${jo.EOL}${a}`)}let n=new um.default;if(!n.validate(wc,s)){let a=(i=n.errors)==null?void 0:i.map((c,u)=>`${++u}) ${c.dataPath} ${c.message}`).join(jo.EOL);throw new Error(`${hl} is malformed.${jo.EOL}${a}`)}return s.entries}var jo,um,lm,hl,AT,gl=T(()=>{"use strict";jo=E(require("os"));U();Ep();is();um=E(require("ajv"));ae();_c();cm();lm=1,hl="JSON file supplied to --mock-network-pattern",AT=(j(),ie(Ya)).getLogger("prepare runner")});function fm(r,e=process){async function t(s){await te(de(mm,async n=>n()),1e4).catch(()=>null),r(s)}e.on("uncaughtException",async s=>{hn.error("Caught exception",{err:s}),console.log("Uncaught exception"),s.message&&console.log("Message =",s.message),s.reason&&console.log("Reason =",s.reason),await t(s)}),e.on("unhandledRejection",s=>{var n;if(hn.fatal("Caught unhandled promise rejection",s),!((n=s==null?void 0:s.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw s}),e.on("rejectionHandled",()=>{hn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let s="Runner aborted - SIGTERM event",n=new Error(s);throw hn.error(s),t(n),n}),e.once("SIGINT",()=>{let s="Runner aborted - SIGINT event",n=new Error(s);throw hn.error(s),t(n),n}),e.once("exit",s=>{r(s)})}function ls(r){mm.push(r)}var hn,mm,gn=T(()=>{"use strict";j();U();hn=I("process-handler"),mm=[]});function Tl(r,e){let t=r.canary?"-master.zip":".zip",s=`${e?Yd:Kr}/extension/testim-firefox-profile${t}`,n=`${e?Qd:Kr}/extension/testim-headless${t}`;return{firefox:s,chrome:n,"edge-chromium":n}}function wm(r){let{chrome:e,firefox:t}=Tl(r,!1);return r.browser==="firefox"?t:r.browser==="chrome"?e:[e,t]}function $o(r){let e=`${Kr}/extension/sessionPlayer`;return r.canary?`${e}-master`:e}var Wo=T(()=>{"use strict";le()});function Rm(r){Le||(r!=null&&r.userId||(r={anonymousId:Sm}),Em.identify(r))}function ht(r,e){return us("ci",r,e)}function us(r,e,t){if(Le)return;let s=r?{userId:r}:{anonymousId:Sm};Em.track(Object.assign(s,{event:e,properties:t}))}var vm,Em,Sm,ds=T(()=>{"use strict";le();vm=E(require("analytics-node")),Em=new vm.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),Sm=require("crypto").randomBytes(20).toString("hex")});function Im(r){return r.start&&us(null,"cli-start-command",{downloadBrowser:Boolean(r.downloadBrowser)}),!!(r.startV2||r.start||r.agent)}async function xm(r){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,s=!1,n=!1,o=!1;if(r.start&&(o=!0),Number.isNaN(r.agentPort))throw new P("Agent port is not number");if(typeof r.agent=="string"&&e.some(a=>r.agent.includes(a))){let a=r.agent.split(",").map(c=>c.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(s=!0),a.includes("playground-selenium")&&(n=!0)}let i=$o(r);return console.log("Start Testim CLI on Agent mode"),{project:r.project,token:r.token,agentMode:!0,agentPort:r.agentPort,agentBind:r.agentBind,openEditor:r.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:s,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:r.ext,extensionPath:r.extensionPath,playerLocation:r.playerPath||i,canary:r.canary,playerPath:r.playerPath,playerRequirePath:r.playerRequirePath,downloadBrowser:Boolean(r.downloadBrowser)}}var Pm=T(()=>{"use strict";Wo();ds();q()});function Vo(r){let{platform:e}=process;e==="win32"?(0,Go.exec)(`start chrome ${r}`):e==="darwin"?(0,Go.exec)(`open -a "Google Chrome" ${r}`):e==="linux"&&(0,Go.exec)(`google-chrome ${r}`)}var Go,vl=T(()=>{"use strict";Go=require("child_process")});var bn={};W(bn,{doLogin:()=>Il,getProjectId:()=>DT,getToken:()=>MT});async function DT(){return km("projectId")}async function MT(){return km("token")}function Cm(r,e){return Promise.race([r,se(e).then(()=>{throw new X("timeout")})])}async function FT(){let r=(await import("express")).default(),e=async function(){return Cm(new Promise(n=>{r.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((s,n)=>{let o=r.listen(42543,i=>{i&&n(i),s(o.address().port)})});try{let{getEditorUrl:s}=await Promise.resolve().then(()=>(Te(),ve)),{editorUrl:n}=await s();Vo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Il({overwriteExisting:r=!0,projects:e=null}={}){let t=El.homedir(),s=Sl.join(t,".testim");if(await be(s)&&!r)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Testim extension ...").start();if(e||(e=await Cm(FT(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await Am(s,o);return}if(e!=null&&e.length){c.succeed();let u=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=u.project.ci.token,o.projectId=u.project.id,await Am(s,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Am(r,e){await Rl.promises.writeFile(r,qo.stringify(e)),console.log(`Testim credentials saved in '${r}'`)}async function km(r){let e=El.homedir(),t=Sl.join(e,".testim"),s=await be(t),n={};if(s)try{n=qo.parse((await Rl.promises.readFile(t)).toString())}catch{}return n||(n={}),n[r]}var El,Sl,qo,Rl,ps=T(()=>{"use strict";El=E(require("os")),Sl=E(require("path")),qo=E(require("yaml"));U();Rl=require("fs");vl()});var Mm={};W(Mm,{process:()=>HT});var xl,Om,Pl,Lm,gt,Me,Nm,UT,Pe,Cl,jT,BT,_m,Dm,$T,Al,zo,kl,WT,Ho,xt,GT,l,VT,qT,HT,Fm=T(()=>{"use strict";xl=E(require("ms")),Om=E(require("chalk")),Pl=E(require("fs")),Lm=E(require("url")),gt=E(require("lodash")),Me=E(require("path"));U();Wo();Pm();Ht();Nm=require("commander");ae();q();Bs();U();UT=r=>r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Pe=(r,e)=>(e.push(r),e),Cl=new Nm.Command,jT=r=>r.split(","),BT=(r,e)=>!r||r.length===0?e:r,_m=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Dm=()=>{function r(f){return f.includes("-h, --help")}function e(f){return f.includes("--params [params-json-string]")}function t(f){return f.includes("--ext")||f.includes("--extension-path")}function s(f){return f.includes("--player-path")||f.includes("--player-require-path")}function n(f){return f.includes("--executionId")||f.includes("--source")||f.includes("--resultId")||f.includes("--remoteRunId")||f.includes("--schedulerId")}function o(f){return f.includes("--get-browser-timeout")||f.includes("--get-browser-retries")||f.includes("--get-session-timeout")||f.includes("--get-session-retries")||f.includes("--driver-request-timeout")||f.includes("--driver-request-retries")}function i(f){return f.includes("--user")}function a(f){return f.includes("shouldMonitorPerformance")}function c(f){return f.includes("--save-rca-locally")}function u(f){return f.includes("--exit-code-ignore-failing-tests")}function d(f){return f.includes("--high-speed")}function p(f){return f.includes("--urls")}function m(f){return f.includes("--test-start-timeout")}function h(f){return f.includes("--install-lazy-deps")}Cl.help(f=>f.split(`
|
|
17
|
-
`).filter(y=>!t(y)&&!e(y)&&!r(y)&&!s(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!c(y)&&!u(y)&&!d(y)&&!p(y)&&!m(y)&&!
|
|
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 dT(){let r=`${Kr}/extension/sessionPlayer_LATEST_RELEASE`;return(await vr(r)).body.toString("utf8")}async function pT(r,e){if(!Ge(r)||Ge(r)&&e||Le)return r;let t=await dT();return`${r}-${t}`}function Ac(){let r=mt();return os.resolve(r,"testim-bin")}function mT(){let r=Ac();return os.resolve(r,"sessionPlayer.zip")}async function em(r,e,t=!1){try{return await co(r,e),await tt(e,Ac())}catch(s){if(t)throw s;return await em(r,e,!0)}}async function Ar(r,e){Po.info("prepare player",{location:r,canary:e});let t=mT();return ft(async()=>{let s=await pT(r,e);return await em(s,t),{}},"preparePlayer",Zp,[r,e,t])()}var Yp,Xp,os,Qp,Po,Zp,Ic,Jp,is=T(()=>{"use strict";Yp=E(require("ms")),Xp=E(require("fs")),os=E(require("path"));le();Ht();Qp=require("serialize-error");j();vc();q();U();Po=x("prepare runner and testim start"),Zp=(0,Yp.default)("0.5 day"),Ic=16,Jp=`The size of the custom extension is more than ${Ic}MB`});function fT(){let r=an.type().toLowerCase();return r==="darwin"?an.arch()==="arm"?"mac_arm":"mac":r==="windows_nt"?an.arch()==="x64"?"win64":"win32":"linux"}async function Co(){let r=fT(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(r in t))throw new P(`Unsupported platform: ${r}`);let s=parseInt(cn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:s,win64:s},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[r]}/${cn}/${n[r]}.zip`,a=Ao.join(Cc,n[r]),c=`${a}.zip`,u=Ao.join(a,o[r]);if(await be(u))return u;if(!await be(c)){let p=(0,kc.default)("Downloading Chromium").start();try{await tm.promises.mkdir(Cc),await ze(i,c)}catch(m){let g=`Failed to download Chromium: ${m.message}`;throw p.fail(g),new Error(g)}p.succeed()}let d=(0,kc.default)("Extracting Chromium").start();try{await tt(c,Cc)}catch(p){let m=`Failed to extract Chromium: ${p.message}`;throw d.fail(m),new Error(m)}return d.succeed(),u}var tm,an,Ao,kc,cn,Cc,_c=T(()=>{"use strict";tm=E(require("fs")),an=E(require("os")),Ao=E(require("path")),kc=E(require("ora"));q();U();cn="1000968",Cc=Ao.join(Mt,`chrome-${cn}`)});async function sm(r,e){return _o=r,Nc=e,await Oc()}function nm(r,e,t){st=r.token,_o=e,Nc=t,un=Mc(st),ko=r.refreshToken,Lc=r.ngrokToken,Dc=r.isNgrokWhitelisted}function gT(r=_o,e=Nc){return ft(()=>(ln.info("request to get cli token from server"),St({url:`${he}/auth/token`,body:{projectId:r,token:e}})),"getTokenV3",rm*10,{projectId:r,token:e})()}async function hT(){return ln.info("request to refresh JWT cli token from server"),st=(await St({url:`${he}/auth/refreshToken`,body:{token:st,refreshToken:ko}})).token,un=Mc(st),st}async function Oc(){try{let r=await gT();return ln.info("successfully get cli token from server"),st=r.token,un=Mc(st),ko=r.refreshToken,Lc=r.ngrokToken,Dc=r.isNgrokWhitelisted,st}catch(r){throw r.message.includes("Unauthorized")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(ln.error(`While trying to retrieve CLI token. caught error: ${r}`,{projectId:_o}),new P(`While trying to retrieve CLI token, caught error: ${r}`))}}function Mc(r){return require("jsonwebtoken").decode(r).exp*1e3}async function Kt(){if(!un)return Oc();if(un<Date.now()+4*rm)try{return await hT()}catch(r){return ln.error("failed to refresh token, executing fallback",r),Oc()}return st}function Oo(){return ko}function Ft(){return st?{uid:require("jsonwebtoken").decode(st).id,ngrokToken:Lc,isNgrokWhitelisted:Dc}:{}}var ln,st,un,ko,Lc,Dc,_o,Nc,rm,It=T(()=>{"use strict";le();Rt();Ht();q();j();ln=x("testim-custom-token"),_o=null,Nc=null,rm=5*60*1e3});var om={};W(om,{isCi:()=>as});var as,Lo=T(()=>{"use strict";as=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var ve={};W(ve,{addTestRetry:()=>il,clearTestResult:()=>sl,deleteCloudflareTunnel:()=>ul,fetchLambdatestConfig:()=>el,forceUpdateCloudflareTunnelRoutes:()=>ll,getAllGrids:()=>Zc,getAppDetails:()=>qc,getApplitoolsIntegrationData:()=>al,getCloudflareTunnel:()=>cl,getEditorUrl:()=>ET,getGridById:()=>Mo,getGridByName:()=>Xc,getHybridGridProvider:()=>Yc,getLabFeaturesByProjectId:()=>tl,getMobileDevicesFromGrid:()=>pl,getRealData:()=>mn,getS3Artifact:()=>pn,getSuiteTestList:()=>Vc,getTestPlan:()=>vT,getTestPlanTestList:()=>Gc,getTestResults:()=>Cr,getUsageForCurrentBillingPeriod:()=>Hc,initializeUserWithAuth:()=>Qc,isTestResultCompleted:()=>zc,keepAliveGrid:()=>Kc,loadSfdcCredential:()=>Uc,loadTest:()=>jc,releaseGridSlot:()=>Jc,reportExecutionFinished:()=>No,reportExecutionStarted:()=>Wc,saveRemoteStep:()=>nl,saveTestPlanResult:()=>Bc,updateExecutionTests:()=>$c,updateRemoteRunFailure:()=>dl,updateTestDataArtifact:()=>Fo,updateTestResult:()=>rl,updateTestStatus:()=>cs,uploadRunDataArtifact:()=>ol});async function dn(){let r=await Kt();if(!r)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${r}`}}async function nt({url:r,body:e,headers:t={},timeout:s,retry:n}){let o=await dn(),i=Object.assign({},t,o);return St({url:`${he}${r||""}`,body:e,headers:i,timeout:s,retry:n})}async function wT(r,e,t,s={},n=void 0){let o=await dn(),i=Object.assign({},s,o);return await tc(`${he}${r||""}`,e,t,i,n)}async function Do(r,e){let t=await dn();return await sc(`${he}${r||""}`,e,t)}async function TT(r,e){let t=await dn();return await Hs(`${he}${r||""}`,e,t)}async function xe(r,e,t,s){let n=await dn();return await Tr(`${he}${r||""}`,e||void 0,n,s,t)}function pn(r,e){return(0,oe.default)(()=>xe(`/storage${r}`,null,{isBinary:!0},e),{retries:ne,factor:1})}async function vT(r,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,oe.default)(()=>xe("/testPlan",{projectId:r,name:e.join(",")}),{retries:ne,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function Uc({branch:r,projectId:e}){let t=await(0,oe.default)(()=>xe(`/branch/branchData/${r}`,{projectId:e}),{retries:ne,factor:1});return t==null?void 0:t.sfdcCredential}function jc({testId:r,branch:e,projectId:t,skipSharedSteps:s=!1,useBranchMap:n=!0}){return(0,oe.default)(()=>xe(`/test/${r}`,{projectId:t,branch:e,skipSharedSteps:s,useBranchMap:n}),{retries:ne,factor:1})}function Bc(r,e,t){return(0,oe.default)(()=>nt({url:"/testPlan/result",body:{projectId:r,testPlanId:e,result:t}}),{retries:ne,factor:1})}function cs(r,e,t,s,n,o,i=ne){return(0,oe.default)(()=>Do("/result/run/test",{runId:e,testId:t,resultId:s,status:n,projectId:r,runnerVersion:yT,...o}),{retries:i,factor:1})}function $c(r,e,t,s,n,o,i,a){return(0,oe.default)(()=>Do("/result/run/tests",{runId:r,runnerStatuses:e,status:t,reason:s,success:n,startTime:o,endTime:i,projectId:a}),{retries:ne,factor:1})}async function Wc({executionId:r,projectId:e,labels:t,startTime:s,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:c,isLocalRun:u,intersections:d}){let{isCi:p}=await Promise.resolve().then(()=>(Lo(),om));return nt({timeout:9e4,url:"/result/run",body:{runId:r,projectId:e,labels:t,startTime:s,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:p,localRunUserId:c,isLocalRun:u}},retry:3})}function No(r,e,t,s,n={},o=void 0,i=void 0){let a=Date.now();return(0,oe.default)(()=>Do("/result/run",{runId:e,projectId:t,endTime:a,status:r,success:s,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ne,factor:1})}async function Gc(r,e,t,s,n){return(0,oe.default)(()=>nt({url:"/testPlan/list",body:{projectId:r,names:e,planIds:t,branch:s,intersections:n},timeout:12e4}),{retries:ne,factor:1})}function Vc({projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:u,intersections:d}){return(0,oe.default)(()=>nt({url:"/suite/v2/list",body:{projectId:r,labels:e,testIds:t,testNames:s,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:u,intersections:d}}),{retries:ne,factor:1})}async function qc({appId:r,projectId:e}){try{return await(0,oe.default)(()=>xe(`/mobile-app/app/${r}?projectId=${e}`),{retries:ne,factor:1})}catch(t){jt.error("failed getting application details",{appId:r,error:t});return}}async function Hc(r){try{return await(0,oe.default)(()=>xe(`/plan/project/${r}/usage-current-billing-period`),{retries:ne,factor:1})}catch(e){jt.error("failed getting usage for current billing period",{projectId:r,error:e});return}}function zc(r,e,t){return(0,oe.default)(()=>xe(`/result/${r}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ne,factor:1})}function Cr(r,e,t,s){return(0,oe.default)(()=>xe(`/test/v2/${r}/result/${e}`,{projectId:t,branch:s}),{retries:ne,factor:1})}function Kc(r,e){return nt({url:`/grid/keep-alive?reqId=${z()}`,body:{projectId:r,slots:e},timeout:1e4})}function Jc(r,e,t,s,n){return nt({url:`/grid/release?reqId=${z()}`,body:{companyId:r,projectId:e,slotId:t,gridId:s,browser:n}})}function Yc(r){return nt({url:"/grid/hybrid/provider",body:r})}function Xc(r,e,t,s,n){return(0,oe.default)(()=>xe("/grid/name",{companyId:r,projectId:e,name:t,browser:s,executionId:n,reqId:z()}),{retries:ne,factor:1})}function Mo(r,e,t,s,n){return(0,oe.default)(()=>xe(`/grid/${t}`,{companyId:r,projectId:e,browser:s,executionId:n,reqId:z()}),{retries:ne,factor:1})}async function Qc({projectId:r,token:e,branchName:t,lightweightMode:s,localGrid:n}){var o,i;try{return await(0,oe.default)(()=>St({url:`${he}/executions/initialize`,body:{projectId:r,token:e,branchName:t||"master",lightweightMode:s,localGrid:n}}),{retries:ne,factor:1})}catch(a){throw jt.error("error initializing info from server",a),(o=a==null?void 0:a.message)!=null&&o.includes("Bad Request")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(i=a==null?void 0:a.code)!=null&&i.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):a}}async function ET(){if(zr)return{editorUrl:zr};try{return await(0,oe.default)(()=>xe("/system-info/editor-url"),{retries:ne,onFailedAttempt:r=>{if(r.attemptNumber>=ne)throw r},factor:1})}catch{return jt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function Zc(r){return(0,oe.default)(()=>xe("/grid",{companyId:r}),{retries:ne,factor:1})}function mn(r,e,t){return(0,oe.default)(()=>xe(`/real-data/${e}?${t}&projectId=${r}`),{retries:ne,factor:1})}function rl(r,e,t,s,n){return(0,oe.default)(()=>nt({url:"/result/test",body:{projectId:r,resultId:e,testId:t,testResult:s,remoteRunId:n}}),{retries:ne,factor:1})}function sl(r,e,t,s){return(0,oe.default)(()=>nt({url:"/result/test/clear",body:{projectId:r,resultId:e,testId:t,testResult:s}}),{retries:ne,factor:1})}function nl(r,e,t,s){return(0,oe.default)(()=>nt({url:"/remoteStep",body:{projectId:r,resultId:e,stepId:t,remoteStep:s}}),{retries:ne,factor:1})}function ST(r){return r.startsWith("/")?r:`/${r}`}function RT(r,e,t){let s=ST(r);return t&&(s=`/${t}${s}`),e&&(s=`/${e}${s}`),s}async function am(r,e,t,s,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${z()}${i||""}`,c=`${e}/${t}/${a}`,u=RT(c,"test-result-artifacts",r),d=Buffer.from(im.gzip(s,{level:3})),p={file:{fileName:a,buffer:d}};return await(0,oe.default)(()=>wT(`/storage${u}`,{},p,{"X-Asset-Encoding":"gzip"}),{retries:ne,factor:1}),u}function il({projectId:r,runId:e,testId:t,newResultId:s,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,oe.default)(()=>nt({url:"/result/test/retry",body:{projectId:r,newResultId:s,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ne,factor:1})}async function al(r){try{return await xe(`/integration/applitools/v3/connected?projectId=${r}`)}catch(e){return jt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function cl(r,e){try{return await Do("/tunnel",{companyId:r,routes:e})}catch(t){return jt.warn("could'nt get tunnel.",{err:t}),{}}}async function ll(r,e){try{return await nt({url:`/tunnel/${e}`,body:{companyId:r}})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}async function ul(r,e){try{return await TT(`/tunnel/${e}`,{companyId:r})}catch(t){jt.warn("could'nt get tunnel.",{err:t});return}}function dl(r){return St({url:`${he}/result/remoteRunFailure`,body:r})}async function pl({projectId:r,projectType:e,gridId:t,companyId:s,selectors:n}){let o=`${bT}/mobileDevices/${t}/${s}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,oe.default)(()=>xe(o,{projectId:r}),{retries:ne,factor:1})}catch(i){return jt.warn("could'nt get devices from headspin grid.",{err:i}),null}}var Jt,im,oe,Fc,yT,jt,ne,bT,el,tl,ol,Fo,Te=T(()=>{"use strict";Jt=E(require("lodash")),im=E(require("pako"));U();le();ae();Rt();It();oe=E(require("p-retry")),Fc=E(require("object-hash"));q();j();yT=ct(),jt=x("testim service api"),ne=3,bT="/grid";el=async()=>(0,oe.default)(()=>xe("/grid/lt/config"),{retries:ne,factor:1}),tl=async r=>(0,oe.default)(()=>xe(`/labFeature/v2/project/${r}`),{retries:ne,factor:1});ol=Jt.memoize(async(r,e,t,s)=>{if(!Jt.isEmpty(s))return await am(r,e,t,JSON.stringify(s),"test-run-data","application/json")},(r,e,t,s)=>`${(0,Fc.default)(s)}:${e}:${t}`),Fo=Jt.memoize(async(r,e,t,s,n)=>!s||Jt.isEmpty(s)?void 0:await am(r,e,t,JSON.stringify((()=>{let i=Jt.clone(s);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&Object.assign(i,{[c]:pc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(r,e,t,s)=>`${(0,Fc.default)(s)}:${e}:${t}`)});var kr={};W(kr,{getSessionPlayer:()=>re,options:()=>fl});var Uo,fl,ml,re,Ee=T(()=>{"use strict";Uo=require("path"),fl={playerPath:void 0},re=()=>{if(ml)return ml;let r=(Oe(),ie(_e));r.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(is(),ie(on)),t=e(),s=fl.playerPath?(0,Uo.resolve)(fl.playerPath,"src/background/sessionPlayerInit.ts"):(0,Uo.join)(t,"sessionPlayer.js"),n=require(s);return r.log("getSessionPlayerRequire end"),ml=n,n}});function PT(r){process.nextTick(()=>{if([J.SELENIUM,J.APPIUM].includes(r))try{(Ee(),ie(kr)).getSessionPlayer(),require("jsdom")}catch{}})}async function fn(r){let{project:e,token:t,lightweightMode:s,useLocalChromeDriver:n,useChromeLauncher:o,mode:i}=r,a=Boolean(s==null?void 0:s.general),c=Boolean(n||o),u=a?xT:IT;_("before initializeUserWithAuth");let d=await ft(async()=>(PT(i),await Qc({projectId:e,token:t,branchName:r.branch,lightweightMode:s,localGrid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:r.branch,lightweightModeGeneral:a,localGrid:c})();return _("after initializeUserWithAuth"),nm(d.authData,r.project,r.token),d}var IT,xT,cm=T(()=>{"use strict";Oe();Te();Ht();It();ae();IT=1e3*60*5,xT=1e3*60*60*10});async function dm(r){var o;let e=Promise.resolve(),t=!r.host&&!r.gridId&&!r.grid&&(!r.testPlan||r.testPlan.length===0),s=r.files.length!==0;(t&&s||r.useLocalChromeDriver)&&(r.chromeBinaryLocation=r.downloadBrowser?await Co():r.chromeBinaryLocation,e=Pr({projectId:r.project,userId:r.user},{chromeBinaryLocation:r.chromeBinaryLocation},Boolean((o=r.lightweightMode)==null?void 0:o.general)),r.useLocalChromeDriver=!0),!r.playerRequirePath&&r.mode!==J.EXTENSION&&await Ar(r.playerLocation,r.canary),r.mode===J.EXTENSION&&!r.ext&&await Pc(r.extensionLocation);let n;if(r.installCustomExtension){let i=Boolean(r.useLocalChromeDriver||r.useChromeLauncher);n=await xc(r.installCustomExtension,i)}return await e,n}async function pm(r){var i;AT.info("prepare MockNetwork",{location:r});let e=await ac(r),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>lm*1e6)throw new Error(`${gl} exceeded ${lm}MB`);let s;try{s=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${gl} cannot be parsed.${jo.EOL}${a}`)}let n=new um.default;if(!n.validate(wc,s)){let a=(i=n.errors)==null?void 0:i.map((c,u)=>`${++u}) ${c.dataPath} ${c.message}`).join(jo.EOL);throw new Error(`${gl} is malformed.${jo.EOL}${a}`)}return s.entries}var jo,um,lm,gl,AT,hl=T(()=>{"use strict";jo=E(require("os"));U();Ep();is();um=E(require("ajv"));ae();_c();cm();lm=1,gl="JSON file supplied to --mock-network-pattern",AT=(j(),ie(Xa)).getLogger("prepare runner")});function fm(r,e=process){async function t(s){await te(de(mm,async n=>n()),1e4).catch(()=>null),r(s)}e.on("uncaughtException",async s=>{gn.error("Caught exception",{err:s}),console.log("Uncaught exception"),s.message&&console.log("Message =",s.message),s.reason&&console.log("Reason =",s.reason),await t(s)}),e.on("unhandledRejection",s=>{var n;if(gn.fatal("Caught unhandled promise rejection",s),!((n=s==null?void 0:s.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw s}),e.on("rejectionHandled",()=>{gn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let s="Runner aborted - SIGTERM event",n=new Error(s);throw gn.error(s),t(n),n}),e.once("SIGINT",()=>{let s="Runner aborted - SIGINT event",n=new Error(s);throw gn.error(s),t(n),n}),e.once("exit",s=>{r(s)})}function ls(r){mm.push(r)}var gn,mm,hn=T(()=>{"use strict";j();U();gn=x("process-handler"),mm=[]});function Tl(r,e){let t=r.canary?"-master.zip":".zip",s=`${e?Xd:Kr}/extension/testim-firefox-profile${t}`,n=`${e?Qd:Kr}/extension/testim-headless${t}`;return{firefox:s,chrome:n,"edge-chromium":n}}function wm(r){let{chrome:e,firefox:t}=Tl(r,!1);return r.browser==="firefox"?t:r.browser==="chrome"?e:[e,t]}function $o(r){let e=`${Kr}/extension/sessionPlayer`;return r.canary?`${e}-master`:e}var Wo=T(()=>{"use strict";le()});function Rm(r){Le||(r!=null&&r.userId||(r={anonymousId:Sm}),Em.identify(r))}function gt(r,e){return us("ci",r,e)}function us(r,e,t){if(Le)return;let s=r?{userId:r}:{anonymousId:Sm};Em.track(Object.assign(s,{event:e,properties:t}))}var vm,Em,Sm,ds=T(()=>{"use strict";le();vm=E(require("analytics-node")),Em=new vm.default("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),Sm=require("crypto").randomBytes(20).toString("hex")});function Im(r){return r.start&&us(null,"cli-start-command",{downloadBrowser:Boolean(r.downloadBrowser)}),!!(r.startV2||r.start||r.agent)}async function xm(r){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,s=!1,n=!1,o=!1;if(r.start&&(o=!0),Number.isNaN(r.agentPort))throw new P("Agent port is not number");if(typeof r.agent=="string"&&e.some(a=>r.agent.includes(a))){let a=r.agent.split(",").map(c=>c.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(s=!0),a.includes("playground-selenium")&&(n=!0)}let i=$o(r);return console.log("Start Testim CLI on Agent mode"),{project:r.project,token:r.token,agentMode:!0,agentPort:r.agentPort,agentBind:r.agentBind,openEditor:r.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:s,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:r.ext,extensionPath:r.extensionPath,playerLocation:r.playerPath||i,canary:r.canary,playerPath:r.playerPath,playerRequirePath:r.playerRequirePath,downloadBrowser:Boolean(r.downloadBrowser)}}var Pm=T(()=>{"use strict";Wo();ds();q()});function Vo(r){let{platform:e}=process;e==="win32"?(0,Go.exec)(`start chrome ${r}`):e==="darwin"?(0,Go.exec)(`open -a "Google Chrome" ${r}`):e==="linux"&&(0,Go.exec)(`google-chrome ${r}`)}var Go,vl=T(()=>{"use strict";Go=require("child_process")});var bn={};W(bn,{doLogin:()=>Il,getProjectId:()=>NT,getToken:()=>MT});async function NT(){return km("projectId")}async function MT(){return km("token")}function Cm(r,e){return Promise.race([r,se(e).then(()=>{throw new Y("timeout")})])}async function FT(){let r=(await import("express")).default(),e=async function(){return Cm(new Promise(n=>{r.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((s,n)=>{let o=r.listen(42543,i=>{i&&n(i),s(o.address().port)})});try{let{getEditorUrl:s}=await Promise.resolve().then(()=>(Te(),ve)),{editorUrl:n}=await s();Vo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Il({overwriteExisting:r=!0,projects:e=null}={}){let t=El.homedir(),s=Sl.join(t,".testim");if(await be(s)&&!r)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Testim extension ...").start();if(e||(e=await Cm(FT(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await Am(s,o);return}if(e!=null&&e.length){c.succeed();let u=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=u.project.ci.token,o.projectId=u.project.id,await Am(s,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Am(r,e){await Rl.promises.writeFile(r,qo.stringify(e)),console.log(`Testim credentials saved in '${r}'`)}async function km(r){let e=El.homedir(),t=Sl.join(e,".testim"),s=await be(t),n={};if(s)try{n=qo.parse((await Rl.promises.readFile(t)).toString())}catch{}return n||(n={}),n[r]}var El,Sl,qo,Rl,ps=T(()=>{"use strict";El=E(require("os")),Sl=E(require("path")),qo=E(require("yaml"));U();Rl=require("fs");vl()});var Mm={};W(Mm,{process:()=>HT});var xl,Om,Pl,Lm,ht,Me,Dm,UT,Pe,Cl,jT,BT,_m,Nm,$T,Al,zo,kl,WT,Ho,xt,GT,l,VT,qT,HT,Fm=T(()=>{"use strict";xl=E(require("ms")),Om=E(require("chalk")),Pl=E(require("fs")),Lm=E(require("url")),ht=E(require("lodash")),Me=E(require("path"));U();Wo();Pm();Ht();Dm=require("commander");ae();q();Bs();U();UT=r=>r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Pe=(r,e)=>(e.push(r),e),Cl=new Dm.Command,jT=r=>r.split(","),BT=(r,e)=>!r||r.length===0?e:r,_m=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Nm=()=>{function r(f){return f.includes("-h, --help")}function e(f){return f.includes("--params [params-json-string]")}function t(f){return f.includes("--ext")||f.includes("--extension-path")}function s(f){return f.includes("--player-path")||f.includes("--player-require-path")}function n(f){return f.includes("--executionId")||f.includes("--source")||f.includes("--resultId")||f.includes("--remoteRunId")||f.includes("--schedulerId")}function o(f){return f.includes("--get-browser-timeout")||f.includes("--get-browser-retries")||f.includes("--get-session-timeout")||f.includes("--get-session-retries")||f.includes("--driver-request-timeout")||f.includes("--driver-request-retries")}function i(f){return f.includes("--user")}function a(f){return f.includes("shouldMonitorPerformance")}function c(f){return f.includes("--save-rca-locally")}function u(f){return f.includes("--exit-code-ignore-failing-tests")}function d(f){return f.includes("--high-speed")}function p(f){return f.includes("--urls")}function m(f){return f.includes("--test-start-timeout")}function g(f){return f.includes("--install-lazy-deps")}Cl.help(f=>f.split(`
|
|
17
|
+
`).filter(y=>!t(y)&&!e(y)&&!r(y)&&!s(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!c(y)&&!u(y)&&!d(y)&&!p(y)&&!m(y)&&!g(y)).join(`
|
|
18
18
|
`))},$T=(r,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Om.default.yellow(`
|
|
19
19
|
WARNING: ${r} is deprecated. ${t}
|
|
20
|
-
`))},Al=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:zo,argv:kl,stdout:WT,exit:Ho,cwd:xt}=global.process,GT=["trace","debug","info","warn","error","silent"];fc(kl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Cl.description("Testim.io CLI").option("--run [file-glob-pattern]","codeful test files to run",Pe,[]).option("-h --help","output usage information",Dm).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",Pe,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Pe,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Pe,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Pe,[]).option("-l, --label [label]","labels to search test by",Pe,[]).option("-n, --name [test-name]","test name to run",Pe,[]).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",jT).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",Pe,[]).option("--test-plan-id [test-plan-id]","test plan to run",Pe,[]).option("--suite [suite-name]","suite to run",Pe,[]).option("--suite-id [suite-id]","suite ID to run",Pe,[]).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",Pe,[]).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-model [device-model]","The device model to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("-rad --reset-app-data [reset-app-data]","set noReset appium capability to false, noReset capability is true by default",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(zo.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,xl.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,xl.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).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: ${Al.join("/")}`,Pe,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Pe,[]).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("--init [init]","Path for an initial test app").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Pe,[]).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)",Pe,[]).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)",Pe,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(kl);l=Cl.opts(),VT=()=>{l.grid||l.gridId||(l.host||(l.host="ondemand.saucelabs.com"),l.port||(l.port=80))},qT=()=>{l.grid||l.gridId||(l.host||(l.host="hub-cloud.browserstack.com"),l.port||(l.port=80))},HT=async()=>{var g,y,b,x,w,v,R,k,L;l.inspect&&require("inspector").open(l.inspect);let r={},e={},t=[],s={};if(!kl.slice(2).length)throw Dm(),new mr;if(l.requireCredentials){let S=await Promise.resolve().then(()=>(ps(),bn)),O=await S.getProjectId(),A=await S.getToken();(!O||!A)&&await S.doLogin()}if(l.login)return await(await Promise.resolve().then(()=>(ps(),bn))).doLogin(),{loginMode:!0};if(l.init)return{initCodimMode:!0,initTestProject:l.init};if(l.version){let S="Testim CLI Version: ";zo.npm_package_version&&(console.log(S,zo.npm_package_version),Ho(0));let O=ct();O&&(console.log(S,O),Ho(0)),console.log("Could not find version, please check the package.json manually"),Ho(0)}if(l.installLazyDeps)return{installLazyDepsMode:!0};l.disableFileCache&&Dp();let n=l.fileCacheLocation||l.usePrefechedData||l.createPrefechedData;if(n){let S=Me.resolve(n);Lp(S)}if(l.usePrefechedData&&Mp(),l.playerRequirePath){let S=Me.resolve(l.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",S);let O=Me.join(S,"tsconfig.node.json"),D=require("ts-node").register({project:O,ignore:[/node_modules/,new RegExp(`^${gt.escapeRegExp(Me.relative(xt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:D.config.options.paths,baseUrl:D.config.options.baseUrl}),(Ee(),ie(kr)).options.playerPath=S;let V=require("module"),Y=V.prototype.require;V.prototype.require=function(fe){return fe==="rox-alias"?Y.call(this,"rox-node"):Y.apply(this,arguments)}}if(l.caFile&&(global.caFileContent=Pl.readFileSync(l.caFile)),l.proxy&&(global.proxyUri=l.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),l.proxyForGrid&&!l.proxy)throw new P("missing --proxy option");if(Im(l))return xm(l);try{let S={};l.configFile?S=require(Me.join(xt(),l.configFile)).config:l.optionsFile&&(S=require(Me.join(xt(),l.optionsFile))),S&&typeof S.then=="function"&&(S=await S),Object.keys(S).forEach(O=>{let A=UT(O);l[A]=BT(l[A],S[O])})}catch(S){throw S.message=`Unable to read options file: ${S.message}`,S}if(l.tunneld)return{tunnel:!0,tunnelPort:l.tunnelPort,tunnelRoutes:l.tunnelRoutes,tunnelRoutesOutput:l.tunnelRoutesOutput,tunnelHostHeader:l.tunnelHostHeader,tunnelRegion:l.tunnelRegion,tunnelDiagnostics:l.tunnelDiagnostics,tunnelUseHttpAddress:l.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:l.token,project:l.project};let o=((g=l.testConfig)==null?void 0:g.length)||((y=l.testConfigId)==null?void 0:y.length),i=((b=l.testPlan)==null?void 0:b.length)||((x=l.testPlanId)==null?void 0:x.length),a=((w=l.suite)==null?void 0:w.length)||((v=l.suiteId)==null?void 0:v.length);if(l.seleniumCapsFile)try{s=require(Me.join(xt(),l.seleniumCapsFile))}catch(S){throw new P(`Failed to parse selenium caps file file error: ${S.message}`)}if((R=l.reporters)!=null&&R.includes("junit")&&!l.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!l.tunnel&&l.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!l.tunnel&&l.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!l.tunnel&&[l.tunnelPort,l.tunnelHostHeader,l.tunnelRegion,l.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(l.chromeExtraPrefs)try{e=require(Me.join(xt(),l.chromeExtraPrefs))}catch(S){throw new P(`Failed to read/open chrome extra prefs file error: ${S.message}`)}if(l.chromeExtraArgs){let S=l.chromeExtraArgs.split(",");for(let O of S){let[A]=O.split("=");_m.includes(A)||l.useLocalChromeDriver||l.useChromeLauncher?(t.push(O),A==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${A}), allowed values: ${JSON.stringify(_m)}`)}}if(l.paramsFile)try{r=Object.assign({},r,require(Me.join(xt(),l.paramsFile)))}catch(S){throw new P(`Failed to read/open params file error: ${S.message}`)}if(l.params)try{r=Object.assign({},r,JSON.parse(l.params))}catch(S){throw new P(`Failed to parse params string error: ${S.message}`)}if(l.sauceUser&&!l.sauceKey||!l.sauceUser&&l.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(l.sauceUser&&l.sauceKey&&(VT(),l.saucelabs={},l.saucelabs.username=l.sauceUser,l.saucelabs.accessKey=l.sauceKey),l.sauceOptions)try{let S=require(Me.join(xt(),l.sauceOptions)),O=S.platformName&&["ios","android"].includes(S.platformName.toLowerCase());if(S.browserName){let D=S.browserName.toLowerCase();switch(D){case"microsoftedge":l.browser="edge";break;default:l.browser=D}}l.browser==="edge"&&parseFloat(S.version)>=Ua&&(l.browser="edge-chromium");let A=parseFloat(S.version)<50&&!["dev","beta"].includes(S.version);if(!O&&l.browser==="chrome"&&A)throw new P("The minimum chrome supported version is 50.0");l.saucelabs=Object.assign({},l.saucelabs,S)}catch(S){throw new P(`Failed to parse saucelabs options file error: ${S.message}`)}if(l.browserstackUser&&!l.browserstackKey||!l.browserstackUser&&l.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(l.browserstackUser&&l.browserstackKey&&(qT(),l.browserstack={},l.browserstack["browserstack.user"]=l.browserstackUser,l.browserstack["browserstack.key"]=l.browserstackKey),l.browserstackOptions)try{let S=require(Me.join(xt(),l.browserstackOptions)),O=S.platform&&["mac","android"].includes(S.platform.toLowerCase());if(S.browserName&&(l.browser=S.browserName.toLowerCase()),l.browser==="edge"&&parseFloat(S.browser_version)>=Ua&&(l.browser="edge-chromium"),!O&&parseFloat(S.browser_version)<50&&l.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");l.browserstack=Object.assign({},l.browserstack,S)}catch(S){throw new P(`Failed to parse browserstack options file error: ${S.message}`)}if(l.perfecto={},l.perfectoToken&&(l.perfecto.securityToken=l.perfectoToken),l.perfectoOptions)try{let S=require(Me.join(xt(),l.perfectoOptions)),O={location:"US East",securityToken:l.perfectoToken};l.perfecto=Object.assign({},O,S)}catch(S){throw new P(`Failed to parse perfecto options file error: ${S.message}`)}if(l.testobjectSauce={},l.testobjectKey&&(l.testobjectSauce.testobjectApiKey=l.testobjectKey),l.testobjectOptions)try{let S=require(Me.join(xt(),l.testobjectOptions)),O={testobjectApiKey:l.testobjectKey};l.testobjectSauce=Object.assign({},O,S)}catch(S){throw new P(`Failed to parse test object options file error: ${S.message}`)}if(!l.project){let O=await(await Promise.resolve().then(()=>(ps(),bn))).getProjectId();if(O)l.project=O;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}l.mode||(l.mode=l.run.length?"selenium":"extension"),l.testConfig&&(l.testConfig=[l.testConfig].flat()),l.testConfigId&&(l.testConfigId=[l.testConfigId].flat()),l.retries=!l.retries||typeof l.retries=="boolean"?1:Number(l.retries)+1,l.browserTimeout=!l.browserTimeout||typeof l.browserTimeout=="boolean"?60*1e3:l.browserTimeout,l.newBrowserWaitTimeout=!l.newBrowserWaitTimeout||typeof l.newBrowserWaitTimeout=="boolean"?10*60*1e3:l.newBrowserWaitTimeout*60*1e3,l.getBrowserTimeout||(l.getBrowserTimeout=l.browserTimeout),l.getBrowserRetries||(l.getBrowserRetries=l.mode===J.APPIUM?1:Math.round(l.newBrowserWaitTimeout/l.browserTimeout)),l.getSessionTimeout=l.browserTimeout<l.getSessionTimeout?l.getSessionTimeout:l.browserTimeout,l.driverRequestTimeout=l.browserTimeout<l.driverRequestTimeout?l.driverRequestTimeout:l.browserTimeout;let c=Boolean(l.timeout);if(l.timeout=!l.timeout||typeof l.timeout=="boolean"?10*60*1e3:l.timeout,l.beforeParallel=!l.beforeParallel||typeof l.beforeParallel=="boolean"?1:Number(l.beforeParallel),l.parallel=!l.parallel||typeof l.parallel=="boolean"?1:Number(l.parallel),l.afterParallel=!l.afterParallel||typeof l.afterParallel=="boolean"?1:Number(l.afterParallel),l.parallel>1&&l.run&&!l.gridId&&!l.grid&&(!l.testPlan||l.testPlan.length===0)&&!((k=l.testPlanId)!=null&&k.length)&&WT.isTTY&&!l.headless&&!zo.TERM&&((await require("prompts")({type:"toggle",name:"isSure",message:"Running in parallel without --headless flag will open several browsers on your computer. Are you sure?",initial:!1,active:"yes",inactive:"no"})).isSure||Ho(0)),l.tunnelPort=!l.tunnelPort||typeof l.tunnelPort=="boolean"?"80":l.tunnelPort,l.port&&(l.port=Number(l.port)),l.retries<=0||Number.isNaN(l.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(l.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(!l.token){let O=await(await Promise.resolve().then(()=>(ps(),bn))).getToken();if(O)l.token=O;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}if(l.browserTimeout<=0||Number.isNaN(l.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(l.newBrowserWaitTimeout<=0||Number.isNaN(l.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(l.timeout<=0||Number.isNaN(l.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(l.beforeParallel<=0||Number.isNaN(l.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(l.parallel<=0||Number.isNaN(l.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(l.afterParallel<=0||Number.isNaN(l.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![J.EXTENSION,J.SELENIUM,J.APPIUM].includes(l.mode))throw new P(`runner mode <${l.mode}> is not supported`);if(l.mode!==J.SELENIUM&&l.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!l.browser&&!o&&!i&&(l.browser="chrome"),l.appiumLogLevel||(l.appiumLogLevel="silent"),!GT.includes(l.appiumLogLevel))throw new P(`runner appium-log-level <${l.appiumLogLevel}> is not supported`);if(l.testPlan&&l.testPlan.length===0&&l.testPlanId&&l.testPlanId.length===0){if(typeof l.host!="string"&&typeof l.grid!="string"&&typeof l.gridId!="string"&&l.run.length===0&&!l.useLocalChromeDriver&&!l.useChromeLauncher&&!l.createPrefechedData)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(l.testId.length||l.label.length||l.name.length||o||l.browser||a||l.useLocalChromeDriver||l.useChromeLauncher)throw new P("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(l.beforeParallel!==1||l.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if((l.testId.length||i||l.label.length||l.name.length||a)&&l.file)throw new P("Cannot pass codeful automation tests with --testId --label --name or --suite");if([l.host,l.grid,l.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((L=l.host)!=null&&L.includes("/")&&(/^(f|ht)tps?:\/\//i.test(l.host)||(l.host=`http://${l.host}`),l.host=Lm.parse(l.host).hostname),l.resultLabel.length){l.resultLabel=l.resultLabel.map(O=>O.trim()).filter(Boolean);let S=l.resultLabel.filter(O=>O.length>=250).filter(Boolean);if(l.branch==="auto-detect"&&l.resultLabel.includes("auto-detect-branch")&&Rr()&&l.resultLabel.unshift(Rr()),S.length)throw new P("A result label cannot exceed 250 characters")}let d=wm(l),p=$o(l);if(!l.w3cCapabilities&&!l.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(l.protocol||(l.protocol=l.port===443?"https":"http"),!["http","https"].includes(l.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(l.rerunFailedByRunId&&l.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(l.rerunFailedByRunId&&(a||l.name.length||l.testId.length||l.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(l.run.length){let S=require("glob");if(l.files=gt.flatMap(l.run,O=>S.sync(O)),l.files.length===0)throw new P(`No files found at path '${l.run}'.`)}else l.files=[];if(l.setRetention&&!gt.inRange(gt.parseInt(l.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");l.setRetention&&(l.setRetention=Number(l.setRetention));let m="is no longer supported, please use --override-mapping-file";if(l.mockNetworkHar)throw new P(`--mock-network-har ${m}`);if(l.mockNetworkPattern)throw new P(`--mock-network-pattern ${m}`);if(l.disableMockNetwork&&l.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!l.collectCodeCoverage&&l.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!l.collectCodeCoverage&&l.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!l.collectCodeCoverage&&l.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(l.collectCodeCoverage&&l.codeCoverageReporter&>.difference(l.codeCoverageReporter,Al).length){let S=gt.difference(l.codeCoverageReporter,Al);throw new P(`invalid --code-coverage-reporter parameters ${S.join("/")}`)}l.codeCoverageReporter=l.codeCoverageReporter.length===0?["html","text"]:l.codeCoverageReporter,l.codeCoverageInclude=l.codeCoverageInclude.length===0?["src/**"]:l.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"},f=Object.keys(h).filter(S=>Boolean(l[S]));if(l.mode!==J.EXTENSION&&f.length){let S=f.length>1?"are":"is";throw new P(`${f.map(O=>h[O]).join(" and ")} ${S} only applicable in extension mode`)}if(l.tmsFieldFile)try{let S=Pl.readFileSync(l.tmsFieldFile);l.tmsCustomFields=JSON.parse(S)}catch(S){throw new P(`failed to parse field file error: ${S.message}`)}if(l.highSpeed&&($T("--high-speed"," --turbo-mode"),l.turboMode=!0),l.deviceUdid&&(l.deviceModel||l.osVersion))throw new P("It is not possible to use --osVersion or --deviceModel with --device-udid. device-udid is unique and cannot be combined with another flag");if(l.resetAppData&&l.fullReset)throw new P("It is not possible to set both --reset-app-data and --full-reset capabilities to true at the same time!");if(l.resetOnSessionStartOnly&&!l.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),l.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"},O=typeof l.lightweightMode=="string"?JSON.parse(l.lightweightMode):{};l.lightweightMode=Object.assign({},S,O)}catch(S){throw new P(`failed to parse lightweightMode settings error: ${S.message}`)}else l.turboMode&&l.mode===J.EXTENSION&&(l.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"});if(typeof l.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[l.testId].flat(),name:[l.name].flat(),label:[l.label].flat(),suites:[l.suite].flat(),suiteIds:[l.suiteId].flat(),testPlan:[l.testPlan].flat(),testPlanIds:[l.testPlanId].flat(),files:[l.files].flat(),webpackConfig:l.webpackConfig,reportFile:l.reportFile,urls:l.urls,reportFileClassname:l.overrideReportFileClassname,reporters:l.reporters,project:l.project,host:l.host,headless:l.headless,useLocalChromeDriver:l.useLocalChromeDriver,chromeBinaryLocation:l.chromeBinaryLocation,useChromeLauncher:l.useChromeLauncher,port:l.port,grid:l.grid,gridId:l.gridId,disableNativeEvents:l.disableNativeEvents,saucelabs:l.saucelabs,browserstack:l.browserstack,baseUrl:l.baseUrl,branch:(l.branch==="auto-detect"?Rr():l.branch)||"master",autoDetect:l.branch==="auto-detect",token:l.token,userParamsData:r,mode:l.mode,isRegressionBaselineRun:l.isRegressionBaselineRun,browser:l.browser,beforeParallel:l.beforeParallel,parallel:l.parallel,afterParallel:l.afterParallel,canary:l.canary,rerunFailedByRunId:l.rerunFailedByRunId,disableGridCheck:l.disableGridCheck,disableTimeoutRetry:l.disableTimeoutRetry,resultLabels:l.resultLabel,path:l.path,protocol:l.protocol,perfecto:l.perfecto,experitestToken:l.experitestToken,testobjectSauce:l.testobjectSauce,gridUsername:l.gridUsername,gridPassword:l.gridPassword,overrideExecutionName:l.overrideExecutionName,tmsSuppressReporting:Boolean(l.suppressTmsReporting)||Boolean(l.tmsSuppressReporting),tmsRunId:l.tmsRunId,tmsCustomFields:l.tmsCustomFields,proxyForGrid:l.proxyForGrid,retentionDays:l.setRetention,passZeroTests:Boolean(l.passZeroTests),runQuarantinedTests:Boolean(l.runQuarantinedTests),deviceModel:l.deviceModel,deviceUdid:l.deviceUdid,osVersion:l.osVersion,appId:l.appId,appiumLogLevel:l.appiumLogLevel,resetAppData:l.resetAppData,fullReset:l.fullReset,resetOnSessionStartOnly:l.resetOnSessionStartOnly,ext:l.ext,extensionLocation:[l.extensionPath||d].flat(),extensionPath:l.extensionPath,playerLocation:l.playerPath||p,playerPath:l.playerPath,playerRequirePath:l.playerRequirePath,tunnel:l.tunnel,tunnelPort:l.tunnelPort,tunnelRoutes:l.tunnelRoutes,tunnelRoutesOutput:l.tunnelRoutesOutput,tunnelHostHeader:l.tunnelHostHeader,tunnelRegion:l.tunnelRegion,tunnelDiagnostics:l.tunnelDiagnostics,tunnelUseHttpAddress:l.tunnelUseHttpAddress,externalLambdatestTunnelId:l.externalLambdatestTunnelId,externalLambdatestUseWss:l.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(l.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(l.externalLambdatestMitm),beforeTest:l.beforeTest,afterTest:l.afterTest,beforeSuite:l.beforeSuite,afterSuite:l.afterSuite,timeout:l.timeout,timeoutWasGiven:c,browserTimeout:l.browserTimeout,newBrowserWaitTimeout:l.newBrowserWaitTimeout,getBrowserTimeout:l.getBrowserTimeout,getBrowserRetries:l.getBrowserRetries,getSessionTimeout:l.getSessionTimeout,getSessionRetries:l.getSessionRetries,driverRequestTimeout:l.driverRequestTimeout,driverRequestRetries:l.driverRequestRetries,testStartTimeout:l.testStartTimeout,testConfigNames:l.testConfig,testConfigIds:l.testConfigId,overrideMappingFile:l.overrideMappingFile,disableMockNetwork:l.disableMockNetwork,codeCoverageUrlFilter:l.codeCoverageUrlFilter,collectCodeCoverage:l.collectCodeCoverage,codeCoverageReportPath:l.codeCoverageReportPath,codeCoverageSourceMapPath:l.codeCoverageSourceMapPath,codeCoverageReporter:l.codeCoverageReporter,codeCoverageInclude:l.codeCoverageInclude,executionId:l.executionId,remoteRunId:l.remoteRunId,schedulerId:l.schedulerId,source:l.source,resultId:l.resultId,installCustomExtension:l.installCustomExtension,w3cCapabilities:l.w3cCapabilities,oldCapabilities:l.oldCapabilities,chromeBlockLocation:l.chromeBlockLocation,chromeUserDataDir:l.chromeUserDataDir,retries:l.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:l.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:s,shouldMonitorPerformance:l.monitorPerformance,user:l.user,lightweightMode:l.lightweightMode,createPrefechedData:l.createPrefechedData,saveRCALocally:l.saveRcaLocally,exitCodeIgnoreFailingTests:l.exitCodeIgnoreFailingTests,disableSockets:l.disableSockets,intersections:{labels:l.intersectWithLabel.length?[l.intersectWithLabel].flat():void 0,suiteNames:l.intersectWithSuite.length?[l.intersectWithSuite].flat():void 0,suiteIds:l.intersectWithSuiteId.length?[l.intersectWithSuiteId].flat():void 0},downloadBrowser:l.downloadBrowser}}});var _l={};W(_l,{installAllLazyDependencies:()=>JT,lazyRequire:()=>he});async function he(r,e={}){let t=Sc(r);if(t)return t;let s;e.silent||(s=(0,Um.default)(`Installing ${r} before first usage...`).start());try{let n=await KT(r);return s&&s.succeed(),n}catch(n){zT.warn("failed to install dependency lazily",{dependency:r,err:n});let o=Bm(r),i=`${r}@${o}`,c=process.argv.includes("npx")?"":"-g ",u=`Installation of ${r} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw s&&s.fail(u),n}}async function KT(r){return ms.has(r)||(ms.set(r,jm(r)),ms.get(r).catch(()=>{ms.delete(r)})),ms.get(r)}async function jm(r){let e=Sc(r);if(e)return e;let t=Bm(r),s=`${r}@${t}`;return await Io(mt(),s),zt(r)}async function JT(){let r=Object.keys(Wa);for(let e of r)await jm(e)}function Bm(r){let e=Object.entries(Wa).find(([t])=>t===r);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Um,zT,ms,yt=T(()=>{"use strict";Um=E(require("ora"));nn();j();U();to();sn();zT=I("lazy-require"),ms=new Map});var Vm={};W(Vm,{init:()=>YT});async function YT(r){var b,x;let e=typeof r=="string"?r:"";(typeof r!="string"||!r.trim())&&(e=(await(0,Ll.default)({type:"text",name:"project",message:"Please enter Project name",validate:v=>String(v).length>3})).project);let t=Xt.resolve(e);Yt.existsSync(t)&&Yt.readdirSync(t).length!==0&&(console.log(`${t} is not empty. Quitting...`),process.exit(1));let s=t.substr(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1),n=(0,Wm.default)(s);if(!n.validForNewPackages){let w=`The name '${s}' is not a valid package name:`;throw console.log(Ko.default.red(w)),n.errors&&n.errors.forEach(v=>console.log(Ko.default.red(v))),n.warnings&&n.warnings.forEach(v=>console.log(Ko.default.yellowBright(`warning: ${v}`))),new P(`${w}
|
|
20
|
+
`))},Al=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:zo,argv:kl,stdout:WT,exit:Ho,cwd:xt}=global.process,GT=["trace","debug","info","warn","error","silent"];fc(kl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Cl.description("Testim.io CLI").option("--run [file-glob-pattern]","codeful test files to run",Pe,[]).option("-h --help","output usage information",Nm).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",Pe,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Pe,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Pe,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Pe,[]).option("-l, --label [label]","labels to search test by",Pe,[]).option("-n, --name [test-name]","test name to run",Pe,[]).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",jT).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",Pe,[]).option("--test-plan-id [test-plan-id]","test plan to run",Pe,[]).option("--suite [suite-name]","suite to run",Pe,[]).option("--suite-id [suite-id]","suite ID to run",Pe,[]).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",Pe,[]).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-model [device-model]","The device model to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("-rad --reset-app-data [reset-app-data]","set noReset appium capability to false, noReset capability is true by default",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(zo.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,xl.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,xl.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).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: ${Al.join("/")}`,Pe,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Pe,[]).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("--init [init]","Path for an initial test app").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Pe,[]).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)",Pe,[]).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)",Pe,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(kl);l=Cl.opts(),VT=()=>{l.grid||l.gridId||(l.host||(l.host="ondemand.saucelabs.com"),l.port||(l.port=80))},qT=()=>{l.grid||l.gridId||(l.host||(l.host="hub-cloud.browserstack.com"),l.port||(l.port=80))},HT=async()=>{var h,y,b,I,w,v,R,k,L;l.inspect&&require("inspector").open(l.inspect);let r={},e={},t=[],s={};if(!kl.slice(2).length)throw Nm(),new mr;if(l.requireCredentials){let S=await Promise.resolve().then(()=>(ps(),bn)),O=await S.getProjectId(),A=await S.getToken();(!O||!A)&&await S.doLogin()}if(l.login)return await(await Promise.resolve().then(()=>(ps(),bn))).doLogin(),{loginMode:!0};if(l.init)return{initCodimMode:!0,initTestProject:l.init};if(l.version){let S="Testim CLI Version: ";zo.npm_package_version&&(console.log(S,zo.npm_package_version),Ho(0));let O=ct();O&&(console.log(S,O),Ho(0)),console.log("Could not find version, please check the package.json manually"),Ho(0)}if(l.installLazyDeps)return{installLazyDepsMode:!0};l.disableFileCache&&Np();let n=l.fileCacheLocation||l.usePrefechedData||l.createPrefechedData;if(n){let S=Me.resolve(n);Lp(S)}if(l.usePrefechedData&&Mp(),l.playerRequirePath){let S=Me.resolve(l.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",S);let O=Me.join(S,"tsconfig.node.json"),N=require("ts-node").register({project:O,ignore:[/node_modules/,new RegExp(`^${ht.escapeRegExp(Me.relative(xt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:N.config.options.paths,baseUrl:N.config.options.baseUrl}),(Ee(),ie(kr)).options.playerPath=S;let V=require("module"),X=V.prototype.require;V.prototype.require=function(fe){return fe==="rox-alias"?X.call(this,"rox-node"):X.apply(this,arguments)}}if(l.caFile&&(global.caFileContent=Pl.readFileSync(l.caFile)),l.proxy&&(global.proxyUri=l.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),l.proxyForGrid&&!l.proxy)throw new P("missing --proxy option");if(Im(l))return xm(l);try{let S={};l.configFile?S=require(Me.join(xt(),l.configFile)).config:l.optionsFile&&(S=require(Me.join(xt(),l.optionsFile))),S&&typeof S.then=="function"&&(S=await S),Object.keys(S).forEach(O=>{let A=UT(O);l[A]=BT(l[A],S[O])})}catch(S){throw S.message=`Unable to read options file: ${S.message}`,S}if(l.tunneld)return{tunnel:!0,tunnelPort:l.tunnelPort,tunnelRoutes:l.tunnelRoutes,tunnelRoutesOutput:l.tunnelRoutesOutput,tunnelHostHeader:l.tunnelHostHeader,tunnelRegion:l.tunnelRegion,tunnelDiagnostics:l.tunnelDiagnostics,tunnelUseHttpAddress:l.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:l.token,project:l.project};let o=((h=l.testConfig)==null?void 0:h.length)||((y=l.testConfigId)==null?void 0:y.length),i=((b=l.testPlan)==null?void 0:b.length)||((I=l.testPlanId)==null?void 0:I.length),a=((w=l.suite)==null?void 0:w.length)||((v=l.suiteId)==null?void 0:v.length);if(l.seleniumCapsFile)try{s=require(Me.join(xt(),l.seleniumCapsFile))}catch(S){throw new P(`Failed to parse selenium caps file file error: ${S.message}`)}if((R=l.reporters)!=null&&R.includes("junit")&&!l.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!l.tunnel&&l.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!l.tunnel&&l.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!l.tunnel&&[l.tunnelPort,l.tunnelHostHeader,l.tunnelRegion,l.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(l.chromeExtraPrefs)try{e=require(Me.join(xt(),l.chromeExtraPrefs))}catch(S){throw new P(`Failed to read/open chrome extra prefs file error: ${S.message}`)}if(l.chromeExtraArgs){let S=l.chromeExtraArgs.split(",");for(let O of S){let[A]=O.split("=");_m.includes(A)||l.useLocalChromeDriver||l.useChromeLauncher?(t.push(O),A==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${A}), allowed values: ${JSON.stringify(_m)}`)}}if(l.paramsFile)try{r=Object.assign({},r,require(Me.join(xt(),l.paramsFile)))}catch(S){throw new P(`Failed to read/open params file error: ${S.message}`)}if(l.params)try{r=Object.assign({},r,JSON.parse(l.params))}catch(S){throw new P(`Failed to parse params string error: ${S.message}`)}if(l.sauceUser&&!l.sauceKey||!l.sauceUser&&l.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(l.sauceUser&&l.sauceKey&&(VT(),l.saucelabs={},l.saucelabs.username=l.sauceUser,l.saucelabs.accessKey=l.sauceKey),l.sauceOptions)try{let S=require(Me.join(xt(),l.sauceOptions)),O=S.platformName&&["ios","android"].includes(S.platformName.toLowerCase());if(S.browserName){let N=S.browserName.toLowerCase();switch(N){case"microsoftedge":l.browser="edge";break;default:l.browser=N}}l.browser==="edge"&&parseFloat(S.version)>=Ua&&(l.browser="edge-chromium");let A=parseFloat(S.version)<50&&!["dev","beta"].includes(S.version);if(!O&&l.browser==="chrome"&&A)throw new P("The minimum chrome supported version is 50.0");l.saucelabs=Object.assign({},l.saucelabs,S)}catch(S){throw new P(`Failed to parse saucelabs options file error: ${S.message}`)}if(l.browserstackUser&&!l.browserstackKey||!l.browserstackUser&&l.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(l.browserstackUser&&l.browserstackKey&&(qT(),l.browserstack={},l.browserstack["browserstack.user"]=l.browserstackUser,l.browserstack["browserstack.key"]=l.browserstackKey),l.browserstackOptions)try{let S=require(Me.join(xt(),l.browserstackOptions)),O=S.platform&&["mac","android"].includes(S.platform.toLowerCase());if(S.browserName&&(l.browser=S.browserName.toLowerCase()),l.browser==="edge"&&parseFloat(S.browser_version)>=Ua&&(l.browser="edge-chromium"),!O&&parseFloat(S.browser_version)<50&&l.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");l.browserstack=Object.assign({},l.browserstack,S)}catch(S){throw new P(`Failed to parse browserstack options file error: ${S.message}`)}if(l.perfecto={},l.perfectoToken&&(l.perfecto.securityToken=l.perfectoToken),l.perfectoOptions)try{let S=require(Me.join(xt(),l.perfectoOptions)),O={location:"US East",securityToken:l.perfectoToken};l.perfecto=Object.assign({},O,S)}catch(S){throw new P(`Failed to parse perfecto options file error: ${S.message}`)}if(l.testobjectSauce={},l.testobjectKey&&(l.testobjectSauce.testobjectApiKey=l.testobjectKey),l.testobjectOptions)try{let S=require(Me.join(xt(),l.testobjectOptions)),O={testobjectApiKey:l.testobjectKey};l.testobjectSauce=Object.assign({},O,S)}catch(S){throw new P(`Failed to parse test object options file error: ${S.message}`)}if(!l.project){let O=await(await Promise.resolve().then(()=>(ps(),bn))).getProjectId();if(O)l.project=O;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}l.mode||(l.mode=l.run.length?"selenium":"extension"),l.testConfig&&(l.testConfig=[l.testConfig].flat()),l.testConfigId&&(l.testConfigId=[l.testConfigId].flat()),l.retries=!l.retries||typeof l.retries=="boolean"?1:Number(l.retries)+1,l.browserTimeout=!l.browserTimeout||typeof l.browserTimeout=="boolean"?60*1e3:l.browserTimeout,l.newBrowserWaitTimeout=!l.newBrowserWaitTimeout||typeof l.newBrowserWaitTimeout=="boolean"?10*60*1e3:l.newBrowserWaitTimeout*60*1e3,l.getBrowserTimeout||(l.getBrowserTimeout=l.browserTimeout),l.getBrowserRetries||(l.getBrowserRetries=l.mode===J.APPIUM?1:Math.round(l.newBrowserWaitTimeout/l.browserTimeout)),l.getSessionTimeout=l.browserTimeout<l.getSessionTimeout?l.getSessionTimeout:l.browserTimeout,l.driverRequestTimeout=l.browserTimeout<l.driverRequestTimeout?l.driverRequestTimeout:l.browserTimeout;let c=Boolean(l.timeout);if(l.timeout=!l.timeout||typeof l.timeout=="boolean"?10*60*1e3:l.timeout,l.beforeParallel=!l.beforeParallel||typeof l.beforeParallel=="boolean"?1:Number(l.beforeParallel),l.parallel=!l.parallel||typeof l.parallel=="boolean"?1:Number(l.parallel),l.afterParallel=!l.afterParallel||typeof l.afterParallel=="boolean"?1:Number(l.afterParallel),l.parallel>1&&l.run&&!l.gridId&&!l.grid&&(!l.testPlan||l.testPlan.length===0)&&!((k=l.testPlanId)!=null&&k.length)&&WT.isTTY&&!l.headless&&!zo.TERM&&((await require("prompts")({type:"toggle",name:"isSure",message:"Running in parallel without --headless flag will open several browsers on your computer. Are you sure?",initial:!1,active:"yes",inactive:"no"})).isSure||Ho(0)),l.tunnelPort=!l.tunnelPort||typeof l.tunnelPort=="boolean"?"80":l.tunnelPort,l.port&&(l.port=Number(l.port)),l.retries<=0||Number.isNaN(l.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(l.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(!l.token){let O=await(await Promise.resolve().then(()=>(ps(),bn))).getToken();if(O)l.token=O;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}if(l.browserTimeout<=0||Number.isNaN(l.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(l.newBrowserWaitTimeout<=0||Number.isNaN(l.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(l.timeout<=0||Number.isNaN(l.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(l.beforeParallel<=0||Number.isNaN(l.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(l.parallel<=0||Number.isNaN(l.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(l.afterParallel<=0||Number.isNaN(l.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![J.EXTENSION,J.SELENIUM,J.APPIUM].includes(l.mode))throw new P(`runner mode <${l.mode}> is not supported`);if(l.mode!==J.SELENIUM&&l.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!l.browser&&!o&&!i&&(l.browser="chrome"),l.appiumLogLevel||(l.appiumLogLevel="silent"),!GT.includes(l.appiumLogLevel))throw new P(`runner appium-log-level <${l.appiumLogLevel}> is not supported`);if(l.testPlan&&l.testPlan.length===0&&l.testPlanId&&l.testPlanId.length===0){if(typeof l.host!="string"&&typeof l.grid!="string"&&typeof l.gridId!="string"&&l.run.length===0&&!l.useLocalChromeDriver&&!l.useChromeLauncher&&!l.createPrefechedData)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(l.testId.length||l.label.length||l.name.length||o||l.browser||a||l.useLocalChromeDriver||l.useChromeLauncher)throw new P("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(l.beforeParallel!==1||l.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if((l.testId.length||i||l.label.length||l.name.length||a)&&l.file)throw new P("Cannot pass codeful automation tests with --testId --label --name or --suite");if([l.host,l.grid,l.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((L=l.host)!=null&&L.includes("/")&&(/^(f|ht)tps?:\/\//i.test(l.host)||(l.host=`http://${l.host}`),l.host=Lm.parse(l.host).hostname),l.resultLabel.length){l.resultLabel=l.resultLabel.map(O=>O.trim()).filter(Boolean);let S=l.resultLabel.filter(O=>O.length>=250).filter(Boolean);if(l.branch==="auto-detect"&&l.resultLabel.includes("auto-detect-branch")&&Rr()&&l.resultLabel.unshift(Rr()),S.length)throw new P("A result label cannot exceed 250 characters")}let d=wm(l),p=$o(l);if(!l.w3cCapabilities&&!l.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(l.protocol||(l.protocol=l.port===443?"https":"http"),!["http","https"].includes(l.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(l.rerunFailedByRunId&&l.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(l.rerunFailedByRunId&&(a||l.name.length||l.testId.length||l.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(l.run.length){let S=require("glob");if(l.files=ht.flatMap(l.run,O=>S.sync(O)),l.files.length===0)throw new P(`No files found at path '${l.run}'.`)}else l.files=[];if(l.setRetention&&!ht.inRange(ht.parseInt(l.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");l.setRetention&&(l.setRetention=Number(l.setRetention));let m="is no longer supported, please use --override-mapping-file";if(l.mockNetworkHar)throw new P(`--mock-network-har ${m}`);if(l.mockNetworkPattern)throw new P(`--mock-network-pattern ${m}`);if(l.disableMockNetwork&&l.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!l.collectCodeCoverage&&l.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!l.collectCodeCoverage&&l.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!l.collectCodeCoverage&&l.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(l.collectCodeCoverage&&l.codeCoverageReporter&&ht.difference(l.codeCoverageReporter,Al).length){let S=ht.difference(l.codeCoverageReporter,Al);throw new P(`invalid --code-coverage-reporter parameters ${S.join("/")}`)}l.codeCoverageReporter=l.codeCoverageReporter.length===0?["html","text"]:l.codeCoverageReporter,l.codeCoverageInclude=l.codeCoverageInclude.length===0?["src/**"]:l.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},f=Object.keys(g).filter(S=>Boolean(l[S]));if(l.mode!==J.EXTENSION&&f.length){let S=f.length>1?"are":"is";throw new P(`${f.map(O=>g[O]).join(" and ")} ${S} only applicable in extension mode`)}if(l.tmsFieldFile)try{let S=Pl.readFileSync(l.tmsFieldFile);l.tmsCustomFields=JSON.parse(S)}catch(S){throw new P(`failed to parse field file error: ${S.message}`)}if(l.highSpeed&&($T("--high-speed"," --turbo-mode"),l.turboMode=!0),l.deviceUdid&&(l.deviceModel||l.osVersion))throw new P("It is not possible to use --osVersion or --deviceModel with --device-udid. device-udid is unique and cannot be combined with another flag");if(l.resetAppData&&l.fullReset)throw new P("It is not possible to set both --reset-app-data and --full-reset capabilities to true at the same time!");if(l.resetOnSessionStartOnly&&!l.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),l.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"},O=typeof l.lightweightMode=="string"?JSON.parse(l.lightweightMode):{};l.lightweightMode=Object.assign({},S,O)}catch(S){throw new P(`failed to parse lightweightMode settings error: ${S.message}`)}else l.turboMode&&l.mode===J.EXTENSION&&(l.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"});if(typeof l.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[l.testId].flat(),name:[l.name].flat(),label:[l.label].flat(),suites:[l.suite].flat(),suiteIds:[l.suiteId].flat(),testPlan:[l.testPlan].flat(),testPlanIds:[l.testPlanId].flat(),files:[l.files].flat(),webpackConfig:l.webpackConfig,reportFile:l.reportFile,urls:l.urls,reportFileClassname:l.overrideReportFileClassname,reporters:l.reporters,project:l.project,host:l.host,headless:l.headless,useLocalChromeDriver:l.useLocalChromeDriver,chromeBinaryLocation:l.chromeBinaryLocation,useChromeLauncher:l.useChromeLauncher,port:l.port,grid:l.grid,gridId:l.gridId,disableNativeEvents:l.disableNativeEvents,saucelabs:l.saucelabs,browserstack:l.browserstack,baseUrl:l.baseUrl,branch:(l.branch==="auto-detect"?Rr():l.branch)||"master",autoDetect:l.branch==="auto-detect",token:l.token,userParamsData:r,mode:l.mode,isRegressionBaselineRun:l.isRegressionBaselineRun,browser:l.browser,beforeParallel:l.beforeParallel,parallel:l.parallel,afterParallel:l.afterParallel,canary:l.canary,rerunFailedByRunId:l.rerunFailedByRunId,disableGridCheck:l.disableGridCheck,disableTimeoutRetry:l.disableTimeoutRetry,resultLabels:l.resultLabel,path:l.path,protocol:l.protocol,perfecto:l.perfecto,experitestToken:l.experitestToken,testobjectSauce:l.testobjectSauce,gridUsername:l.gridUsername,gridPassword:l.gridPassword,overrideExecutionName:l.overrideExecutionName,tmsSuppressReporting:Boolean(l.suppressTmsReporting)||Boolean(l.tmsSuppressReporting),tmsRunId:l.tmsRunId,tmsCustomFields:l.tmsCustomFields,proxyForGrid:l.proxyForGrid,retentionDays:l.setRetention,passZeroTests:Boolean(l.passZeroTests),runQuarantinedTests:Boolean(l.runQuarantinedTests),deviceModel:l.deviceModel,deviceUdid:l.deviceUdid,osVersion:l.osVersion,appId:l.appId,appiumLogLevel:l.appiumLogLevel,resetAppData:l.resetAppData,fullReset:l.fullReset,resetOnSessionStartOnly:l.resetOnSessionStartOnly,ext:l.ext,extensionLocation:[l.extensionPath||d].flat(),extensionPath:l.extensionPath,playerLocation:l.playerPath||p,playerPath:l.playerPath,playerRequirePath:l.playerRequirePath,tunnel:l.tunnel,tunnelPort:l.tunnelPort,tunnelRoutes:l.tunnelRoutes,tunnelRoutesOutput:l.tunnelRoutesOutput,tunnelHostHeader:l.tunnelHostHeader,tunnelRegion:l.tunnelRegion,tunnelDiagnostics:l.tunnelDiagnostics,tunnelUseHttpAddress:l.tunnelUseHttpAddress,externalLambdatestTunnelId:l.externalLambdatestTunnelId,externalLambdatestUseWss:l.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(l.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(l.externalLambdatestMitm),beforeTest:l.beforeTest,afterTest:l.afterTest,beforeSuite:l.beforeSuite,afterSuite:l.afterSuite,timeout:l.timeout,timeoutWasGiven:c,browserTimeout:l.browserTimeout,newBrowserWaitTimeout:l.newBrowserWaitTimeout,getBrowserTimeout:l.getBrowserTimeout,getBrowserRetries:l.getBrowserRetries,getSessionTimeout:l.getSessionTimeout,getSessionRetries:l.getSessionRetries,driverRequestTimeout:l.driverRequestTimeout,driverRequestRetries:l.driverRequestRetries,testStartTimeout:l.testStartTimeout,testConfigNames:l.testConfig,testConfigIds:l.testConfigId,overrideMappingFile:l.overrideMappingFile,disableMockNetwork:l.disableMockNetwork,codeCoverageUrlFilter:l.codeCoverageUrlFilter,collectCodeCoverage:l.collectCodeCoverage,codeCoverageReportPath:l.codeCoverageReportPath,codeCoverageSourceMapPath:l.codeCoverageSourceMapPath,codeCoverageReporter:l.codeCoverageReporter,codeCoverageInclude:l.codeCoverageInclude,executionId:l.executionId,remoteRunId:l.remoteRunId,schedulerId:l.schedulerId,source:l.source,resultId:l.resultId,installCustomExtension:l.installCustomExtension,w3cCapabilities:l.w3cCapabilities,oldCapabilities:l.oldCapabilities,chromeBlockLocation:l.chromeBlockLocation,chromeUserDataDir:l.chromeUserDataDir,retries:l.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:l.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:s,shouldMonitorPerformance:l.monitorPerformance,user:l.user,lightweightMode:l.lightweightMode,createPrefechedData:l.createPrefechedData,saveRCALocally:l.saveRcaLocally,exitCodeIgnoreFailingTests:l.exitCodeIgnoreFailingTests,disableSockets:l.disableSockets,intersections:{labels:l.intersectWithLabel.length?[l.intersectWithLabel].flat():void 0,suiteNames:l.intersectWithSuite.length?[l.intersectWithSuite].flat():void 0,suiteIds:l.intersectWithSuiteId.length?[l.intersectWithSuiteId].flat():void 0},downloadBrowser:l.downloadBrowser}}});var _l={};W(_l,{installAllLazyDependencies:()=>JT,lazyRequire:()=>ge});async function ge(r,e={}){let t=Sc(r);if(t)return t;let s;e.silent||(s=(0,Um.default)(`Installing ${r} before first usage...`).start());try{let n=await KT(r);return s&&s.succeed(),n}catch(n){zT.warn("failed to install dependency lazily",{dependency:r,err:n});let o=Bm(r),i=`${r}@${o}`,c=process.argv.includes("npx")?"":"-g ",u=`Installation of ${r} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw s&&s.fail(u),n}}async function KT(r){return ms.has(r)||(ms.set(r,jm(r)),ms.get(r).catch(()=>{ms.delete(r)})),ms.get(r)}async function jm(r){let e=Sc(r);if(e)return e;let t=Bm(r),s=`${r}@${t}`;return await Io(mt(),s),zt(r)}async function JT(){let r=Object.keys(Wa);for(let e of r)await jm(e)}function Bm(r){let e=Object.entries(Wa).find(([t])=>t===r);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Um,zT,ms,yt=T(()=>{"use strict";Um=E(require("ora"));nn();j();U();to();sn();zT=x("lazy-require"),ms=new Map});var Vm={};W(Vm,{init:()=>XT});async function XT(r){var b,I;let e=typeof r=="string"?r:"";(typeof r!="string"||!r.trim())&&(e=(await(0,Ll.default)({type:"text",name:"project",message:"Please enter Project name",validate:v=>String(v).length>3})).project);let t=Yt.resolve(e);Xt.existsSync(t)&&Xt.readdirSync(t).length!==0&&(console.log(`${t} is not empty. Quitting...`),process.exit(1));let s=t.substr(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1),n=(0,Wm.default)(s);if(!n.validForNewPackages){let w=`The name '${s}' is not a valid package name:`;throw console.log(Ko.default.red(w)),n.errors&&n.errors.forEach(v=>console.log(Ko.default.red(v))),n.warnings&&n.warnings.forEach(v=>console.log(Ko.default.yellowBright(`warning: ${v}`))),new P(`${w}
|
|
21
21
|
validation errors:
|
|
22
22
|
${((b=n.errors)==null?void 0:b.join(`
|
|
23
23
|
`))||""}
|
|
24
24
|
warnings:
|
|
25
|
-
${((
|
|
26
|
-
`))||""}`)}let i=(await(0,Ll.default)({type:"toggle",name:"isJs",message:"Add support for TypeScript?",initial:!0,active:"no",inactive:"yes"})).isJs?"template.js":"template.ts",a="codim",c=Xt.join(__dirname,a,i),u=Xt.join(process.cwd(),e),d=(0,Ol.default)(`Creating new test project in ${u}`).start();await lo(c,u);let p=Xt.join(__dirname,a,i,"package.json"),m=Xt.join(process.cwd(),e,"package.json"),f=(await Yt.promises.readFile(p)).toString().replace("~testim-codeful-test-project~",s);await Yt.promises.writeFile(m,f);let g="node_modules",y=Xt.join(process.cwd(),e,".gitignore");await Yt.promises.writeFile(y,g),d.succeed(),d=(0,Ol.default)("Installing dependencies").start(),await XT("npm install",{cwd:u}),d.succeed(),console.log(`Testim Dev Kit project folder successfully created in ${u}.`)}var Yt,Xt,$m,Ol,Ko,Ll,Wm,Gm,XT,qm=T(()=>{"use strict";Yt=E(require("fs")),Xt=E(require("path")),$m=E(require("child_process")),Ol=E(require("ora")),Ko=E(require("chalk")),Ll=E(require("prompts")),Wm=E(require("validate-npm-package-name")),Gm=require("util");q();lc();XT=(0,Gm.promisify)($m.exec)});var zm={};W(zm,{preloadTests:()=>wn});async function wn(r){if(!Array.isArray(r.testId)||!r.testId.length)return{};let e={branch:r.branch,projectId:r.project};return await ft(async()=>{let t=await de(r.testId,s=>jc({...e,testId:s}),{concurrency:2});return Hm.keyBy(t,"testData.id")},"loadTests",QT,[e,r.testId])()}var Hm,QT,Jo=T(()=>{"use strict";Hm=E(require("lodash"));Ht();Te();U();QT=1e3*60*60*10});function Nl(){return ct()}async function Xm(){if(!Le)try{let r=await te(ev(),5e3,"The API call to NPM timed out"),e=Nl();e&&Jm.lt(e,r)&&console.log(Km.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(r){ZT.warn("Failed to get NPM version",{err:r})}}var Km,Jm,ZT,ev,Dl=T(()=>{"use strict";Km=E(require("chalk")),Jm=E(require("semver"));U();le();nn();Ht();j();ZT=I("npm-driver"),ev=ft(()=>Bp("@testim/testim-cli"),"getNpmVersion")});var Ml,rv,fs,Ym,Qm,Fl,Zm,ef=T(()=>{"use strict";U();q();j();yt();Ml=I("testimNgrok"),rv=".whitelisted-ngrok.testim.io",fs="",Qm=async(r,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${z()}-${r.projectData.projectId}${rv}`);let s={proto:"http",addr:r.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};r.tunnelHostHeader&&(s.host_header=r.tunnelHostHeader),r.tunnelRegion&&(s.region=r.tunnelRegion);let o=await(await he("ngrok")).connect(s);r.tunnelUseHttpAddress&&o.startsWith("https://")?(Ml.info("replace https to http"),fs=o.replace("https://","http://")):fs=o,r.tunnelDiagnostics&&Fl(),r.baseUrl=fs},Fl=async(r=!0)=>{try{let t=(await he("ngrok")).getApi(),{tunnels:s}=await t.listTunnels(),n=s.find(o=>o.public_url===fs);console.log("ngrok stats",n),Ml.info("ngrok stats",{tunnel:n})}catch(e){Ml.error("error collecting ngrok stats",{err:e})}r&&(Ym=setTimeout(()=>Fl(),1e4))},Zm=async r=>{if(!fs)return;clearTimeout(Ym),r.tunnelDiagnostics&&await Fl(!1),await(await he("ngrok")).disconnect(fs)}});var Qt,jl,tf,nv,ov,Ul,Xo,Qo,Yo,iv,rf,sf,nf=T(()=>{"use strict";Qt=E(require("os")),jl=E(require("fs")),tf=E(require("child_process"));U();Te();nv="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",ov={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"}},Ul=Qt.tmpdir(),Xo=`${Ul}/cloudflared`,Qo=null,Yo=null,iv=async()=>{if(await be(Xo))return;let e=ov[Qt.platform()+Qt.arch()];if(!e)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let t=e.extract?Ul+e.path:Xo;await ze(`${nv}/${e.path}`,t),e.extract&&await tt(t,Ul),await jl.promises.chmod(Xo,"755")},rf=async r=>{let e=r.baseUrl||`http://localhost:${r.tunnelPort||80}`,t="tunnelRoutes"in r&&r.tunnelRoutes||[e],[s]=await Promise.all([cl(r.company.companyId,t),iv()]);Qo=s._id,Yo=tf.spawn(Xo,["tunnel","--no-autoupdate","run","--force","--token",s.token],{stdio:"inherit"}),await ll(r.company.companyId,Qo),"tunnelRoutesOutput"in r&&r.tunnelRoutesOutput&&await jl.promises.writeFile(r.tunnelRoutesOutput,JSON.stringify(s.routesMapping,null,2)),r.baseUrl=`${r.tunnelUseHttpAddress?"http":"https"}://${s.routesMapping[e]}`},sf=async r=>{let e=[];return Qo&&e.push(ul(r.company.companyId,Qo)),Yo&&e.push(new Promise((t,s)=>{Yo.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),Yo.kill()})),await Promise.all(e)}});var K,af,cv,lv,uv,of,Zo,Bl,M,ye=T(()=>{"use strict";K=E(require("rox-node"));j();U();le();af=I("FeatureFlagsService"),cv=!Le&&!0&&!Kd,lv=2e4,uv=60*60*24,of=["labs","disabled","enabled"],Zo=class extends K.default.Variant{constructor(e="disabled"){super(e,of)}getValue(){let e=super.getValue();return of.includes(e)?e:(af.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Bl=class{constructor(){this.flags={useNewWSCLI:new K.default.Flag,useSafariWebdriverVisibilityChecks:new K.default.Flag,useClickimVisibilityChecks:new K.default.Flag,runGetElementCodeInAut:new K.default.Flag,enableFrameSwitchOptimization:new K.default.Flag,maximumJsResultSize:new K.default.Configuration(2e3*1024),skipFileInputClicks:new K.default.Flag,errorMessageOnBadNetwork:new K.default.Flag(!0),warnOnBadNetwork:new K.default.Flag(!1),overrideAzureStorageUrl:new K.default.Flag,useJsInputCodeInSafari:new K.default.Flag,useJsInputCodeInFirefox:new K.default.Flag,autoSaveDownloadFileFireFox:new K.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new K.default.Flag(!0),experimentalPreCodeCompilation:new K.default.Flag(!0),experimentalAsyncCustomCode:new K.default.Flag,useSameBrowserForMultiTests:new Zo("labs"),highSpeedMode:new Zo,usePortedHtml5DragDrop:new K.default.Flag,testNamesToBeforeSuiteHook:new K.default.Flag,addCustomCapabilities:new K.default.Variant("{}"),enableWorkerThreadsCliCodeExecution:new K.default.Flag(!0),LTNetworkCapabilities:new K.default.Flag,downloadToBase64:new K.default.Flag,dec2022eolBrowsers:new K.default.Flag,publicGridURL:new K.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new K.default.Flag(!0),unsupportedCapsFields:new K.default.Variant("[]")},K.default.register("default",this.flags)}setProjectId(e){K.default.setCustomStringProperty("projectId",e)}setProjectType(e){K.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){K.default.setCustomStringProperty("productType",e)}setCompanyId(e){K.default.setCustomStringProperty("companyId",e)}setPlanType(e){K.default.setCustomStringProperty("planType",e)}setIsPOC(e){K.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){K.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){K.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!cv)return;let e={fetchIntervalInSec:uv,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return te(K.default.setup(Hd,e),lv).catch(t=>af.error("failed to get feature flag status",t))}},M=new Bl});var lf,uf,Zt,df,pf,cf,dv,pv,ei,mv,fv,ee,ti=T(()=>{"use strict";lf=E(require("ms")),uf=E(require("p-retry")),Zt=E(require("os")),df=E(require("portfinder")),pf=E(require("child_process"));U();Rt();Te();q();j();Wo();ae();ye();cf=I("lambdatestService"),dv="https://downloads.lambdatest.com/tunnel/v3",pv={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"},ei=`${Zt.tmpdir()}/LT`,mv=`${ei}/LT`,fv=(0,lf.default)("15m"),ee=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===ue.LAMBDATEST||e.type===ue.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ee.isLambdatestGrid(e)&&(ee.lambdatestConfigPromise||(ee.lambdatestConfigPromise=el()),ee.lambdatestConfig=await ee.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?fv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await be(mv))return;let t=pv[Zt.platform()+Zt.arch()];if(!t)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let s=`${ei}.zip`;await ze(`${dv}/${t}`,s),await tt(s,ei)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ee.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await df.getPortPromise(),{gridData:s={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;ee.tunnelName=z();let a=["--tunnelName",ee.tunnelName,"--infoAPIPort",String(t)];if(e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),s.tunnelUser&&s.tunnelKey)a=[...a,"--user",s.tunnelUser,"--key",s.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(i)try{let d=new URL(i);a=[...a,"--proxy-host",d.hostname],d.port&&(a=[...a,"--proxy-port",d.port]),d.username&&d.password&&(a=[...a,"--proxy-user",d.username,"--proxy-pass",d.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),ee.tunnel=pf.spawn("./LT",a,{cwd:ei});let c="",u="";ee.tunnel.stdout.on("data",d=>{c+=d.toString()}),ee.tunnel.stderr.on("data",d=>{u+=d.toString()});try{let d=await(0,uf.default)(()=>Tr(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});cf.info("LT tunnel info",d)}catch(d){throw cf.error("Failed to start LT tunnel",{err:d,stdoutResult:c,stderrResult:u}),d}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ee.tunnel))return new Promise((t,s)=>{ee.tunnel.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),ee.tunnel.kill()})}getCapabilities(e,t,s,n,o){if(!this.isActive)return{};let i=ee.lambdatestConfig.CAPABILITIES[t]||{},a={...ee.tunnelName&&{tunnel:!0,tunnelName:ee.tunnelName}},c=[],{mode:u,canary:d,ext:p,extensionPath:m,installCustomExtension:h}=e;if(u===J.EXTENSION&&!p){let f=Tl({canary:d},!0);!m&&f[t]&&(c=[...c,f[t]]),m&&Ge(m)&&(c=[...c,m])}return h&&Ge(h)&&(c=[...c,h]),{build:s,name:`${n} - ${o}`,platform:ee.lambdatestConfig.PLATFORM,selenium_version:ee.lambdatestConfig.SELENIUM_VERSION,resolution:ee.lambdatestConfig.RESOLUTION,timezone:ee.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled()}}}});var $l={};W($l,{connect:()=>si,disconnect:()=>ni,serveTunneling:()=>gv});var ri,mf,ff,hv,si,ni,gv,Wl=T(()=>{"use strict";ef();gn();nf();It();ri=E(require("ora"));j();ae();ti();mf=I("tunnel"),ff=r=>{var e;return[ue.LAMBDATEST,ue.HYBRID].includes((e=r.gridData)==null?void 0:e.type)&&r.gridData.tunnel==="lambdatest"},hv=r=>{var e;return r.tunnelRoutes||((e=r.gridData)==null?void 0:e.type)===ue.HYBRID&&r.gridData.tunnel==="cloudflare"},si=async r=>{if(!r.tunnel)return;let e=Ft(),t;try{ff(r)?(t=(0,ri.default)("Starting testim lambdatest tunnel...").start(),await ee.connectTunnel(r)):hv(r)?(t=(0,ri.default)("Starting testim cloudflare tunnel...").start(),await rf(r)):(t=(0,ri.default)("Starting testim ngrok tunnel...").start(),await Qm(r,e)),t.succeed()}catch(s){let n="Failed to start tunnel. Please contact support@testim.io";throw mf.error("Failed to open tunnel",{err:s}),t==null||t.fail(n),new Error(n)}},ni=async r=>{if(r.tunnel)try{ff(r)?await ee.disconnectTunnel(r):"tunnelRoutes"in r?await sf(r):await Zm(r)}catch(e){let t="catch error - failed to close tunnel";throw mf.error(t,{err:e}),new Error(t)}},gv=async(r,e=new Promise(()=>{}))=>(await si(r),ls(()=>ni(r)),await e)});function yv(r){if(r.protocol)return r.protocol;if([ue.TESTIM,ue.BROWSERSTACK,ue.SAUCELABS].includes(r.type)&&r.port===443)return"https";if([ue.TESTIM_ENTERPRISE,ue.LAMBDATEST,ue.DEVICE_FARM].includes(r.type)){let e=hf.exec(r.host);return(e==null?void 0:e[2])||"https"}return""}function bv(r){let e=hf.exec(r);return e==null?void 0:e[3]}function ii(r){var y,b,x,w,v,R,k,L,S;let e=r&&bv(r.host),t=r==null?void 0:r.port,s=r==null?void 0:r.path,n=r&&yv(r),o=r==null?void 0:r.token,i=r==null?void 0:r.slotId,a=(y=r==null?void 0:r.hybrid)==null?void 0:y.tunnel,c=(b=r==null?void 0:r.external)==null?void 0:b.user,u=(x=r==null?void 0:r.external)==null?void 0:x.key,d=r==null?void 0:r.type,p=d===ue.HYBRID?a&&((R=(v=(w=r.hybrid)==null?void 0:w.external)==null?void 0:v[r.hybrid.tunnel])==null?void 0:R.user):c,m=d===ue.HYBRID?a&&((S=(L=(k=r.hybrid)==null?void 0:k.external)==null?void 0:L[r.hybrid.tunnel])==null?void 0:S.key):u,h=r==null?void 0:r.name,f=r&&(r._id||r.gridId),g=r==null?void 0:r.provider;return{host:e,port:t,path:s,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:u,type:d,name:h,provider:g,tunnelUser:p,tunnelKey:m}}async function yf(r,e,t,s,n){let o;try{o=await n()}catch(i){throw Xe.error("failed to get grid",{projectId:r,companyId:e,err:i}),new Error(Zr.UNKNOWN)}if(Xe.info("get grid info",Object.assign({},o,{projectId:r,companyId:e})),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error(Zr.UNKNOWN);if(o.status==="success"){let i=ii(o.grid);return wv(t,e,i.gridId,i.slotId,s),i}throw o.code==="not-found"?new ut(Zr.NOT_FOUND):o.code==="no-available-slot"?new hr(`Failed to run test on ${s} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new ut(Zr.UNKNOWN))}function Tv(r,e,t,s,n,o){return yf(t,e,r,n,()=>Mo(e,t,s,n,o))}function vv(r,e,t,s,n,o,i){return yf(t,e,r,n,()=>{var u;let c=(u=i.allGrids)==null?void 0:u.find(d=>(d.name||"").toLowerCase()===s.toLowerCase());return c!=null&&c._id?Mo(e,t,c._id,n,o):Yc(e,t,s,n,o)})}function bf(r){return Zc(r)}async function wf(r,e,t){let n=(t||await bf(r)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return ii(n)}async function Ev(r,e,t){let n=(t||await bf(r)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return ii(n)}async function Gl(r,e){let t=Tn[r];if(!t)return;let{slotId:s,gridId:n,browser:o,companyId:i}=t;if(delete Tn[r],!s){Xe.warn("failed to find grid slot id",{projectId:e});return}Xe.info("release slot id",{projectId:e,companyId:i,slotId:s,gridId:n,browser:o});try{await Jc(i,e,s,n,o)}catch(a){Xe.error("failed to release slot",{projectId:e,err:a})}}async function Sv(r){let e=Object.values(Tn).filter(Boolean);if(e.length!==0){Xe.info("keep alive worker slots",{projectId:r,slots:e});try{await Kc(r,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:r})}}}function Rv(r){gf=global.setInterval(Sv,1e4,r)}async function Iv(r){let e=Object.keys(Tn);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:r});try{await de(e,t=>Gl(Number(t),r))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:r})}}}async function xv(r){await Iv(r),clearInterval(gf)}function Pv(r,e){let{testobjectSauce:t,saucelabs:s}=e;if(r==="testobject")return t.testobjectApiKey;if(r==="saucelabs")return s.accessKey}function Av(r,e){let{saucelabs:t}=e;if(r==="saucelabs")return t.username}function Tf(r){let t=(()=>oi.isEmpty(r.testobjectSauce)?oi.isEmpty(r.saucelabs)?oi.isEmpty(r.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:s,port:n,path:o,protocol:i}=r,a=Pv(t,r),c=Av(t,r);return{host:s,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function vf(r,e){let t=r.company.companyId;return await wf(t,e.gridId,r.allGrids)}async function Ef(r){let{allGrids:e=void 0,company:t,host:s,useLocalChromeDriver:n,useChromeLauncher:o,gridId:i,grid:a}=r;if(n||o)return{mode:"local"};if(s)return Tf(r);let c=t==null?void 0:t.companyId;if(i)return wf(c,i,e);if(a)return Ev(c,a,e);if(Xs(r)||r.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new ut("Missing host or grid configuration")}async function Sf(r,e,t,s){return await(async()=>{let{host:i,project:a,grid:c,gridId:u,useLocalChromeDriver:d,useChromeLauncher:p,company:m}=t,h=m==null?void 0:m.companyId;if(d||p)return{mode:"local"};if(i)return Tf(t);if(u)return Tv(s,h,a,u,r,e);if(c)return vv(s,h,a,c,r,e,t);throw new ut("Missing host or grid configuration")})()}var oi,Xe,Tn,hf,gf,wv,vn,Rf,hs=T(()=>{"use strict";oi=E(require("lodash"));Te();j();U();ae();q();Xe=I("grid-service"),Tn={},hf=/(^(https?):\/{2})?(.*)/,gf=null;wv=(r,e,t,s,n)=>{Tn[r]={gridId:t,companyId:e,slotId:s,browser:n}};vn={start:Rv,end:xv};Rf=async(r={},e={},t={},s={},n={})=>{var f,g,y;let{company:{companyId:o}={}}=r,{gridId:i,type:a}=e,c=r.browser||t.browserValue,u=Boolean(r.tunnel),{maxRetries:d,currentRetry:p}=n;if(!i||!a||(a===ue.LAMBDATEST&&await((f=s.enableIfNeeded)==null?void 0:f.call(s,e)),a!==ue.HYBRID||!o||!c||!d||!p))return e;let m=await Xc({companyId:o,gridId:i,maxRetries:d,currentRetry:p,browser:c,usingTunnel:u});Xe.info("handling hybrid grid",{response:m,companyId:o});let h=ii({...e,...m.connectionDetails,provider:m.provider});return m.provider!=="lambdatest"&&((g=s.disable)==null||g.call(s)),m.provider==="lambdatest"&&await((y=s.enableIfNeeded)==null?void 0:y.call(s,h)),h}});function Sn(){return ai||"master"}function If(r="master",e="false"){if(typeof r!="string"&&(r!=null&&r.branch)&&r.branch==="master"){ai="master";return}if(r&&!r.isArchived){ai=r.branch||r;return}ai=e?"master":void 0}var ai,Vl=T(()=>{"use strict"});var Rn,ql,Cv,Hl,kv,zl,ci,li,ui,di,pi,mi=T(()=>{"use strict";U();ae();Rn=r=>{let{status:e,sessionType:t,success:s,mobile:n}=r;return n!=null&&n.isAppFromDevice||n!=null&&n.isAppForIosVirtualDevice?!1:e===pe.FAILED||t===Nt.CODEFUL&&s===!1},ql=r=>{let{status:e}=r;return e===pe.ABORTED},Cv=r=>{let{status:e,sessionType:t,success:s}=r;return e===pe.PASSED||t===Nt.CODEFUL&&s===!0},Hl=r=>r.runnerStatus===uc.SKIPPED,kv=r=>r.testStatus===Ke.EVALUATING,zl=(r,e)=>e?!r.runConfig:!1,ci=(r,e)=>Object.values(r).filter(t=>{var s,n;return Hl(t)&&Je(t,e||((s=t.mobile)==null?void 0:s.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,li=r=>Object.values(r).filter(e=>Rn(e)&&kv(e)).length,ui=(r,e)=>Object.values(r).filter(t=>Rn(t)&&!zl(t,e)),di=(r,e)=>Object.values(r).filter(t=>Cv(t)&&!zl(t,e)),pi=(r,e)=>Object.values(r).filter(t=>ql(t)&&!zl(t,e))});function _v(r){let e=r.indexOf("--token");if(e===-1&&(e=r.indexOf("--t")),e!==-1)try{let t=r.slice();return t.splice(e,2),t}catch{}return r}var fi,Pf,hi,Af=T(()=>{"use strict";j();mi();fi=I("debug-reporter"),Pf={token:void 0,userParamsData:void 0,projectData:void 0,allGrids:void 0,gridData:void 0,awsAccessKeyId:void 0,awsSecretAccessKey:void 0,runParams:void 0,perfecto:void 0,testobjectSauce:void 0},hi=class{constructor(e){this.options=e}onTestStarted(e,t){fi.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let s=this.options.gridData||{},n=s.provider,o=s.host,i=s.gridId,a=s.type,c=s.failedGetBrowserAttempts;fi.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}onTestPlanStarted(e,t,s,n,o,i,a){let c=_v(process.argv);fi.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:Object.assign({},this.options,Pf),args:c})}onTestPlanFinished(e,t,s,n,o,i){let a=di(e,i).length,c=Object.keys(e).length-a;fi.info("Test Plan Finished",{isAnonymous:o,passed:a,failed:c,testPlanName:t,options:Object.assign({},this.options,Pf),duration:s,executionId:n})}}});var Kl,Pt,In=T(()=>{"use strict";ae();Kl=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===ue.DEVICE_FARM}},Pt=new Kl});var Xl={};W(Xl,{Reporter:()=>Ov});var er,xn,_r,gi,Cf,Jl,Ov,Yl=T(()=>{"use strict";er=E(require("chalk")),xn=E(require("lodash"));U();ae();In();mi();_r={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:gi}=Dt,Cf="device",Jl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t,s,n){let o=n?"File":"Test",i=e.isTestsContainer?"":`(${e.testId})`,a=e.isTestsContainer?"":`url: ${er.default.underline(at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`${o} "${e.name}" started ${i} ${a}`.trim())}onTestFinished(e,t,s,n){if(n)return;let o=e.success?pe.PASSED:pe.FAILED,i=e.isTestsContainer?" ":`(${e.testId})`,a=_r[e.success?"success":"error"];console.log(a(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${o} ${i} duration: ${po(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(s=>{let n=at(this.options.editorUrl,this.options.project,s.testId,s.resultId,this.branchToUse);return s.isTestsContainer?s.name:`${s.name} : ${n}`});console.log(_r.error("Failed runs are:")),console.log(_r.error(t.join(`
|
|
27
|
-
\r`)))}onTestPlanFinished(e,t,s,n,o,i){let a=ui(e,i),c=di(e,i),u=pi(e,i),d=c.length,p=u.length,m=a.length,h="",f="";if(Pt.isTestStatusEnabled){let w=li(e);h=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${ci(e,this.options)}`}let g=this.buildTestPlanName(o,t,i),y,b=_r[m?"error":"success"],x=`PASSED: ${d} FAILED: ${m}${h} ABORTED: ${p}${f} Duration: ${po(s)}`;i||g.trim()===""||g.trim()==="Anonymous"?y=`Tests completed. ${x} (Execution ID: ${n})`:y=`Test plan${g} completed ${x} (${n})`,this.printWorkerDivider(),console.log(b(y)),this.printWorkerDivider(),this.printAllFailedTests(a)}buildTestPlanName(e,t,s){if(s)return"";let n=xn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,o=xn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=xn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,a=xn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,c=[i,o,n,a].filter(Boolean).join(", ");return e?` anonymous (${c})`:` '${t}'`}onTestPlanStarted(e,t,s,n,o,i,a,c){let u=m=>{m.forEach((h,f)=>{var b;let g=(b=h.testData)!=null&&b.index?`- ${h.testData.index} / ${h.testData.total} Data set`:"",y=c?"":`(${h.testId})`;console.log(" ",f+1,":",`${h.name}${Je(h,this.options)?"-quarantine":""}`,y,g)})},d=a?`config '${a}'`:"default configs";if(c)console.log(`Run test plan, Project: ${this.options.project} (Execution ID: ${o}):`);else{let m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",h=`${d}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${h} (${o})`)}this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),u(e)),console.log(c?"File list:":"Test list:"),u(t),s.length>0&&(console.log("After all:"),u(s)),this.printWorkerDivider()}onGetSlot(e,t){let s=this.options.grid||this.options.gridId,n=this.options.mode===gi.APPIUM?Cf:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(s)}`)}onGetSession(e,t,s){let n=s===gi.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,t,s){let n=t?"file":"test";console.log(this.toWorkerIdPrefix(e),`Wait for ${n} complete`),s&&t&&console.log(this.toWorkerIdPrefix(e),`Chrome Debugger available at ${s}`)}onGetBrowserFailure(e,t,s){if(s!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===gi.APPIUM?"device":"browser";if(n)console.log(_r.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(_r.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===gi.APPIUM?"Appium":"Selenium";console.log(_r.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Ov=Jl});var eu={};W(eu,{Reporter:()=>Uv});function Lv(r){let e=r.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function Nv(r){return r.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${r.visitedUrlsList||""}`}function Dv(r){return`${r.visitedUrlsJson||""}`}async function Mv(r,e,t,s,n,o){function i(m){let h=at(r,t,m.testId,m.resultId,s),f={$:{name:Lv(m),classname:n,time:gc(m.duration),ownedBy:m.testOwnerName,ownerEmail:m.testOwnerEmail},"system-out":h};if(Rn(m)||ql(m)){let g=`Step Failed: ${m.failureReason||m.reason}`,y=Rn(m)?`${g} More info at: ${h}`:g;f.failure={$:{message:y}}}return Hl(m)&&Je(m,o)&&Pt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=Nv(m),f["visited-urls-json"]=Dv(m)),f}function a(m){let{results:h,testPlanName:f,configName:g}=m,y=h||{},x={name:(g&&f?`${f} with config '${g}'`:f)||"selenium run",tests:u(y),failure:d(y),timestamp:c(e)};if(Pt.isTestStatusEnabled){x.skipped=ci(y,o);let w=li(y);x.failure-=w,x["failure-evaluating"]=w}return{$:x,testcase:Object.keys(y).map(w=>i(y[w]))}}function c(m){let h=Object.keys(m).map(g=>m[g].startTime),f=Math.min.apply(null,h);return f?new Date(f).toISOString():new Date().toISOString()}function u(m){return Object.keys(m).length}function d(m){return ui(m).length+pi(m).length}let p={testsuites:{testsuite:e.map(m=>a(m))}};try{return new Zl.Builder().buildObject(p)}catch(m){return Fv(m)}}function Fv(r){let e=new Zl.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:r.message}}}}}};return e.buildObject(t)}var Zl,kf,Ql,Uv,tu=T(()=>{"use strict";Zl=E(require("xml2js"));U();kf=require("fs");In();mi();Ql=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,s=this.options.project,n=await Mv(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await kf.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)}};Uv=Ql});var _f={};W(_f,{Reporter:()=>jv});function gs(r){return r?r.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var ru,su,jv,Of=T(()=>{"use strict";j();ru=I("team-city-reporter");su=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${s}`;return gs(n)}onTestStarted(e,t,s,n,o){if(s){ru.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${o}']`)}onTestFailed(e,t,s,n,o,i){if(o){ru.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${gs(t)}' details='${gs(s)}' flowId='${i}']`)}onTestFinished(e,t,s){if(s){ru.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,s="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${gs(s)}']`)}onTestPlanStarted(e,t,s,n){console.log(`##teamcity[testSuiteStarted name='${gs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${gs(t)}']`)}},jv=su});var Lf={};W(Lf,{Reporter:()=>Bv});var nu,Bv,Nf=T(()=>{"use strict";nu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,s,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},Bv=nu});var Df={};W(Df,{Reporter:()=>$v});var ou,$v,Mf=T(()=>{"use strict";U();vl();ou=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e,t,s,n){if(n)return;let o=at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Vo(o)}},$v=ou});var Wv,iu,Q,Bt=T(()=>{"use strict";Af();j();Wv=I("reporter"),iu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let s=e.reporters;if(this.reporters.push(new hi(e)),s===void 0||s.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Yl(),Xl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(tu(),eu));this.reporters.push(new o(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(Of(),_f)),s.includes("console")&&Promise.resolve().then(()=>(Yl(),Xl)),s.includes("junit")&&Promise.resolve().then(()=>(tu(),eu)),s.includes("json")&&Promise.resolve().then(()=>(Nf(),Lf)),s.includes("chrome")&&Promise.resolve().then(()=>(Mf(),Df))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,n,o,i,a){let c={};if(a){let d=Object.values(a);if(d.length>0){for(let p of Object.values(a))c[p.id]=p;for(let p of Object.keys(e))d.some(m=>m.parentResultId!==p)||(c[p]=e[p])}else Wv.warn("childTestResults is not array"),c=e}else c=e;let u=Date.now()-(s||0);return[c,t,u,n,o,i,void 0]}onAllTestPlansFinishedMutator(e){for(let t of e)if(t.childTestResults){t.results={};let s=Object.values(t.childTestResults);for(let n of s)t.results[n.id]=n;for(let n of Object.keys(e))s.some(o=>o.parentResultId!==n)||(t.results[n]=e[n])}return[e]}generateHook(e,t){return async(...s)=>{var o;let n=t==null?void 0:t(...s);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||s))}}},Q=new iu});function Uf(r,e){return e!=null&&e.type&&(r[`${e.type}Mode`]=!0),r}function jf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:u,user:d,lightweightMode:p,isStartUp:m,projectType:h,appSource:f}){let g=Uf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:Ff(u,d),isStartUp:m,projectType:h,...["android","ios"].includes(h)&&f&&{appSource:f}},p);ht("test-run-ci",g)}function Bf({executionId:r,projectId:e,testId:t,resultId:s,result:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:u,source:d,user:p,lightweightMode:m,logger:h,isStartUp:f,projectType:g,appSource:y}){try{let b=Uf({executionId:r,projectId:e,testId:t,resultId:s,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:u,mockNetworkEnabled:n.wasMockNetworkActivated,source:Ff(d,p),isStartUp:f,projectType:g,...["android","ios"].includes(g)&&y&&{appSource:y}},m);if(n.success){ht("test-run-ci-success",b);return}ht("test-run-ci-fail",Object.assign({},b,{failureReason:n.failureReason}))}catch(b){h.error("failed to update test end analytics",{err:b})}}function $f({executionId:r,projectId:e,sessionType:t}){ht("batch-run-ci",{executionId:r,projectId:e,sessionType:t})}var Ff,au=T(()=>{"use strict";ds();Lo();Ff=(r,e)=>r!=="cli"&&r!=="cli-local"?r:as&&e?"ci-with-user":as?"ci":e?"cli-with-user":r});var Gv,Gf=T(()=>{"use strict";Gv=require("istanbul-lib-report")});var Vf,qf,Vv,Hf,Or,qv,zf,cu,Hv,Kf,Jf=T(()=>{"use strict";Vf=E(require("ora")),qf=E(require("moment")),Vv=E(require("test-exclude")),Hf=E(require("fs")),Or=E(require("path")),qv=E(require("istanbul-reports")),zf=E(require("istanbul-lib-report"));Te();q();U();j();yt();Gf();cu=I("test-run-status"),Hv=async(r,e,t)=>{let{mergeProcessCovs:n}=await he("@bcoe/v8-coverage"),o={result:[]},i=new Map,c=(await mn(r,"testResult",`runId=${t}`)).data.docs;return await de(c.flatMap(u=>u.JSCoverageURLS||[]),async u=>{let d=await pn(u,9e4);await de(d,async p=>{if(!i.has(p.url)){let m=p.text;p.sourceUrl&&(i.set(p.url,"TEMP"),m=await(void 0)(p.sourceUrl)),i.set(p.url,{text:m,url:p.url,sourceMapType:p.sourceMapType,hash:p.hash})}delete p.text,o=n([o,{result:[p]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:o}},Kf=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;cu.info("start js coverage process");let n=(0,Vf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=Or.resolve(r.codeCoverageReportPath||"./coverage"),i=Or.resolve(o,`.js/${(0,qf.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?Or.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:u,covUrlMap:d}]=await Promise.all([he("istanbul-lib-coverage"),Hv(r.project,e,s)]);if(u.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}cu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:u.result.length});let p=c.createCoverageMap({}),m={};await de(u.result,async({url:f,functions:g})=>{let{text:y,sourceMapType:b}=d.get(f),x=await(void 0).getSourceMap({sourceMapType:b,url:f,source:y,sourceMapDir:a});m[f]=x;let w=await(void 0).convertV8ToIstanbul(r,{source:y,sourceMap:x,functions:g});p.merge(w)}),await(void 0).remapCoverage(r,i,m);let h=await(void 0).saveCoverageReports(r,p,o,i);return n.succeed(),h}catch(c){let u="Failed to report coverage information";c instanceof P?n.fail(`${u}, missing arg: ${c.message}`):n.fail(u),cu.error(u,{err:c})}}});var Xf={};W(Xf,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>$t});var Ae,$t,ys=T(()=>{"use strict";U();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},$t=class{constructor(){this.marks=Object.fromEntries(Object.values(Object.assign({ALL:"ALL"},Ae)).map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=z();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let s=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(s);return}this.marks[t].push(s)}getStats(){let e=Object.entries(this.marks).flatMap(([t,s])=>!Array.isArray(s)||!s.length?[]:[[`${t}_COUNT`,s.length],[`${t}_P50`,ho(s,50)],[`${t}_P95`,ho(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var eh={};W(eh,{initServer:()=>Jv,mapFilesToLocalDrive:()=>uu});function uu(r,e){var t;try{r.failurePath=(r.failurePath||[]).map(s=>Object.assign(s,yi[s.id]?{screenshot:yi[s.id]}:{})),Object.keys(bs).forEach(s=>{r.assets||(r.assets={}),r.assets[Zf[s]]=bs[s]}),r.assets||(r.assets={}),r.assets.screenshots=Object.values(yi)}catch(s){e&&e.error("failed to map files to local drive",{err:s}),r.failurePath||(r.failurePath=[]),r.assets||(r.assets={}),(t=r.assets).screenshots||(t.screenshots=[])}}async function Jv({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await he("multer"),n=typeof t=="string"?t:zv;await lu.promises.mkdir(n,{recursive:!0});let o=s({storage:s.diskStorage({async destination(c,u,d){let p=JSON.parse(c.body.metadata||"{}");if(!p.testResultId)return d(new Error("missing testResultId"),"");let m=Pn.join(n,p.testResultId);try{await lu.promises.mkdir(m,{recursive:!0})}catch(h){return d(h,"")}return d(null,m)},filename(c,u,d){let{fileName:p}=c.body,m=JSON.parse(c.body.metadata||"{}");if(!m.stepId&&!p)return d(new Error("missing stepId or fileName"),"");if(m.stepId){let h=Pn.extname(p);return d(null,`step_${m.stepId}_${m.stepName||""}${h}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,p)}})}),i=(0,Qf.default)();i.post("/",o.single("file"),(c,u)=>{var p;let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(yi[d.stepId]=c.file.path),d.testResultId&&Kv.includes(d.subType)&&(bs[p=d.subType]||(bs[p]=[]),bs[d.subType].push(c.file.path)),u.sendStatus(200)}),i.use((c,u)=>u.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,u)=>{let d=a(i);d.listen(r,e),d.on("error",p),d.on("listening",()=>c(d.address()));function p(m){if(m.syscall!=="listen")return u(m);switch(m.code){case"EACCES":case"EPERM":return u(new P(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return u(new P(`Port ${r} is already in use`));default:return u(m)}}})}var lu,Yf,Pn,Qf,zv,yi,bs,Zf,Kv,du=T(()=>{"use strict";lu=E(require("fs")),Yf=E(require("os")),Pn=E(require("path")),Qf=E(require("express"));q();yt();zv=Pn.join(Yf.tmpdir(),"testim/rca/"),yi={},bs={},Zf={"test-log":"consoleLogs","har-file":"networkLogs"},Kv=Object.keys(Zf)});var tr,pu,bi,th=T(()=>{"use strict";tr=E(require("lodash"));U();j();pu=I("override-test-data-builder"),bi=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}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)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(s=>this.overrideSingleTest(s,e.overrideTestData[s])),delete e.overrideTestData):pu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):pu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}pu.error("skip override test data to test name",{testName:e,projectId:s}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let s=this.mapTestListToUniqueId(e);if(s.length!==0)return this.createNewTestPerOverrideTestData(s,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return tr.chain(t).map(s=>{if(s.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(s)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:s}=this;return[...new Set(e)].map(n=>{let o=s.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),c=s[i],u=this.createNewTestItems(c,t);return s.splice(i,a-i+1,...u)})}createNewTestItems(e,t){return[].concat(t).map((s,n)=>{let o=z();return Object.assign({},e,{resultId:o,testData:{value:s,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function wi(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw ot.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Lr,ot,Xv,Yv,Qv,Zv,Ti,rh=T(()=>{"use strict";Lr=E(require("lodash"));U();ae();hs();Te();q();j();Bt();gn();Jf();ys();du();le();ye();th();In();ot=I("test-run-status"),Xv=Rr(),Yv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Qv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Zv=ct();Ti=class{constructor(e,t,s,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new $t;var a,c,u,d,p;(a=this.options).runParams||(a.runParams={}),this.fileUserParamsData=this.options.userParamsData;let o=Js(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:oo||t.parallel||1,browser:o,gitBranch:Xv,gitCommit:Yv,gitRepoUrl:Qv,runnerVersion:Zv,gridHost:t.host||((c=t.gridData)==null?void 0:c.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:s,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(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||((u=t.gridData)==null?void 0:u.gridId),gridName:t.grid||((d=t.gridData)==null?void 0:d.name),gridType:(p=t.gridData)==null?void 0:p.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:Er(t)},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:s,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,isTestsContainer:u,testId:d,name:p,testStatus:m,testCreatorName:h,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:y,testLabels:b,testSuites:x,allLabels:w}=a,v={originalTestResultId:t,previousTestResultId:s,config:Lr.cloneDeep(c),testId:d,status:"QUEUED",name:p,resultId:e,isTestsContainer:u,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},v,{testCreatorName:h,testCreatorEmail:f,testOwnerName:g,testOwnerEmail:y,testLabels:b,testSuites:x,allLabels:w}),il({projectId:n,runId:o,testId:d,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:v})}getAllTestResults(){return this.testRunStatus}testStart(e,t,s,n){let o=this.getTestResult(s);o.workerId=e;let i=this.options.files.length>0;return Q.onTestStarted(o,e,n,i,s),o}async updateTestStatusRunning(e,t,s){var u;let{project:n,remoteRunId:o,projectData:i}=this.options;if((u=this.options.lightweightMode)!=null&&u.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Fo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){ot.error("failed to upload test data artifact (runner)",{err:d})}let c=Lr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,cs(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:s})}async testStartReport(e,t,s){if(Je(e,this.options))return;let n=this.exportsGlobal;try{let o=await wi(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw ot.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,n,o){let i=this.testStart(e,t,s,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),ot.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,n){let{name:o,testId:i,testStatus:a}=s,{resultId:c,success:u}=t;if(a===Ke.EVALUATING&&Pt.isTestStatusEnabled){Q.onTestIgnored(e,s,`test in ${Ke.EVALUATING} status`);return}if(u){Q.onTestPassed(o);return}Q.onTestFailed(s,s.failureReason,at(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);Q.onTestIgnored(e,s,`test in ${Ke.QUARANTINE}`)}testEnd(e,t,s,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&uu(i,ot),i.resultUrl=at(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||(t.testId=i.testId),t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o);let c=this.options.files.length>0;Q.onTestFinished(i,e,o,c);let u=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=u,i}async testEndReport(e,t,s,n){var i;let o=s.exportsGlobal;try{try{await wi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){ot.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 cs(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw ot.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,n,o,i){let a=this.testEnd(e,t,s,n,o);return this.testEndReport(a,s,t,i)}calcTestRunStatus(){let{options:e,testInfoList:t}=this,s=e.company.companyId,n=t.map(o=>{var p,m,h,f;let i=e.browser?tn(e.browser,e.saucelabs,e.browserstack):o.runConfig;if(i&&M.flags.dec2022eolBrowsers.isEnabled()&&((p=en(i.browserValue))!=null&&p.eol))throw new P(`Unsupported Browser: ${i.browserName}`);let a=!M.flags.allowAppFromDeviceRuns.isEnabled()&&Ys(o.nativeApp),c=Qs(e)&&(es(o.nativeApp)||a),u=Je(o,e)||c,d={testId:o.testId,status:u?pe.SKIPPED:pe.QUEUED,name:o.name,resultId:o.resultId,isTestsContainer:o.isTestsContainer,testStatus:o.testStatus||Ke.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...c&&{reason:es(o.nativeApp)?"virtual-build":"app-from-device"},config:Object.assign({},this.execConfig,{companyId:s,testData:((m=o.testData)==null?void 0:m.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((h=o.testData)==null?void 0:h.total)||null,testDataIndex:((f=o.testData)==null?void 0:f.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,d]});return Object.fromEntries(n)}async executionStart(e,t,s,n,o){ot.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;ls(()=>Promise.all([vn.end(t),Do("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=s||Date.now();let u={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},d=await wi(i.beforeSuite,u),p=new bi(d,Lr.cloneDeep(this.testInfoList),t);this.testInfoList=p.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=d;let{testInfoList:m}=this,h=[],f=[],g=[];for(let b of m){if(b.isBeforeTestPlan){h.push(b);continue}if(b.isAfterTestPlan){g.push(b);continue}f.push(b)}let y=async()=>{let b=Lr.cloneDeep(this.testRunStatus);await de(Object.keys(b),async R=>{var A;let k=b[R],L=(A=k.config)==null?void 0:A.testData,S=k.testId,O=await Fo(t,S,R,L,c.defaults);O&&(delete k.config.testData,k.config.testDataUrl=O)});let x=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),w={executionId:e,projectId:t,labels:n||[],startTime:s,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:x,intersections:i.intersections},v=Wc(w);return this.executionStartedPromise=v,v.catch(R=>ot.error(R)),v};try{await y()}catch(b){ot.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:h,tests:f,afterTests:g}}concatSeleniumPerfMarks(e){Lr.chain(e).keys().each(t=>{let s=t;this.seleniumPerfStats.marks[s]&&(this.seleniumPerfStats.marks[s]=[...this.seleniumPerfStats.marks[s],...e[s]])}).value()}async executionEnd(e){var d;let t=bc(this.testRunStatus),s=t.length,n=0,o=0,i=0;for(let{status:p,testStatus:m}of t)p===pe.PASSED&&n++,p===pe.SKIPPED&&o++,p===pe.FAILED&&m===Ke.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await wi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:n,skipped:o})}catch(p){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),ot.warn("error while running afterSuite Hook",{err:p,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let u=await Kf(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:u}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Do("FINISHED",e,this.options.project,s===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(p){throw ot.error("Failed to update suite finished",{err:p}),p}}async markAllQueuedTests(e,t,s,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await $c(e,["QUEUED"],t,s,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=s,a.success=n}return this.testRunStatus}}});function tE(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function yu(r){return oh.readFileSync(r,{encoding:"base64"})}function ch(r,e,t){if(!(t!=null&&t.isLambdatestRun()&&Ge(r))&&r){let s=yu(r);ws.info(`adding extension: custom, path: ${r} length: ${s.length} hash: ${gu(s)} current extension count: ${e.length}`),e.push(s)}}function lh(r,e,t,s,n){if(n!=null&&n.isLambdatestRun())return;if(r.ext||s){let c=typeof r.ext=="string"?r.ext:`${__dirname}/..`,u=s||c,d=`--load-extension=${u}`;ws.info(`adding extension: testim unpacked , path: ${u}`),t.push(d);return}let o=r.canary?"-master.zip":".zip",i=hu.join(process.cwd(),`testim-headless${o}`),a=yu(i);ws.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${gu(a)} current extension count: ${e.length}`),e.push(a)}function rE(r,e,t,s,n,o,i){var g,y;let a=t.seleniumName||t.browserValue,c=[],u=[...ah];e.headless&&u.push("--headless");let d=()=>e.mode!==J.EXTENSION,p={prefs:{"profile.default_content_setting_values.popups":mu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":mu.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:d()};fu(n)&&(p.prefs["download.default_directory"]="C:\\Users\\testnode",p.w3c=!0,r.desiredCapabilities.version="latest-1",r.desiredCapabilities["aws:maxDurationSecs"]=2400,r.desiredCapabilities["aws:idleTimeoutSecs"]=60),fu(n)&&a==="MicrosoftEdge"&&(r.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(p.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(b=>u.push(`--${b}`)),e.chromeBlockLocation&&(p.prefs["profile.default_content_setting_values.geolocation"]=mu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&u.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&u.push("--disable-gpu"),Object.assign(r.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(p.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+dc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),ch(s,c,i),e.mode===J.EXTENSION&&lh(e,c,u,o,i),c.length>0&&(p.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(p.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),p.args=u;let h={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return ee.isLambdatestGrid(n)&&delete p.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(r.desiredCapabilities[h]=p),(e.w3cCapabilities||n.type==="testimEnterprise")&&(r.desiredCapabilities[`${f}:${h}`]=p),r}function nE(r,e,t){let s={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"browser.helperApps.neverAsk.saveToDisk":nh.join(","),"browser.helperApps.neverAsk.openFile":nh.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(r.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:s}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(r.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===J.EXTENSION)if(e.ext)r.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=hu.join(process.cwd(),`testim-firefox-profile${n}`);r.desiredCapabilities.firefox_profile=yu(o)}return e.headless&&(r.desiredCapabilities["moz:firefoxOptions"].args||(r.desiredCapabilities["moz:firefoxOptions"].args=[]),r.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),r}function oE(r,e,t){let{saucelabs:s}=r;return s!=null&&s.username&&s.accessKey?t?(t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=s.appiumVersion||t.sl.appiumVersion,Object.assign({},t.sl,s,{name:e})):Object.assign({},s,{name:e}):{}}function iE(r,e,t){return bt.isEmpty(r.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,r.browserstack,{name:e})):Object.assign({},r.browserstack,{name:e})}function aE(r){return r.perfecto?r.perfecto:{}}function cE(r,e,t){if(r.experitestToken){let s=e==="safari";return{accessKey:r.experitestToken,browserVersion:"latest",platformName:s?"MAC":"WIN10",seleniumScreenshot:s,newSessionWaitTimeout:t}}return{}}function lE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:n}=r,o=s||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=ja(o,i)),a}function vi(r,e,t,s,n,o,i,a=null){var g,y,b,x,w,v;if(s.mode==="local"){let R=[],k=[...ah],L={};return r.headless&&k.push("--headless"),r.silentDebuggerExtensionApi&&k.push("--silent-debugger-extension-api"),r.remoteDebuggingPort!==void 0&&k.push(`--remote-debugging-port=${r.remoteDebuggingPort}`),r.chromeExtraArgs&&r.chromeExtraArgs.forEach(S=>k.push(`--${S}`)),r.chromeBinaryLocation&&(L.binary=r.chromeBinaryLocation),r.mode!=="selenium"&&lh(r,R,k,null,a),ch(n,R,a),{logLevel:sh,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:k,extensions:R,...L},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:u}=r,d=lE(r,s),p={hostname:s.host,host:s.host,port:s.port||4444,path:s.path||"/wd/hub",protocol:s.protocol||"http",logLevel:sh,connectionRetryTimeout:c,connectionRetryCount:u,getSessionTimeout:Math.max(a.getSessionTimeout,r.getSessionTimeout),getSessionRetries:a.getSessionRetries||r.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!bt.isEmpty(d)&&{headers:d},...r.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};fu(s)&&(r.oldCapabilities=!1,r.w3cCapabilities=!0,p.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),r.disableNativeEvents&&(p.desiredCapabilities.nativeEvents=!1),s.user&&s.key&&(s.type==="saucelabs"&&(r.saucelabs||(r.saucelabs={}),(g=r.saucelabs).username||(g.username=s.user),(y=r.saucelabs).accessKey||(y.accessKey=s.key)),s.type==="browserstack"&&(r.browserstack||(r.browserstack={}),(b=r.browserstack)["browserstack.user"]||(b["browserstack.user"]=s.user),(x=r.browserstack)["browserstack.key"]||(x["browserstack.key"]=s.key))),s.key&&s.type==="perfecto"&&(r.perfecto.securityToken=s.key);let m=Number(r.browserTimeout/1e3),h=r.browser||(t==null?void 0:t.browserValue);bt.merge(p.desiredCapabilities,oE(r,e,t),iE(r,e,t),aE(r),cE(r,h,m),a==null?void 0:a.getCapabilities(r,h,o,i,e));let f=null;switch(!r.ext&&!r.extensionPath&&((w=s.host)!=null&&w.endsWith(".testim.io"))&&!r.canary&&r.mode===J.EXTENSION&&(h==="chrome"?f="/opt/testim-headless":h==="edge-chromium"&&(f="C:/selenium/testim-headless")),(v=s.host)!=null&&v.endsWith(".testim.io")&&h==="edge-chromium"&&(p.desiredCapabilities.version="83"),h){case"chrome":case"edge-chromium":p=sE(p,r,t,n,s,f,a);break;case"firefox":p=nE(p,r,a);break;case"safari":case"safari technology preview":p=tE(p,h);break;default:break}bt.merge(p.desiredCapabilities,r.seleniumCapsFileContent);try{let R={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},k=A=>A[s.provider]||A[p.host]||A[R[p.host]],L=A=>{var D,B;return k(A)||A[(D=p.desiredCapabilities)==null?void 0:D.browserName]||A[(B=p.desiredCapabilities)==null?void 0:B.version]||A||{}},S=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),O=L(L(S));Object.keys(O).length&&(ws.info(`Adding custom capabilities: ${JSON.stringify(O)}`),Object.assign(p.desiredCapabilities,O))}catch(R){ws.error("Failed to load custom capabilities",{error:R,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return p.desiredCapabilities&&!p.capabilities&&(eE(p.desiredCapabilities),p.capabilities={alwaysMatch:p.desiredCapabilities,firstMatch:[{}]},delete p.desiredCapabilities),p.hostname=p.host,p}function uh({projectType:r,gridInfo:e,nativeApp:t,options:s,appPath:n,androidActivityWait:o,sessionTags:i}){let{deviceModel:a,osVersion:c,deviceUdid:u,fullReset:d,resetAppData:p,resetOnSessionStartOnly:m}=s,h={};if(!t&&!n)throw Error("missing mobile app!");if(e.type!==ue.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid");let f={protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`,logLevel:s.appiumLogLevel},g={"headspin:capture":!0,"headspin:retryNewSessionFailure":!1,"headspin:sessionTags":i,...!d&&!p&&{"appium:noReset":!0},...!d&&p&&{"appium:noReset":!1}};switch(r){case"ios":g={...g,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...d&&{"appium:fullReset":d,"appium:resetOnSessionStartOnly":m},...t&&{"appium:bundleId":t.id},...n&&{"appium:app":n}};break;case"android":g={...g,platformName:"Android",...d&&{"appium:fullReset":d},...!d&&p&&{"appium:autoGrantPermissions":!0},"appium:automationName":"UiAutomator2","appium:appWaitActivity":o,...t&&{"appium:appPackage":t.id||t.packageName,"appium:appActivity":t.activity},...n&&{"appium:app":n}};break;default:throw Error(`unsupported mobile project ${r}`)}return a&&(h.model=a),c&&(h.os_version=c),u&&(h.device_id=u,delete h.model,delete h.os_version),bt.isEmpty(h)||(g["headspin:selector"]=h),{...f,desiredCapabilities:g,capabilities:g,connectionRetryCount:0}}var oh,hu,ih,bt,ws,sh,mu,ah,gu,fu,eE,sE,nh,Ei=T(()=>{"use strict";oh=E(require("fs")),hu=E(require("path")),ih=E(require("crypto")),bt=E(require("lodash"));U();le();j();ye();ae();ti();ws=I("testim-desired-capabilities-builder"),sh=no?"debug":"silent",mu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ah=["--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"],gu=(...r)=>ih.createHash("sha256").update(r.join("")).digest("hex"),fu=r=>r.type===ue.DEVICE_FARM||r.type===ue.HYBRID&&r.provider==="devicefarm",eE=r=>{Object.prototype.hasOwnProperty.call(r,"version")&&(r.browserVersion=r.version,delete r.version),Object.prototype.hasOwnProperty.call(r,"platform")&&(r.platformName=r.platform,delete r.platform),Object.prototype.hasOwnProperty.call(r,"acceptSslCerts")&&(r.acceptInsecureCerts=r.acceptSslCerts,delete r.acceptSslCerts),Object.prototype.hasOwnProperty.call(r,"unexpectedAlertBehaviour")&&(r.unhandledPromptBehavior=r.unexpectedAlertBehaviour,delete r.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(r,"chromeOptions")&&(r["goog:chromeOptions"]??(r["goog:chromeOptions"]=r.chromeOptions),delete r.chromeOptions);let e;try{e=M.flags.unsupportedCapsFields.getValue();let t=JSON.parse(e);if(!Array.isArray(t))return;t.forEach(s=>{delete r[s]})}catch{ws.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:e})}};sE=bt.memoize(rE,(r,e,t,s,n,o)=>{let i=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(bt.omit(e,"runParams")),c=JSON.stringify(t),u=JSON.stringify(n.type);return gu(i,a,c,s,u,o)}),nh=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(r){var e,t,s,n,o,i,a;return((e=r.message)==null?void 0:e.match(/Command not found/))||r.message==="HTTP method not allowed"||r.message==="Unknown error"||((t=r.message)==null?void 0:t.match(/Unknown timeout type/))||r.name==="unknown command"||((s=r.message)==null?void 0:s.match(/did not match a known command/))||((n=r.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=r.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=r.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=r.message)==null?void 0:a.match(/\.\w* is not a function/))}function dh(r,e,t){if(!e||!r)return r;if(r.includes("%"))return r.replace(/ /g,"%20");try{return decodeURI(r)!==r?r:encodeURI(r)}catch(s){return t&&t.warn("tried to encode url but failed",{err:s,url:r}),r}}async function ph(r){if(!Si||!Ri){let[e,t]=await Promise.all([import("got"),import("webdriverio/node_modules/webdriver/build/utils.js")]);[Si,Ri]=[e.RequestError,t.CustomRequestError]}return!Si||!Ri?!1:r instanceof Si||r instanceof Ri}var Si,Ri,wu=T(()=>{"use strict"});function Tu(r){function e(m){return m?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(m.nodeType):!1}function t(m){return m?s(m.parentNode,e):null}function s(m,h){for(let f=m;f&&f!==m.ownerDocument;f=f.parentNode)if(h(f))return f;return null}function n(m,h){for(let f=m;f&&f!==m.ownerDocument;f=t(f))if(h(f))return f;return null}function o(m,h){if(!m||!h)return null;m instanceof DocumentFragment&&(m=m.host);let g=window.getComputedStyle(m).getPropertyValue(h);if(g&&g!=="inherit")return g;let y=t(m);return o(y,h)}function i(m){let h=m.getBoundingClientRect();if(h.width>0&&h.height>0)return!0;if(m.tagName.toUpperCase()==="PATH"&&h.width+h.height>0){let g=o(m,"stroke-width");return!!g&&parseInt(g,10)>0}return o(m,"overflow")==="hidden"?!1:Array.from(m.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?i(g):!1)}function a(m){return o(m,"overflow")==="hidden"}function c(m){return!m||!a(m)||!m.childNodes.length?!1:Array.from(m.childNodes).every(h=>h.nodeType===Node.TEXT_NODE?!1:!e(h)||!i(h)?!0:c(h))}function u(m){var h;return m?(h=m.parentNode)!=null&&h.host?!0:u(m.parentNode):!1}if(!r||!u(r)&&!document.contains(r))return!1;switch(r.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let m=s(r,h=>h.tagName.toUpperCase()==="SELECT");return Tu(m)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(o(r,"visibility")!=="visible")return!1;let d=!!n(r,m=>Number(o(m,"opacity"))===0),p=!!n(r,m=>o(m,"display")==="none");return!(d||p||!i(r)||c(r))}var mh=T(()=>{"use strict"});var fh,hh,An,uE,dE,Ii,gh=T(()=>{"use strict";fh=E(require("promise-queue")),hh=E(require("webdriverio"));le();Oe();U();j();Bs();mh();wu();ys();An=I("WebDriverApi"),uE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},dE={implicit:0,pageLoad:1,script:2},Ii=class{seleniumPerfStats;client;get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){return this.capabilities&&"browserName"in this.capabilities&&this.capabilities.browserName.toLocaleLowerCase()||void 0}constructor(){this.w3cRequests={}}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}rejectWithLog(e,t){let{testName:s,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";return An.warn("error from selenium",{err:e,testResultId:n,testName:s,crashingFunc:o}),Promise.reject(e)}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof Ga<"u"&&(e=Ga);let t=1/0;this.queue=new fh.default(e,t)}async addToQueue(e){let t=this.seleniumPerfStats.markStart();try{return await this.queue.add(e)}catch(s){return this.rejectWithLog(s,e)}finally{this.seleniumPerfStats.markEnd(t)}}async initClient(e,t,s){var o,i;this.testName=t,this.testResultId=s,e.deprecationWarnings=!1,this.initQueueRequests(),_("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{An.info("requesting browser",{testResultId:s,testName:t}),_("before this.client.init"),this.client=await hh.remote(e)}),_("after client init")}finally{await((i=this.seleniumPerfStats)==null?void 0:i.markEnd(n,Ae.GET_BROWSER))}}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){return this.capabilities&&"platformName"in this.capabilities&&this.capabilities.platformName.toLocaleLowerCase()==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}execute(...e){return this.addToQueue(()=>{let t=e.shift();if(typeof t!="string"&&typeof t!="function")return Promise.reject(new Error("number or type of arguments don't agree with execute protocol command"));typeof t=="function"&&(t=`return (${t}).apply(null, arguments)`);let s=i=>{throw i.executedScript=t,i},n=()=>this.client.execute(t,e).catch(s),o=()=>this.client.executeScript(t,e).catch(s);return"execute"in this.w3cRequests&&this.w3cRequests.execute?n():(e=e.map(i=>{if(i===null){An.warn('The function "executeScript" in webdriverio can no longer expect "null" as an argument, it was replaced with "undefined"',{script:t,args:e});return}return i}),o().catch(i=>{if(Fe(i))return Object.assign(this.w3cRequests,{execute:!0}),n();throw i}))}).then(t=>({value:t}))}executeAsync(...e){return this.addToQueue(()=>{let t=e.shift();if(typeof t!="string"&&typeof t!="function")return Promise.reject(new Error("number or type of arguments don't agree with execute protocol command"));typeof t=="function"&&(t=`return (${t}).apply(null, arguments)`);let s=()=>this.client.executeAsync(t,e),n=()=>this.client.executeAsyncScript(t,e);return"executeAsync"in this.w3cRequests&&this.w3cRequests.executeAsync?s():n().catch(o=>{if(Fe(o))return this.w3cRequests.executeAsync=!0,s();throw o})}).then(t=>({value:t}))}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let s=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return s!=null&&s.targetInfos?s.targetInfos:[]}takeScreenshot(){var t;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ae.GET_SCREENSHOT);return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.takeScreenshot().then(n=>({value:n}))}).finally(()=>{var s;return(s=this.seleniumPerfStats)==null?void 0:s.markEnd(e,Ae.GET_SCREENSHOT)})}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ae.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_SCREENSHOT)}}getElementBySelector(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e)}).then(t=>({value:t}))}elementIdDisplayed(e){return this.addToQueue(()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),s=()=>this.execute(Tu,{ELEMENT:e,[Hr]:e});return"elementIdDisplayed"in this.w3cRequests&&this.w3cRequests.elementIdDisplayed?s():t().catch(n=>{if(Fe(n))return this.w3cRequests.elementIdDisplayed=!0,s();throw n})})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}url(e){return e?this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(dh(e,this.isSafari(),An))}):Promise.resolve()}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(()=>{let s=()=>{let o=[];return o[dE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});return"timeouts"in this.w3cRequests&&this.w3cRequests.timeouts?n():s().catch(o=>{if(Fe(o))return this.w3cRequests.timeouts=!0,n();throw o})})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(n,o){window.scrollTo(n,o)};return this.execute(s,e,t)}setValue(e,t){return this.elementIdClear(De(e)).then(()=>this.elementIdValue(De(e),t))}getViewportSize(e){return this.execute(uE).then(t=>typeof e=="string"&&e.match(/(width|height)/)?(e=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`,t.value[e]):{width:t.value.screenWidth||0,height:t.value.screenHeight||0})}keys(e){let t=i=>Fa.hasOwnProperty(i)?[Fa[i]]:i.split(""),s=[];if(typeof e=="string")s=t(e);else if(e instanceof Array)for(let i of e)s=s.concat(t(i));else return Promise.reject(new Error("number or type of arguments don't agree with keys protocol command"));let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:s})},o=()=>{let i=s.map(c=>({type:"keyDown",value:c})),a=s.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};return this.w3cRequests.keys?o():this.addToQueue(()=>n().catch(i=>{if(Fe(i))return this.w3cRequests.keys=!0,o();throw i}))}elementIdValue(e,t){return t=Array.isArray(t)?t.join():t,this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.elementSendKeys(e,t)}).then(s=>({value:s}))}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(De(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),s=await t.$('button[type="submit"]');return await s.isExisting()?s.click():(await t.$("input:last-of-type")).keys("Enter")})}findElementAndPress(e,t,s,n){return this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:t,y:s,button:n})}).then(o=>({value:o}))}rightClick(e,t,s){return this.findElementAndPress(e,t,s,"right")}leftClick(e,t,s){return this.findElementAndPress(e,t,s,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}actions(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.performActions(e)}).then(t=>({value:t}))}doDoubleClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).doubleClick()}).then(t=>({value:t}))}dragAndDrop(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e).dragAndDrop(t)}).then(s=>({value:s}))}buttonDown(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.buttonDown()}).then(e=>({value:e}))}buttonUp(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.buttonUp()}).then(e=>({value:e}))}moveTo(e,t,s){let n={};return typeof t=="number"&&(n.xOffset=t),typeof s=="number"&&(n.yOffset=s),this.isSafari()&&!n.hasOwnProperty("yoffset")&&(n.yOffset=1),this.isSafari()&&!n.hasOwnProperty("xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}uploadFile(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.uploadFile(e)}).then(t=>({value:t}))}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()})}windowHandleSize(e){return this.addToQueue(()=>{let t=async()=>await this.client.getWindowSize(),s=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let n=Math.abs(e.width),o=Math.abs(e.height);t=async()=>await this.client.setWindowSize(n,o),s=async()=>await this.client._setWindowSize(n,o)}return this.w3cRequests.windowHandleSize?t():s().catch(n=>{if(Fe(n))return this.w3cRequests.windowHandleSize=!0,t();throw n})}).then(t=>({value:t}))}setCookie(e,t,s,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getCookies(e).then((s=[])=>s||(typeof e=="string"?null:[]))})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){if(this.w3cRequests={},!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.w3cRequests={},!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}isAppInstalled(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.isAppInstalled(e)}).then(t=>{let s=!!t.value;return An.info(`is app (${e}) installed? ${s}`,t),s})}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 yh,bh=T(()=>{"use strict";yh=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let n=r.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(m){function h(x,w,v){return v>x&&v<w}let f=m.pointerPosition||{},g=s.getBoundingClientRect(),y=f.originX&&h(g.left,g.left+g.width,f.originX)?f.originX:g.left+g.width/2,b=f.originY&&h(g.top,g.top+g.height,f.originY)?f.originY:g.top+g.height/2;return{x:y,y:b}},a=function(m,h){return{screenX:0,screenY:0,clientX:m,clientY:h,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(m,h,f){if(!window.PointerEvent)return;let g=a(h,f);return new window.PointerEvent(m,g)},u=function(m,h,f){let g=document.createEvent("MouseEvents");return g.initMouseEvent(m,!0,!0,document.defaultView,1,0,0,h,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var h;let m=document.activeElement;for(;(h=m.shadowRoot)!=null&&h.activeElement;)m=m.shadowRoot.activeElement;return m},p=function(m){let h=i(m),f=m.event;return t.includes(f)?c(f,h.x,h.y):u(f,h.x,h.y)};try{n.map(h=>p(h)).filter(Boolean).forEach(h=>s.dispatchEvent(h));let m=d();dispatchFocus(r.elementToFocusLocatedElement,m),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(m){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:m.toString(),success:!1})}}});function Nr(r,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function s(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=s();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(r){let o=getLocatedElement(r);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var xi=T(()=>{"use strict"});var Eh={};W(Eh,{WebDriver:()=>Dr});async function hE(r){var e,t;try{let s=(t=(e=r==null?void 0:r.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return s?await mE(s):void 0}catch(s){Ve.info("Error getting cdpAddress",s);return}}var Ye,vh,Ve,rr,pE,wh,mE,sr,fE,Th,Dr,Cn=T(()=>{"use strict";Ye=E(require("lodash"));U();Oe();Ei();vh=E(require("ua-parser-js"));Bs();j();wu();gh();q();bh();xi();ye();ys();Ve=I("webdriver"),[rr,pE]=[0,2],{extractElementId:wh,getCdpAddressForHost:mE}=H,sr=()=>(Ee(),ie(kr)).getSessionPlayer().codeSnippets,fE=()=>(Ee(),ie(kr)).getSessionPlayer().locatorBuilderUtils,Th=()=>(Ee(),ie(kr)).getSessionPlayer().utils;Dr=class extends Ii{constructor(){super(),this.started=!1,this.keepAliveTimer=null,this.unsupportedActions={},this._isAlive=!1,this._keepAliveRequests=[],this.cdpUrl=void 0,this.browserClosedCallbacks=[],this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=!1}registerToClosedBrowser(e){this.browserClosedCallbacks.push(e)}unregisterToClosedBrowser(e){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(t=>t!==e)}async init(e,t,s,n,o,i,a,c=new $t,u=!1,d){var f,g,y,b,x,w,v,R;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=(y=(g=(f=e==null?void 0:e.company)==null?void 0:f.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.ignoreHiddenTagsText,this.browserClosedCallbacks=[];let p=vi(e,t,s,n,o,i,a,d);p.desiredCapabilities&&delete p.desiredCapabilities.marionette,p.capabilities&&delete p.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(d==null?void 0:d.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=c;let m=u?0:1500,h=u?()=>{}:()=>this.executeJS("window.focus()");try{_("before initClient in webdriver.js init");let k=await this.initClient(p,t,a);_("after initResult before getCdpAddress in init"),this.cdpUrl=await hE(k),_("after getCdpAddress in webdriver.js init"),Ve.info(`init new session testName: ${t}`,{sessionId:this.getSessionId(),testResultId:a}),await se(m),await h(),_("after focus and delay in webdriver.js init")}catch(k){Ve.error("failed to init webdriver",{err:k,capabilities:p});let L=((x=(b=e==null?void 0:e.company)==null?void 0:b.activePlan)==null?void 0:x.plan)==="free";throw(w=k.stack)!=null&&w.includes("at startWebDriverSession")&&((v=k.message)!=null&&v.startsWith("Failed to create session"))&&((R=k.message)!=null&&R.includes("Timeout awaiting 'request'"))&&L?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/capabilit(y|ies)/)?new Ws(k.message):new Error("failed to init client driver")}}initUnsupportedActions(e){e&&(this.unsupportedActions={...this.unsupportedActions,move:!0})}isAlive(){return this._isAlive}maxKeepAliveGap(){let e=n=>Ye.zip(Ye.dropRight(n,1),Ye.drop(n,1)),t=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),s=e(t).map(([n,o])=>o-n);return Math.max(...s)}async isClosedBrowserError(e){return["session-not-found","no such window"].includes(e==null?void 0:e.name)?!0:await ph(e)?["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(s=>e.message.includes(s)):!1}start(){if(this.started)return;this.started=!0;let e=async()=>{let t=i=>this._keepAliveRequests.push({start:Date.now(),id:i}),s=(i,a)=>{(this._keepAliveRequests.find(c=>c.id===a)||{})[i]=Date.now()};function n(){return window.getTestimStatus&&window.getTestimStatus()}if(this.queue.getQueueLength()>0)return;let o=z();t(o);try{await this.executeJS(n),this._isAlive=!0,s("end",o),this.browserClosedFailedKeepAlives=0}catch(i){if(s("error",o),i.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ve.warn("close unexpected alert open"),await this.alertAccept().catch(a=>Ve.warn("failed to click on alert",{err:a}));return}if(Ve.warn("err while getting testim status",{err:i}),this._isAlive=!1,await this.isClosedBrowserError(i)){this.browserClosedFailedKeepAlives++;let a=3;this.browserClosedFailedKeepAlives>=a&&this.browserClosedCallbacks.forEach(c=>{try{c(i)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(e,1e4)}switchToLocatedFrame(e){return this.getElement(e).then(async t=>{let s=wh(t.value);return await this.switchToFrame({ELEMENT:s,[Hr]:s}),t})}switchToFrame(e){return this.frame(e)}switchToTopFrame(){return this.frame().catch(e=>{var t;throw(t=e.message)!=null&&t.includes("ECONNREFUSED")?new Gs:e})}getElement(e){let t=this.seleniumPerfStats.markStart(Ae.GET_ELEMENT);return typeof e=="string"||typeof e=="number"?this.getElementBySelector(`[testim_dom_element_id='${e}']`).finally(()=>this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)):e&&e.shadowPath&&e.shadowPath.length||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari()?this.execute(`
|
|
25
|
+
${((I=n.warnings)==null?void 0:I.join(`
|
|
26
|
+
`))||""}`)}let i=(await(0,Ll.default)({type:"toggle",name:"isJs",message:"Add support for TypeScript?",initial:!0,active:"no",inactive:"yes"})).isJs?"template.js":"template.ts",a="codim",c=Yt.join(__dirname,a,i),u=Yt.join(process.cwd(),e),d=(0,Ol.default)(`Creating new test project in ${u}`).start();await lo(c,u);let p=Yt.join(__dirname,a,i,"package.json"),m=Yt.join(process.cwd(),e,"package.json"),f=(await Xt.promises.readFile(p)).toString().replace("~testim-codeful-test-project~",s);await Xt.promises.writeFile(m,f);let h="node_modules",y=Yt.join(process.cwd(),e,".gitignore");await Xt.promises.writeFile(y,h),d.succeed(),d=(0,Ol.default)("Installing dependencies").start(),await YT("npm install",{cwd:u}),d.succeed(),console.log(`Testim Dev Kit project folder successfully created in ${u}.`)}var Xt,Yt,$m,Ol,Ko,Ll,Wm,Gm,YT,qm=T(()=>{"use strict";Xt=E(require("fs")),Yt=E(require("path")),$m=E(require("child_process")),Ol=E(require("ora")),Ko=E(require("chalk")),Ll=E(require("prompts")),Wm=E(require("validate-npm-package-name")),Gm=require("util");q();lc();YT=(0,Gm.promisify)($m.exec)});var zm={};W(zm,{preloadTests:()=>wn});async function wn(r){if(!Array.isArray(r.testId)||!r.testId.length)return{};let e={branch:r.branch,projectId:r.project};return await ft(async()=>{let t=await de(r.testId,s=>jc({...e,testId:s}),{concurrency:2});return Hm.keyBy(t,"testData.id")},"loadTests",QT,[e,r.testId])()}var Hm,QT,Jo=T(()=>{"use strict";Hm=E(require("lodash"));Ht();Te();U();QT=1e3*60*60*10});function Dl(){return ct()}async function Ym(){if(!Le)try{let r=await te(ev(),5e3,"The API call to NPM timed out"),e=Dl();e&&Jm.lt(e,r)&&console.log(Km.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(r){ZT.warn("Failed to get NPM version",{err:r})}}var Km,Jm,ZT,ev,Nl=T(()=>{"use strict";Km=E(require("chalk")),Jm=E(require("semver"));U();le();nn();Ht();j();ZT=x("npm-driver"),ev=ft(()=>Bp("@testim/testim-cli"),"getNpmVersion")});var Ml,rv,fs,Xm,Qm,Fl,Zm,ef=T(()=>{"use strict";U();q();j();yt();Ml=x("testimNgrok"),rv=".whitelisted-ngrok.testim.io",fs="",Qm=async(r,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${z()}-${r.projectData.projectId}${rv}`);let s={proto:"http",addr:r.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};r.tunnelHostHeader&&(s.host_header=r.tunnelHostHeader),r.tunnelRegion&&(s.region=r.tunnelRegion);let o=await(await ge("ngrok")).connect(s);r.tunnelUseHttpAddress&&o.startsWith("https://")?(Ml.info("replace https to http"),fs=o.replace("https://","http://")):fs=o,r.tunnelDiagnostics&&Fl(),r.baseUrl=fs},Fl=async(r=!0)=>{try{let t=(await ge("ngrok")).getApi(),{tunnels:s}=await t.listTunnels(),n=s.find(o=>o.public_url===fs);console.log("ngrok stats",n),Ml.info("ngrok stats",{tunnel:n})}catch(e){Ml.error("error collecting ngrok stats",{err:e})}r&&(Xm=setTimeout(()=>Fl(),1e4))},Zm=async r=>{if(!fs)return;clearTimeout(Xm),r.tunnelDiagnostics&&await Fl(!1),await(await ge("ngrok")).disconnect(fs)}});var Qt,jl,tf,nv,ov,Ul,Yo,Qo,Xo,iv,rf,sf,nf=T(()=>{"use strict";Qt=E(require("os")),jl=E(require("fs")),tf=E(require("child_process"));U();Te();nv="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",ov={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"}},Ul=Qt.tmpdir(),Yo=`${Ul}/cloudflared`,Qo=null,Xo=null,iv=async()=>{if(await be(Yo))return;let e=ov[Qt.platform()+Qt.arch()];if(!e)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let t=e.extract?Ul+e.path:Yo;await ze(`${nv}/${e.path}`,t),e.extract&&await tt(t,Ul),await jl.promises.chmod(Yo,"755")},rf=async r=>{let e=r.baseUrl||`http://localhost:${r.tunnelPort||80}`,t="tunnelRoutes"in r&&r.tunnelRoutes||[e],[s]=await Promise.all([cl(r.company.companyId,t),iv()]);Qo=s._id,Xo=tf.spawn(Yo,["tunnel","--no-autoupdate","run","--force","--token",s.token],{stdio:"inherit"}),await ll(r.company.companyId,Qo),"tunnelRoutesOutput"in r&&r.tunnelRoutesOutput&&await jl.promises.writeFile(r.tunnelRoutesOutput,JSON.stringify(s.routesMapping,null,2)),r.baseUrl=`${r.tunnelUseHttpAddress?"http":"https"}://${s.routesMapping[e]}`},sf=async r=>{let e=[];return Qo&&e.push(ul(r.company.companyId,Qo)),Xo&&e.push(new Promise((t,s)=>{Xo.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),Xo.kill()})),await Promise.all(e)}});var K,af,cv,lv,uv,of,Zo,Bl,M,ye=T(()=>{"use strict";K=E(require("rox-node"));j();U();le();af=x("FeatureFlagsService"),cv=!Le&&!0&&!Kd,lv=2e4,uv=60*60*24,of=["labs","disabled","enabled"],Zo=class extends K.default.Variant{constructor(e="disabled"){super(e,of)}getValue(){let e=super.getValue();return of.includes(e)?e:(af.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Bl=class{constructor(){this.flags={useNewWSCLI:new K.default.Flag,useSafariWebdriverVisibilityChecks:new K.default.Flag,useClickimVisibilityChecks:new K.default.Flag,runGetElementCodeInAut:new K.default.Flag,enableFrameSwitchOptimization:new K.default.Flag,maximumJsResultSize:new K.default.Configuration(2e3*1024),skipFileInputClicks:new K.default.Flag,errorMessageOnBadNetwork:new K.default.Flag(!0),warnOnBadNetwork:new K.default.Flag(!1),overrideAzureStorageUrl:new K.default.Flag,useJsInputCodeInSafari:new K.default.Flag,useJsInputCodeInFirefox:new K.default.Flag,autoSaveDownloadFileFireFox:new K.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new K.default.Flag(!0),experimentalPreCodeCompilation:new K.default.Flag(!0),experimentalAsyncCustomCode:new K.default.Flag,useSameBrowserForMultiTests:new Zo("labs"),highSpeedMode:new Zo,usePortedHtml5DragDrop:new K.default.Flag,testNamesToBeforeSuiteHook:new K.default.Flag,addCustomCapabilities:new K.default.Variant("{}"),enableWorkerThreadsCliCodeExecution:new K.default.Flag(!0),LTNetworkCapabilities:new K.default.Flag,downloadToBase64:new K.default.Flag,dec2022eolBrowsers:new K.default.Flag,publicGridURL:new K.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new K.default.Flag(!0),unsupportedCapsFields:new K.default.Variant("[]")},K.default.register("default",this.flags)}setProjectId(e){K.default.setCustomStringProperty("projectId",e)}setProjectType(e){K.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){K.default.setCustomStringProperty("productType",e)}setCompanyId(e){K.default.setCustomStringProperty("companyId",e)}setPlanType(e){K.default.setCustomStringProperty("planType",e)}setIsPOC(e){K.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){K.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){K.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!cv)return;let e={fetchIntervalInSec:uv,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return te(K.default.setup(Hd,e),lv).catch(t=>af.error("failed to get feature flag status",t))}},M=new Bl});var lf,uf,Zt,df,pf,cf,dv,pv,ei,mv,fv,ee,ti=T(()=>{"use strict";lf=E(require("ms")),uf=E(require("p-retry")),Zt=E(require("os")),df=E(require("portfinder")),pf=E(require("child_process"));U();Rt();Te();q();j();Wo();ae();ye();cf=x("lambdatestService"),dv="https://downloads.lambdatest.com/tunnel/v3",pv={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"},ei=`${Zt.tmpdir()}/LT`,mv=`${ei}/LT`,fv=(0,lf.default)("15m"),ee=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===ue.LAMBDATEST||e.type===ue.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ee.isLambdatestGrid(e)&&(ee.lambdatestConfigPromise||(ee.lambdatestConfigPromise=el()),ee.lambdatestConfig=await ee.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?fv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await be(mv))return;let t=pv[Zt.platform()+Zt.arch()];if(!t)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let s=`${ei}.zip`;await ze(`${dv}/${t}`,s),await tt(s,ei)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ee.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await df.getPortPromise(),{gridData:s={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;ee.tunnelName=z();let a=["--tunnelName",ee.tunnelName,"--infoAPIPort",String(t)];if(e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),s.tunnelUser&&s.tunnelKey)a=[...a,"--user",s.tunnelUser,"--key",s.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(i)try{let d=new URL(i);a=[...a,"--proxy-host",d.hostname],d.port&&(a=[...a,"--proxy-port",d.port]),d.username&&d.password&&(a=[...a,"--proxy-user",d.username,"--proxy-pass",d.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),ee.tunnel=pf.spawn("./LT",a,{cwd:ei});let c="",u="";ee.tunnel.stdout.on("data",d=>{c+=d.toString()}),ee.tunnel.stderr.on("data",d=>{u+=d.toString()});try{let d=await(0,uf.default)(()=>Tr(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});cf.info("LT tunnel info",d)}catch(d){throw cf.error("Failed to start LT tunnel",{err:d,stdoutResult:c,stderrResult:u}),d}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ee.tunnel))return new Promise((t,s)=>{ee.tunnel.on("close",n=>{n&&s(new Error(`tunnel process exited with code ${n}`)),t()}),ee.tunnel.kill()})}getCapabilities(e,t,s,n,o){if(!this.isActive)return{};let i=ee.lambdatestConfig.CAPABILITIES[t]||{},a={...ee.tunnelName&&{tunnel:!0,tunnelName:ee.tunnelName}},c=[],{mode:u,canary:d,ext:p,extensionPath:m,installCustomExtension:g}=e;if(u===J.EXTENSION&&!p){let f=Tl({canary:d},!0);!m&&f[t]&&(c=[...c,f[t]]),m&&Ge(m)&&(c=[...c,m])}return g&&Ge(g)&&(c=[...c,g]),{build:s,name:`${n} - ${o}`,platform:ee.lambdatestConfig.PLATFORM,selenium_version:ee.lambdatestConfig.SELENIUM_VERSION,resolution:ee.lambdatestConfig.RESOLUTION,timezone:ee.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled()}}}});var $l={};W($l,{connect:()=>si,disconnect:()=>ni,serveTunneling:()=>hv});var ri,mf,ff,gv,si,ni,hv,Wl=T(()=>{"use strict";ef();hn();nf();It();ri=E(require("ora"));j();ae();ti();mf=x("tunnel"),ff=r=>{var e;return[ue.LAMBDATEST,ue.HYBRID].includes((e=r.gridData)==null?void 0:e.type)&&r.gridData.tunnel==="lambdatest"},gv=r=>{var e;return r.tunnelRoutes||((e=r.gridData)==null?void 0:e.type)===ue.HYBRID&&r.gridData.tunnel==="cloudflare"},si=async r=>{if(!r.tunnel)return;let e=Ft(),t;try{ff(r)?(t=(0,ri.default)("Starting testim lambdatest tunnel...").start(),await ee.connectTunnel(r)):gv(r)?(t=(0,ri.default)("Starting testim cloudflare tunnel...").start(),await rf(r)):(t=(0,ri.default)("Starting testim ngrok tunnel...").start(),await Qm(r,e)),t.succeed()}catch(s){let n="Failed to start tunnel. Please contact support@testim.io";throw mf.error("Failed to open tunnel",{err:s}),t==null||t.fail(n),new Error(n)}},ni=async r=>{if(r.tunnel)try{ff(r)?await ee.disconnectTunnel(r):"tunnelRoutes"in r?await sf(r):await Zm(r)}catch(e){let t="catch error - failed to close tunnel";throw mf.error(t,{err:e}),new Error(t)}},hv=async(r,e=new Promise(()=>{}))=>(await si(r),ls(()=>ni(r)),await e)});function yv(r){if(r.protocol)return r.protocol;if([ue.TESTIM,ue.BROWSERSTACK,ue.SAUCELABS].includes(r.type)&&r.port===443)return"https";if([ue.TESTIM_ENTERPRISE,ue.LAMBDATEST,ue.DEVICE_FARM].includes(r.type)){let e=gf.exec(r.host);return(e==null?void 0:e[2])||"https"}return""}function bv(r){let e=gf.exec(r);return e==null?void 0:e[3]}function ii(r){var y,b,I,w,v,R,k,L,S;let e=r&&bv(r.host),t=r==null?void 0:r.port,s=r==null?void 0:r.path,n=r&&yv(r),o=r==null?void 0:r.token,i=r==null?void 0:r.slotId,a=(y=r==null?void 0:r.hybrid)==null?void 0:y.tunnel,c=(b=r==null?void 0:r.external)==null?void 0:b.user,u=(I=r==null?void 0:r.external)==null?void 0:I.key,d=r==null?void 0:r.type,p=d===ue.HYBRID?a&&((R=(v=(w=r.hybrid)==null?void 0:w.external)==null?void 0:v[r.hybrid.tunnel])==null?void 0:R.user):c,m=d===ue.HYBRID?a&&((S=(L=(k=r.hybrid)==null?void 0:k.external)==null?void 0:L[r.hybrid.tunnel])==null?void 0:S.key):u,g=r==null?void 0:r.name,f=r&&(r._id||r.gridId),h=r==null?void 0:r.provider;return{host:e,port:t,path:s,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:u,type:d,name:g,provider:h,tunnelUser:p,tunnelKey:m}}async function yf(r,e,t,s,n){let o;try{o=await n()}catch(i){throw Ye.error("failed to get grid",{projectId:r,companyId:e,err:i}),new Error(Zr.UNKNOWN)}if(Ye.info("get grid info",Object.assign({},o,{projectId:r,companyId:e})),!o||!["success","error"].includes(o.status))throw Ye.error("invalid response - get grid",{res:o}),new Error(Zr.UNKNOWN);if(o.status==="success"){let i=ii(o.grid);return wv(t,e,i.gridId,i.slotId,s),i}throw o.code==="not-found"?new ut(Zr.NOT_FOUND):o.code==="no-available-slot"?new gr(`Failed to run test on ${s} - concurrency limit reached`):(Ye.error("invalid code error response - get grid",{res:o}),new ut(Zr.UNKNOWN))}function Tv(r,e,t,s,n,o){return yf(t,e,r,n,()=>Mo(e,t,s,n,o))}function vv(r,e,t,s,n,o,i){return yf(t,e,r,n,()=>{var u;let c=(u=i.allGrids)==null?void 0:u.find(d=>(d.name||"").toLowerCase()===s.toLowerCase());return c!=null&&c._id?Mo(e,t,c._id,n,o):Xc(e,t,s,n,o)})}function bf(r){return Zc(r)}async function wf(r,e,t){let n=(t||await bf(r)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return ii(n)}async function Ev(r,e,t){let n=(t||await bf(r)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return ii(n)}async function Gl(r,e){let t=Tn[r];if(!t)return;let{slotId:s,gridId:n,browser:o,companyId:i}=t;if(delete Tn[r],!s){Ye.warn("failed to find grid slot id",{projectId:e});return}Ye.info("release slot id",{projectId:e,companyId:i,slotId:s,gridId:n,browser:o});try{await Jc(i,e,s,n,o)}catch(a){Ye.error("failed to release slot",{projectId:e,err:a})}}async function Sv(r){let e=Object.values(Tn).filter(Boolean);if(e.length!==0){Ye.info("keep alive worker slots",{projectId:r,slots:e});try{await Kc(r,e)}catch(t){Ye.error("failed to update grid keep alive",{err:t,slots:e,projectId:r})}}}function Rv(r){hf=global.setInterval(Sv,1e4,r)}async function Iv(r){let e=Object.keys(Tn);if(e.length){Ye.warn("not all slots released before end runner flow",{projectId:r});try{await de(e,t=>Gl(Number(t),r))}catch(t){Ye.error("failed to release all slots",{err:t,projectId:r})}}}async function xv(r){await Iv(r),clearInterval(hf)}function Pv(r,e){let{testobjectSauce:t,saucelabs:s}=e;if(r==="testobject")return t.testobjectApiKey;if(r==="saucelabs")return s.accessKey}function Av(r,e){let{saucelabs:t}=e;if(r==="saucelabs")return t.username}function Tf(r){let t=(()=>oi.isEmpty(r.testobjectSauce)?oi.isEmpty(r.saucelabs)?oi.isEmpty(r.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:s,port:n,path:o,protocol:i}=r,a=Pv(t,r),c=Av(t,r);return{host:s,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function vf(r,e){let t=r.company.companyId;return await wf(t,e.gridId,r.allGrids)}async function Ef(r){let{allGrids:e=void 0,company:t,host:s,useLocalChromeDriver:n,useChromeLauncher:o,gridId:i,grid:a}=r;if(n||o)return{mode:"local"};if(s)return Tf(r);let c=t==null?void 0:t.companyId;if(i)return wf(c,i,e);if(a)return Ev(c,a,e);if(Ys(r)||r.tunnelOnlyMode){Ye.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new ut("Missing host or grid configuration")}async function Sf(r,e,t,s){return await(async()=>{let{host:i,project:a,grid:c,gridId:u,useLocalChromeDriver:d,useChromeLauncher:p,company:m}=t,g=m==null?void 0:m.companyId;if(d||p)return{mode:"local"};if(i)return Tf(t);if(u)return Tv(s,g,a,u,r,e);if(c)return vv(s,g,a,c,r,e,t);throw new ut("Missing host or grid configuration")})()}var oi,Ye,Tn,gf,hf,wv,vn,Rf,gs=T(()=>{"use strict";oi=E(require("lodash"));Te();j();U();ae();q();Ye=x("grid-service"),Tn={},gf=/(^(https?):\/{2})?(.*)/,hf=null;wv=(r,e,t,s,n)=>{Tn[r]={gridId:t,companyId:e,slotId:s,browser:n}};vn={start:Rv,end:xv};Rf=async(r={},e={},t={},s={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=r,{gridId:i,type:a}=e,c=r.browser||t.browserValue,u=Boolean(r.tunnel),{maxRetries:d,currentRetry:p}=n;if(!i||!a||(a===ue.LAMBDATEST&&await((f=s.enableIfNeeded)==null?void 0:f.call(s,e)),a!==ue.HYBRID||!o||!c||!d||!p))return e;let m=await Yc({companyId:o,gridId:i,maxRetries:d,currentRetry:p,browser:c,usingTunnel:u});Ye.info("handling hybrid grid",{response:m,companyId:o});let g=ii({...e,...m.connectionDetails,provider:m.provider});return m.provider!=="lambdatest"&&((h=s.disable)==null||h.call(s)),m.provider==="lambdatest"&&await((y=s.enableIfNeeded)==null?void 0:y.call(s,g)),g}});function Sn(){return ai||"master"}function If(r="master",e="false"){if(typeof r!="string"&&(r!=null&&r.branch)&&r.branch==="master"){ai="master";return}if(r&&!r.isArchived){ai=r.branch||r;return}ai=e?"master":void 0}var ai,Vl=T(()=>{"use strict"});var Rn,ql,Cv,Hl,kv,zl,ci,li,ui,di,pi,mi=T(()=>{"use strict";U();ae();Rn=r=>{let{status:e,sessionType:t,success:s,mobile:n}=r;return n!=null&&n.isAppFromDevice||n!=null&&n.isAppForIosVirtualDevice?!1:e===pe.FAILED||t===Dt.CODEFUL&&s===!1},ql=r=>{let{status:e}=r;return e===pe.ABORTED},Cv=r=>{let{status:e,sessionType:t,success:s}=r;return e===pe.PASSED||t===Dt.CODEFUL&&s===!0},Hl=r=>r.runnerStatus===uc.SKIPPED,kv=r=>r.testStatus===Ke.EVALUATING,zl=(r,e)=>e?!r.runConfig:!1,ci=(r,e)=>Object.values(r).filter(t=>{var s,n;return Hl(t)&&Je(t,e||((s=t.mobile)==null?void 0:s.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,li=r=>Object.values(r).filter(e=>Rn(e)&&kv(e)).length,ui=(r,e)=>Object.values(r).filter(t=>Rn(t)&&!zl(t,e)),di=(r,e)=>Object.values(r).filter(t=>Cv(t)&&!zl(t,e)),pi=(r,e)=>Object.values(r).filter(t=>ql(t)&&!zl(t,e))});function _v(r){let e=r.indexOf("--token");if(e===-1&&(e=r.indexOf("--t")),e!==-1)try{let t=r.slice();return t.splice(e,2),t}catch{}return r}var fi,Pf,gi,Af=T(()=>{"use strict";j();mi();fi=x("debug-reporter"),Pf={token:void 0,userParamsData:void 0,projectData:void 0,allGrids:void 0,gridData:void 0,awsAccessKeyId:void 0,awsSecretAccessKey:void 0,runParams:void 0,perfecto:void 0,testobjectSauce:void 0},gi=class{constructor(e){this.options=e}onTestStarted(e,t){fi.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let s=this.options.gridData||{},n=s.provider,o=s.host,i=s.gridId,a=s.type,c=s.failedGetBrowserAttempts;fi.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}onTestPlanStarted(e,t,s,n,o,i,a){let c=_v(process.argv);fi.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:Object.assign({},this.options,Pf),args:c})}onTestPlanFinished(e,t,s,n,o,i){let a=di(e,i).length,c=Object.keys(e).length-a;fi.info("Test Plan Finished",{isAnonymous:o,passed:a,failed:c,testPlanName:t,options:Object.assign({},this.options,Pf),duration:s,executionId:n})}}});var Kl,Pt,In=T(()=>{"use strict";ae();Kl=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===ue.DEVICE_FARM}},Pt=new Kl});var Yl={};W(Yl,{Reporter:()=>Ov});var er,xn,_r,hi,Cf,Jl,Ov,Xl=T(()=>{"use strict";er=E(require("chalk")),xn=E(require("lodash"));U();ae();In();mi();_r={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:hi}=Nt,Cf="device",Jl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t,s,n){let o=n?"File":"Test",i=e.isTestsContainer?"":`(${e.testId})`,a=e.isTestsContainer?"":`url: ${er.default.underline(at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`${o} "${e.name}" started ${i} ${a}`.trim())}onTestFinished(e,t,s,n){if(n)return;let o=e.success?pe.PASSED:pe.FAILED,i=e.isTestsContainer?" ":`(${e.testId})`,a=_r[e.success?"success":"error"];console.log(a(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${o} ${i} duration: ${po(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(s=>{let n=at(this.options.editorUrl,this.options.project,s.testId,s.resultId,this.branchToUse);return s.isTestsContainer?s.name:`${s.name} : ${n}`});console.log(_r.error("Failed runs are:")),console.log(_r.error(t.join(`
|
|
27
|
+
\r`)))}onTestPlanFinished(e,t,s,n,o,i){let a=ui(e,i),c=di(e,i),u=pi(e,i),d=c.length,p=u.length,m=a.length,g="",f="";if(Pt.isTestStatusEnabled){let w=li(e);g=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${ci(e,this.options)}`}let h=this.buildTestPlanName(o,t,i),y,b=_r[m?"error":"success"],I=`PASSED: ${d} FAILED: ${m}${g} ABORTED: ${p}${f} Duration: ${po(s)}`;i||h.trim()===""||h.trim()==="Anonymous"?y=`Tests completed. ${I} (Execution ID: ${n})`:y=`Test plan${h} completed ${I} (${n})`,this.printWorkerDivider(),console.log(b(y)),this.printWorkerDivider(),this.printAllFailedTests(a)}buildTestPlanName(e,t,s){if(s)return"";let n=xn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,o=xn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=xn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,a=xn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,c=[i,o,n,a].filter(Boolean).join(", ");return e?` anonymous (${c})`:` '${t}'`}onTestPlanStarted(e,t,s,n,o,i,a,c){let u=m=>{m.forEach((g,f)=>{var b;let h=(b=g.testData)!=null&&b.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=c?"":`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${Je(g,this.options)?"-quarantine":""}`,y,h)})},d=a?`config '${a}'`:"default configs";if(c)console.log(`Run test plan, Project: ${this.options.project} (Execution ID: ${o}):`);else{let m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",g=`${d}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${g} (${o})`)}this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),u(e)),console.log(c?"File list:":"Test list:"),u(t),s.length>0&&(console.log("After all:"),u(s)),this.printWorkerDivider()}onGetSlot(e,t){let s=this.options.grid||this.options.gridId,n=this.options.mode===hi.APPIUM?Cf:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(s)}`)}onGetSession(e,t,s){let n=s===hi.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,t,s){let n=t?"file":"test";console.log(this.toWorkerIdPrefix(e),`Wait for ${n} complete`),s&&t&&console.log(this.toWorkerIdPrefix(e),`Chrome Debugger available at ${s}`)}onGetBrowserFailure(e,t,s){if(s!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===hi.APPIUM?"device":"browser";if(n)console.log(_r.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(_r.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===hi.APPIUM?"Appium":"Selenium";console.log(_r.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Ov=Jl});var eu={};W(eu,{Reporter:()=>Uv});function Lv(r){let e=r.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function Dv(r){return r.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${r.visitedUrlsList||""}`}function Nv(r){return`${r.visitedUrlsJson||""}`}async function Mv(r,e,t,s,n,o){function i(m){let g=at(r,t,m.testId,m.resultId,s),f={$:{name:Lv(m),classname:n,time:hc(m.duration),ownedBy:m.testOwnerName,ownerEmail:m.testOwnerEmail},"system-out":g};if(Rn(m)||ql(m)){let h=`Step Failed: ${m.failureReason||m.reason}`,y=Rn(m)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Hl(m)&&Je(m,o)&&Pt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=Dv(m),f["visited-urls-json"]=Nv(m)),f}function a(m){let{results:g,testPlanName:f,configName:h}=m,y=g||{},I={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:u(y),failure:d(y),timestamp:c(e)};if(Pt.isTestStatusEnabled){I.skipped=ci(y,o);let w=li(y);I.failure-=w,I["failure-evaluating"]=w}return{$:I,testcase:Object.keys(y).map(w=>i(y[w]))}}function c(m){let g=Object.keys(m).map(h=>m[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function u(m){return Object.keys(m).length}function d(m){return ui(m).length+pi(m).length}let p={testsuites:{testsuite:e.map(m=>a(m))}};try{return new Zl.Builder().buildObject(p)}catch(m){return Fv(m)}}function Fv(r){let e=new Zl.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:r.message}}}}}};return e.buildObject(t)}var Zl,kf,Ql,Uv,tu=T(()=>{"use strict";Zl=E(require("xml2js"));U();kf=require("fs");In();mi();Ql=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,s=this.options.project,n=await Mv(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await kf.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)}};Uv=Ql});var _f={};W(_f,{Reporter:()=>jv});function hs(r){return r?r.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var ru,su,jv,Of=T(()=>{"use strict";j();ru=x("team-city-reporter");su=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${s}`;return hs(n)}onTestStarted(e,t,s,n,o){if(s){ru.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${o}']`)}onTestFailed(e,t,s,n,o,i){if(o){ru.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${hs(t)}' details='${hs(s)}' flowId='${i}']`)}onTestFinished(e,t,s){if(s){ru.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,s="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${hs(s)}']`)}onTestPlanStarted(e,t,s,n){console.log(`##teamcity[testSuiteStarted name='${hs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${hs(t)}']`)}},jv=su});var Lf={};W(Lf,{Reporter:()=>Bv});var nu,Bv,Df=T(()=>{"use strict";nu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,s,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},Bv=nu});var Nf={};W(Nf,{Reporter:()=>$v});var ou,$v,Mf=T(()=>{"use strict";U();vl();ou=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e,t,s,n){if(n)return;let o=at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Vo(o)}},$v=ou});var Wv,iu,Q,Bt=T(()=>{"use strict";Af();j();Wv=x("reporter"),iu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let s=e.reporters;if(this.reporters.push(new gi(e)),s===void 0||s.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Xl(),Yl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(tu(),eu));this.reporters.push(new o(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(Of(),_f)),s.includes("console")&&Promise.resolve().then(()=>(Xl(),Yl)),s.includes("junit")&&Promise.resolve().then(()=>(tu(),eu)),s.includes("json")&&Promise.resolve().then(()=>(Df(),Lf)),s.includes("chrome")&&Promise.resolve().then(()=>(Mf(),Nf))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,n,o,i,a){let c={};if(a){let d=Object.values(a);if(d.length>0){for(let p of Object.values(a))c[p.id]=p;for(let p of Object.keys(e))d.some(m=>m.parentResultId!==p)||(c[p]=e[p])}else Wv.warn("childTestResults is not array"),c=e}else c=e;let u=Date.now()-(s||0);return[c,t,u,n,o,i,void 0]}onAllTestPlansFinishedMutator(e){for(let t of e)if(t.childTestResults){t.results={};let s=Object.values(t.childTestResults);for(let n of s)t.results[n.id]=n;for(let n of Object.keys(e))s.some(o=>o.parentResultId!==n)||(t.results[n]=e[n])}return[e]}generateHook(e,t){return async(...s)=>{var o;let n=t==null?void 0:t(...s);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||s))}}},Q=new iu});function Uf(r,e){return e!=null&&e.type&&(r[`${e.type}Mode`]=!0),r}function jf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:u,user:d,lightweightMode:p,isStartUp:m,projectType:g,appSource:f}){let h=Uf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:Ff(u,d),isStartUp:m,projectType:g,...["android","ios"].includes(g)&&f&&{appSource:f}},p);gt("test-run-ci",h)}function Bf({executionId:r,projectId:e,testId:t,resultId:s,result:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:u,source:d,user:p,lightweightMode:m,logger:g,isStartUp:f,projectType:h,appSource:y}){try{let b=Uf({executionId:r,projectId:e,testId:t,resultId:s,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:u,mockNetworkEnabled:n.wasMockNetworkActivated,source:Ff(d,p),isStartUp:f,projectType:h,...["android","ios"].includes(h)&&y&&{appSource:y}},m);if(n.success){gt("test-run-ci-success",b);return}gt("test-run-ci-fail",Object.assign({},b,{failureReason:n.failureReason}))}catch(b){g.error("failed to update test end analytics",{err:b})}}function $f({executionId:r,projectId:e,sessionType:t}){gt("batch-run-ci",{executionId:r,projectId:e,sessionType:t})}var Ff,au=T(()=>{"use strict";ds();Lo();Ff=(r,e)=>r!=="cli"&&r!=="cli-local"?r:as&&e?"ci-with-user":as?"ci":e?"cli-with-user":r});var Gv,Gf=T(()=>{"use strict";Gv=require("istanbul-lib-report")});var Vf,qf,Vv,Hf,Or,qv,zf,cu,Hv,Kf,Jf=T(()=>{"use strict";Vf=E(require("ora")),qf=E(require("moment")),Vv=E(require("test-exclude")),Hf=E(require("fs")),Or=E(require("path")),qv=E(require("istanbul-reports")),zf=E(require("istanbul-lib-report"));Te();q();U();j();yt();Gf();cu=x("test-run-status"),Hv=async(r,e,t)=>{let{mergeProcessCovs:n}=await ge("@bcoe/v8-coverage"),o={result:[]},i=new Map,c=(await mn(r,"testResult",`runId=${t}`)).data.docs;return await de(c.flatMap(u=>u.JSCoverageURLS||[]),async u=>{let d=await pn(u,9e4);await de(d,async p=>{if(!i.has(p.url)){let m=p.text;p.sourceUrl&&(i.set(p.url,"TEMP"),m=await(void 0)(p.sourceUrl)),i.set(p.url,{text:m,url:p.url,sourceMapType:p.sourceMapType,hash:p.hash})}delete p.text,o=n([o,{result:[p]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:o}},Kf=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;cu.info("start js coverage process");let n=(0,Vf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=Or.resolve(r.codeCoverageReportPath||"./coverage"),i=Or.resolve(o,`.js/${(0,qf.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?Or.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:u,covUrlMap:d}]=await Promise.all([ge("istanbul-lib-coverage"),Hv(r.project,e,s)]);if(u.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}cu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:u.result.length});let p=c.createCoverageMap({}),m={};await de(u.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:b}=d.get(f),I=await(void 0).getSourceMap({sourceMapType:b,url:f,source:y,sourceMapDir:a});m[f]=I;let w=await(void 0).convertV8ToIstanbul(r,{source:y,sourceMap:I,functions:h});p.merge(w)}),await(void 0).remapCoverage(r,i,m);let g=await(void 0).saveCoverageReports(r,p,o,i);return n.succeed(),g}catch(c){let u="Failed to report coverage information";c instanceof P?n.fail(`${u}, missing arg: ${c.message}`):n.fail(u),cu.error(u,{err:c})}}});var Yf={};W(Yf,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>$t});var Ae,$t,ys=T(()=>{"use strict";U();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},$t=class{constructor(){this.marks=Object.fromEntries(Object.values(Object.assign({ALL:"ALL"},Ae)).map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=z();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let s=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(s);return}this.marks[t].push(s)}getStats(){let e=Object.entries(this.marks).flatMap(([t,s])=>!Array.isArray(s)||!s.length?[]:[[`${t}_COUNT`,s.length],[`${t}_P50`,go(s,50)],[`${t}_P95`,go(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var eg={};W(eg,{initServer:()=>Jv,mapFilesToLocalDrive:()=>uu});function uu(r,e){var t;try{r.failurePath=(r.failurePath||[]).map(s=>Object.assign(s,yi[s.id]?{screenshot:yi[s.id]}:{})),Object.keys(bs).forEach(s=>{r.assets||(r.assets={}),r.assets[Zf[s]]=bs[s]}),r.assets||(r.assets={}),r.assets.screenshots=Object.values(yi)}catch(s){e&&e.error("failed to map files to local drive",{err:s}),r.failurePath||(r.failurePath=[]),r.assets||(r.assets={}),(t=r.assets).screenshots||(t.screenshots=[])}}async function Jv({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await ge("multer"),n=typeof t=="string"?t:zv;await lu.promises.mkdir(n,{recursive:!0});let o=s({storage:s.diskStorage({async destination(c,u,d){let p=JSON.parse(c.body.metadata||"{}");if(!p.testResultId)return d(new Error("missing testResultId"),"");let m=Pn.join(n,p.testResultId);try{await lu.promises.mkdir(m,{recursive:!0})}catch(g){return d(g,"")}return d(null,m)},filename(c,u,d){let{fileName:p}=c.body,m=JSON.parse(c.body.metadata||"{}");if(!m.stepId&&!p)return d(new Error("missing stepId or fileName"),"");if(m.stepId){let g=Pn.extname(p);return d(null,`step_${m.stepId}_${m.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,p)}})}),i=(0,Qf.default)();i.post("/",o.single("file"),(c,u)=>{var p;let d=JSON.parse(c.body.metadata||"{}");d.stepId&&(yi[d.stepId]=c.file.path),d.testResultId&&Kv.includes(d.subType)&&(bs[p=d.subType]||(bs[p]=[]),bs[d.subType].push(c.file.path)),u.sendStatus(200)}),i.use((c,u)=>u.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,u)=>{let d=a(i);d.listen(r,e),d.on("error",p),d.on("listening",()=>c(d.address()));function p(m){if(m.syscall!=="listen")return u(m);switch(m.code){case"EACCES":case"EPERM":return u(new P(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return u(new P(`Port ${r} is already in use`));default:return u(m)}}})}var lu,Xf,Pn,Qf,zv,yi,bs,Zf,Kv,du=T(()=>{"use strict";lu=E(require("fs")),Xf=E(require("os")),Pn=E(require("path")),Qf=E(require("express"));q();yt();zv=Pn.join(Xf.tmpdir(),"testim/rca/"),yi={},bs={},Zf={"test-log":"consoleLogs","har-file":"networkLogs"},Kv=Object.keys(Zf)});var tr,pu,bi,tg=T(()=>{"use strict";tr=E(require("lodash"));U();j();pu=x("override-test-data-builder"),bi=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}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)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(s=>this.overrideSingleTest(s,e.overrideTestData[s])),delete e.overrideTestData):pu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):pu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}pu.error("skip override test data to test name",{testName:e,projectId:s}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let s=this.mapTestListToUniqueId(e);if(s.length!==0)return this.createNewTestPerOverrideTestData(s,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return tr.chain(t).map(s=>{if(s.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(s)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:s}=this;return[...new Set(e)].map(n=>{let o=s.map(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),c=s[i],u=this.createNewTestItems(c,t);return s.splice(i,a-i+1,...u)})}createNewTestItems(e,t){return[].concat(t).map((s,n)=>{let o=z();return Object.assign({},e,{resultId:o,testData:{value:s,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function wi(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw ot.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Lr,ot,Yv,Xv,Qv,Zv,Ti,rg=T(()=>{"use strict";Lr=E(require("lodash"));U();ae();gs();Te();q();j();Bt();hn();Jf();ys();du();le();ye();tg();In();ot=x("test-run-status"),Yv=Rr(),Xv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Qv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Zv=ct();Ti=class{constructor(e,t,s,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new $t;var a,c,u,d,p;(a=this.options).runParams||(a.runParams={}),this.fileUserParamsData=this.options.userParamsData;let o=Js(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:oo||t.parallel||1,browser:o,gitBranch:Yv,gitCommit:Xv,gitRepoUrl:Qv,runnerVersion:Zv,gridHost:t.host||((c=t.gridData)==null?void 0:c.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:s,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(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||((u=t.gridData)==null?void 0:u.gridId),gridName:t.grid||((d=t.gridData)==null?void 0:d.name),gridType:(p=t.gridData)==null?void 0:p.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:Er(t)},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:s,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,isTestsContainer:u,testId:d,name:p,testStatus:m,testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:b,testSuites:I,allLabels:w}=a,v={originalTestResultId:t,previousTestResultId:s,config:Lr.cloneDeep(c),testId:d,status:"QUEUED",name:p,resultId:e,isTestsContainer:u,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},v,{testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:b,testSuites:I,allLabels:w}),il({projectId:n,runId:o,testId:d,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:v})}getAllTestResults(){return this.testRunStatus}testStart(e,t,s,n){let o=this.getTestResult(s);o.workerId=e;let i=this.options.files.length>0;return Q.onTestStarted(o,e,n,i,s),o}async updateTestStatusRunning(e,t,s){var u;let{project:n,remoteRunId:o,projectData:i}=this.options;if((u=this.options.lightweightMode)!=null&&u.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Fo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){ot.error("failed to upload test data artifact (runner)",{err:d})}let c=Lr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,cs(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:s})}async testStartReport(e,t,s){if(Je(e,this.options))return;let n=this.exportsGlobal;try{let o=await wi(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw ot.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,n,o){let i=this.testStart(e,t,s,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),ot.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,n){let{name:o,testId:i,testStatus:a}=s,{resultId:c,success:u}=t;if(a===Ke.EVALUATING&&Pt.isTestStatusEnabled){Q.onTestIgnored(e,s,`test in ${Ke.EVALUATING} status`);return}if(u){Q.onTestPassed(o);return}Q.onTestFailed(s,s.failureReason,at(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);Q.onTestIgnored(e,s,`test in ${Ke.QUARANTINE}`)}testEnd(e,t,s,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&uu(i,ot),i.resultUrl=at(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||(t.testId=i.testId),t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o);let c=this.options.files.length>0;Q.onTestFinished(i,e,o,c);let u=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=u,i}async testEndReport(e,t,s,n){var i;let o=s.exportsGlobal;try{try{await wi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){ot.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 cs(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw ot.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,n,o,i){let a=this.testEnd(e,t,s,n,o);return this.testEndReport(a,s,t,i)}calcTestRunStatus(){let{options:e,testInfoList:t}=this,s=e.company.companyId,n=t.map(o=>{var p,m,g,f;let i=e.browser?tn(e.browser,e.saucelabs,e.browserstack):o.runConfig;if(i&&M.flags.dec2022eolBrowsers.isEnabled()&&((p=en(i.browserValue))!=null&&p.eol))throw new P(`Unsupported Browser: ${i.browserName}`);let a=!M.flags.allowAppFromDeviceRuns.isEnabled()&&Xs(o.nativeApp),c=Qs(e)&&(es(o.nativeApp)||a),u=Je(o,e)||c,d={testId:o.testId,status:u?pe.SKIPPED:pe.QUEUED,name:o.name,resultId:o.resultId,isTestsContainer:o.isTestsContainer,testStatus:o.testStatus||Ke.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...c&&{reason:es(o.nativeApp)?"virtual-build":"app-from-device"},config:Object.assign({},this.execConfig,{companyId:s,testData:((m=o.testData)==null?void 0:m.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((g=o.testData)==null?void 0:g.total)||null,testDataIndex:((f=o.testData)==null?void 0:f.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,d]});return Object.fromEntries(n)}async executionStart(e,t,s,n,o){ot.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;ls(()=>Promise.all([vn.end(t),No("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=s||Date.now();let u={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},d=await wi(i.beforeSuite,u),p=new bi(d,Lr.cloneDeep(this.testInfoList),t);this.testInfoList=p.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=d;let{testInfoList:m}=this,g=[],f=[],h=[];for(let b of m){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){h.push(b);continue}f.push(b)}let y=async()=>{let b=Lr.cloneDeep(this.testRunStatus);await de(Object.keys(b),async R=>{var A;let k=b[R],L=(A=k.config)==null?void 0:A.testData,S=k.testId,O=await Fo(t,S,R,L,c.defaults);O&&(delete k.config.testData,k.config.testDataUrl=O)});let I=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),w={executionId:e,projectId:t,labels:n||[],startTime:s,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:I,intersections:i.intersections},v=Wc(w);return this.executionStartedPromise=v,v.catch(R=>ot.error(R)),v};try{await y()}catch(b){ot.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){Lr.chain(e).keys().each(t=>{let s=t;this.seleniumPerfStats.marks[s]&&(this.seleniumPerfStats.marks[s]=[...this.seleniumPerfStats.marks[s],...e[s]])}).value()}async executionEnd(e){var d;let t=bc(this.testRunStatus),s=t.length,n=0,o=0,i=0;for(let{status:p,testStatus:m}of t)p===pe.PASSED&&n++,p===pe.SKIPPED&&o++,p===pe.FAILED&&m===Ke.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await wi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:n,skipped:o})}catch(p){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),ot.warn("error while running afterSuite Hook",{err:p,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let u=await Kf(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:u}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await No("FINISHED",e,this.options.project,s===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(p){throw ot.error("Failed to update suite finished",{err:p}),p}}async markAllQueuedTests(e,t,s,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await $c(e,["QUEUED"],t,s,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=s,a.success=n}return this.testRunStatus}}});function tE(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function yu(r){return og.readFileSync(r,{encoding:"base64"})}function cg(r,e,t){if(!(t!=null&&t.isLambdatestRun()&&Ge(r))&&r){let s=yu(r);ws.info(`adding extension: custom, path: ${r} length: ${s.length} hash: ${hu(s)} current extension count: ${e.length}`),e.push(s)}}function lg(r,e,t,s,n){if(n!=null&&n.isLambdatestRun())return;if(r.ext||s){let c=typeof r.ext=="string"?r.ext:`${__dirname}/..`,u=s||c,d=`--load-extension=${u}`;ws.info(`adding extension: testim unpacked , path: ${u}`),t.push(d);return}let o=r.canary?"-master.zip":".zip",i=gu.join(process.cwd(),`testim-headless${o}`),a=yu(i);ws.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${hu(a)} current extension count: ${e.length}`),e.push(a)}function rE(r,e,t,s,n,o,i){var h,y;let a=t.seleniumName||t.browserValue,c=[],u=[...ag];e.headless&&u.push("--headless");let d=()=>e.mode!==J.EXTENSION,p={prefs:{"profile.default_content_setting_values.popups":mu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":mu.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:d()};fu(n)&&(p.prefs["download.default_directory"]="C:\\Users\\testnode",p.w3c=!0,r.desiredCapabilities.version="latest-1",r.desiredCapabilities["aws:maxDurationSecs"]=2400,r.desiredCapabilities["aws:idleTimeoutSecs"]=60),fu(n)&&a==="MicrosoftEdge"&&(r.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(p.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(b=>u.push(`--${b}`)),e.chromeBlockLocation&&(p.prefs["profile.default_content_setting_values.geolocation"]=mu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&u.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(h=e.projectData)==null?void 0:h.defaults)!=null&&y.disableChromiumGpu&&u.push("--disable-gpu"),Object.assign(r.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(p.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+dc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),cg(s,c,i),e.mode===J.EXTENSION&&lg(e,c,u,o,i),c.length>0&&(p.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(p.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),p.args=u;let g={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return ee.isLambdatestGrid(n)&&delete p.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(r.desiredCapabilities[g]=p),(e.w3cCapabilities||n.type==="testimEnterprise")&&(r.desiredCapabilities[`${f}:${g}`]=p),r}function nE(r,e,t){let s={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"browser.helperApps.neverAsk.saveToDisk":ng.join(","),"browser.helperApps.neverAsk.openFile":ng.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(r.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:s}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(r.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===J.EXTENSION)if(e.ext)r.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=gu.join(process.cwd(),`testim-firefox-profile${n}`);r.desiredCapabilities.firefox_profile=yu(o)}return e.headless&&(r.desiredCapabilities["moz:firefoxOptions"].args||(r.desiredCapabilities["moz:firefoxOptions"].args=[]),r.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),r}function oE(r,e,t){let{saucelabs:s}=r;return s!=null&&s.username&&s.accessKey?t?(t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=s.appiumVersion||t.sl.appiumVersion,Object.assign({},t.sl,s,{name:e})):Object.assign({},s,{name:e}):{}}function iE(r,e,t){return bt.isEmpty(r.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,r.browserstack,{name:e})):Object.assign({},r.browserstack,{name:e})}function aE(r){return r.perfecto?r.perfecto:{}}function cE(r,e,t){if(r.experitestToken){let s=e==="safari";return{accessKey:r.experitestToken,browserVersion:"latest",platformName:s?"MAC":"WIN10",seleniumScreenshot:s,newSessionWaitTimeout:t}}return{}}function lE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:n}=r,o=s||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=ja(o,i)),a}function vi(r,e,t,s,n,o,i,a=null){var h,y,b,I,w,v;if(s.mode==="local"){let R=[],k=[...ag],L={};return r.headless&&k.push("--headless"),r.silentDebuggerExtensionApi&&k.push("--silent-debugger-extension-api"),r.remoteDebuggingPort!==void 0&&k.push(`--remote-debugging-port=${r.remoteDebuggingPort}`),r.chromeExtraArgs&&r.chromeExtraArgs.forEach(S=>k.push(`--${S}`)),r.chromeBinaryLocation&&(L.binary=r.chromeBinaryLocation),r.mode!=="selenium"&&lg(r,R,k,null,a),cg(n,R,a),{logLevel:sg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:k,extensions:R,...L},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:u}=r,d=lE(r,s),p={hostname:s.host,host:s.host,port:s.port||4444,path:s.path||"/wd/hub",protocol:s.protocol||"http",logLevel:sg,connectionRetryTimeout:c,connectionRetryCount:u,getSessionTimeout:Math.max(a.getSessionTimeout,r.getSessionTimeout),getSessionRetries:a.getSessionRetries||r.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!bt.isEmpty(d)&&{headers:d},...r.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};fu(s)&&(r.oldCapabilities=!1,r.w3cCapabilities=!0,p.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),r.disableNativeEvents&&(p.desiredCapabilities.nativeEvents=!1),s.user&&s.key&&(s.type==="saucelabs"&&(r.saucelabs||(r.saucelabs={}),(h=r.saucelabs).username||(h.username=s.user),(y=r.saucelabs).accessKey||(y.accessKey=s.key)),s.type==="browserstack"&&(r.browserstack||(r.browserstack={}),(b=r.browserstack)["browserstack.user"]||(b["browserstack.user"]=s.user),(I=r.browserstack)["browserstack.key"]||(I["browserstack.key"]=s.key))),s.key&&s.type==="perfecto"&&(r.perfecto.securityToken=s.key);let m=Number(r.browserTimeout/1e3),g=r.browser||(t==null?void 0:t.browserValue);bt.merge(p.desiredCapabilities,oE(r,e,t),iE(r,e,t),aE(r),cE(r,g,m),a==null?void 0:a.getCapabilities(r,g,o,i,e));let f=null;switch(!r.ext&&!r.extensionPath&&((w=s.host)!=null&&w.endsWith(".testim.io"))&&!r.canary&&r.mode===J.EXTENSION&&(g==="chrome"?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),(v=s.host)!=null&&v.endsWith(".testim.io")&&g==="edge-chromium"&&(p.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":p=sE(p,r,t,n,s,f,a);break;case"firefox":p=nE(p,r,a);break;case"safari":case"safari technology preview":p=tE(p,g);break;default:break}bt.merge(p.desiredCapabilities,r.seleniumCapsFileContent);try{let R={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},k=A=>A[s.provider]||A[p.host]||A[R[p.host]],L=A=>{var N,B;return k(A)||A[(N=p.desiredCapabilities)==null?void 0:N.browserName]||A[(B=p.desiredCapabilities)==null?void 0:B.version]||A||{}},S=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),O=L(L(S));Object.keys(O).length&&(ws.info(`Adding custom capabilities: ${JSON.stringify(O)}`),Object.assign(p.desiredCapabilities,O))}catch(R){ws.error("Failed to load custom capabilities",{error:R,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return p.desiredCapabilities&&!p.capabilities&&(eE(p.desiredCapabilities),p.capabilities={alwaysMatch:p.desiredCapabilities,firstMatch:[{}]},delete p.desiredCapabilities),p.hostname=p.host,p}function ug({projectType:r,gridInfo:e,nativeApp:t,options:s,appPath:n,androidActivityWait:o,sessionTags:i}){let{deviceModel:a,osVersion:c,deviceUdid:u,fullReset:d,resetAppData:p,resetOnSessionStartOnly:m}=s,g={};if(!t&&!n)throw Error("missing mobile app!");if(e.type!==ue.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid");let f={protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`,logLevel:s.appiumLogLevel},h={"headspin:capture":!0,"headspin:retryNewSessionFailure":!1,"headspin:sessionTags":i,...!d&&!p&&{"appium:noReset":!0},...!d&&p&&{"appium:noReset":!1}};switch(r){case"ios":h={...h,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...d&&{"appium:fullReset":d,"appium:resetOnSessionStartOnly":m},...t&&{"appium:bundleId":t.id},...n&&{"appium:app":n}};break;case"android":h={...h,platformName:"Android",...d&&{"appium:fullReset":d},...!d&&p&&{"appium:autoGrantPermissions":!0},"appium:automationName":"UiAutomator2","appium:appWaitActivity":o,...t&&{"appium:appPackage":t.id||t.packageName,"appium:appActivity":t.activity},...n&&{"appium:app":n}};break;default:throw Error(`unsupported mobile project ${r}`)}return a&&(g.model=a),c&&(g.os_version=c),u&&(g.device_id=u,delete g.model,delete g.os_version),bt.isEmpty(g)||(h["headspin:selector"]=g),{...f,desiredCapabilities:h,capabilities:h,connectionRetryCount:0}}var og,gu,ig,bt,ws,sg,mu,ag,hu,fu,eE,sE,ng,Ei=T(()=>{"use strict";og=E(require("fs")),gu=E(require("path")),ig=E(require("crypto")),bt=E(require("lodash"));U();le();j();ye();ae();ti();ws=x("testim-desired-capabilities-builder"),sg=no?"debug":"silent",mu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ag=["--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"],hu=(...r)=>ig.createHash("sha256").update(r.join("")).digest("hex"),fu=r=>r.type===ue.DEVICE_FARM||r.type===ue.HYBRID&&r.provider==="devicefarm",eE=r=>{Object.prototype.hasOwnProperty.call(r,"version")&&(r.browserVersion=r.version,delete r.version),Object.prototype.hasOwnProperty.call(r,"platform")&&(r.platformName=r.platform,delete r.platform),Object.prototype.hasOwnProperty.call(r,"acceptSslCerts")&&(r.acceptInsecureCerts=r.acceptSslCerts,delete r.acceptSslCerts),Object.prototype.hasOwnProperty.call(r,"unexpectedAlertBehaviour")&&(r.unhandledPromptBehavior=r.unexpectedAlertBehaviour,delete r.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(r,"chromeOptions")&&(r["goog:chromeOptions"]??(r["goog:chromeOptions"]=r.chromeOptions),delete r.chromeOptions);let e;try{e=M.flags.unsupportedCapsFields.getValue();let t=JSON.parse(e);if(!Array.isArray(t))return;t.forEach(s=>{delete r[s]})}catch{ws.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:e})}};sE=bt.memoize(rE,(r,e,t,s,n,o)=>{let i=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(bt.omit(e,"runParams")),c=JSON.stringify(t),u=JSON.stringify(n.type);return hu(i,a,c,s,u,o)}),ng=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(r){var e,t,s,n,o,i,a;return((e=r.message)==null?void 0:e.match(/Command not found/))||r.message==="HTTP method not allowed"||r.message==="Unknown error"||((t=r.message)==null?void 0:t.match(/Unknown timeout type/))||r.name==="unknown command"||((s=r.message)==null?void 0:s.match(/did not match a known command/))||((n=r.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=r.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=r.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=r.message)==null?void 0:a.match(/\.\w* is not a function/))}function dg(r,e,t){if(!e||!r)return r;if(r.includes("%"))return r.replace(/ /g,"%20");try{return decodeURI(r)!==r?r:encodeURI(r)}catch(s){return t&&t.warn("tried to encode url but failed",{err:s,url:r}),r}}async function pg(r){if(!Si||!Ri){let[e,t]=await Promise.all([import("got"),import("webdriverio/node_modules/webdriver/build/utils.js")]);[Si,Ri]=[e.RequestError,t.CustomRequestError]}return!Si||!Ri?!1:r instanceof Si||r instanceof Ri}var Si,Ri,wu=T(()=>{"use strict"});function Tu(r){function e(m){return m?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(m.nodeType):!1}function t(m){return m?s(m.parentNode,e):null}function s(m,g){for(let f=m;f&&f!==m.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(m,g){for(let f=m;f&&f!==m.ownerDocument;f=t(f))if(g(f))return f;return null}function o(m,g){if(!m||!g)return null;m instanceof DocumentFragment&&(m=m.host);let h=window.getComputedStyle(m).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(m);return o(y,g)}function i(m){let g=m.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(m.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(m,"stroke-width");return!!h&&parseInt(h,10)>0}return o(m,"overflow")==="hidden"?!1:Array.from(m.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(m){return o(m,"overflow")==="hidden"}function c(m){return!m||!a(m)||!m.childNodes.length?!1:Array.from(m.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function u(m){var g;return m?(g=m.parentNode)!=null&&g.host?!0:u(m.parentNode):!1}if(!r||!u(r)&&!document.contains(r))return!1;switch(r.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=s(r,f=>f.tagName.toUpperCase()==="SELECT");return Tu(g)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(o(r,"visibility")!=="visible")return!1;let d=!!n(r,m=>Number(o(m,"opacity"))===0),p=!!n(r,m=>o(m,"display")==="none");return!(d||p||!i(r)||c(r))}var mg=T(()=>{"use strict"});var fg,gg,An,uE,dE,Ii,hg=T(()=>{"use strict";fg=E(require("promise-queue")),gg=E(require("webdriverio"));le();Oe();U();j();Bs();mg();wu();ys();An=x("WebDriverApi"),uE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},dE={implicit:0,pageLoad:1,script:2},Ii=class{seleniumPerfStats;client;get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){return this.capabilities&&"browserName"in this.capabilities&&this.capabilities.browserName.toLocaleLowerCase()||void 0}constructor(){this.w3cRequests={}}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}rejectWithLog(e,t){let{testName:s,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";return An.warn("error from selenium",{err:e,testResultId:n,testName:s,crashingFunc:o}),Promise.reject(e)}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof Ga<"u"&&(e=Ga);let t=1/0;this.queue=new fg.default(e,t)}async addToQueue(e){let t=this.seleniumPerfStats.markStart();try{return await this.queue.add(e)}catch(s){return this.rejectWithLog(s,e)}finally{this.seleniumPerfStats.markEnd(t)}}async initClient(e,t,s){var o,i;this.testName=t,this.testResultId=s,e.deprecationWarnings=!1,this.initQueueRequests(),_("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{An.info("requesting browser",{testResultId:s,testName:t}),_("before this.client.init"),this.client=await gg.remote(e)}),_("after client init")}finally{await((i=this.seleniumPerfStats)==null?void 0:i.markEnd(n,Ae.GET_BROWSER))}}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){return this.capabilities&&"platformName"in this.capabilities&&this.capabilities.platformName.toLocaleLowerCase()==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}execute(...e){return this.addToQueue(()=>{let t=e.shift();if(typeof t!="string"&&typeof t!="function")return Promise.reject(new Error("number or type of arguments don't agree with execute protocol command"));typeof t=="function"&&(t=`return (${t}).apply(null, arguments)`);let s=i=>{throw i.executedScript=t,i},n=()=>this.client.execute(t,e).catch(s),o=()=>this.client.executeScript(t,e).catch(s);return"execute"in this.w3cRequests&&this.w3cRequests.execute?n():(e=e.map(i=>{if(i===null){An.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:t,args:e});return}return i}),o().catch(i=>{if(Fe(i))return Object.assign(this.w3cRequests,{execute:!0}),n();throw i}))}).then(t=>({value:t}))}executeAsync(...e){return this.addToQueue(()=>{let t=e.shift();if(typeof t!="string"&&typeof t!="function")return Promise.reject(new Error("number or type of arguments don't agree with execute protocol command"));typeof t=="function"&&(t=`return (${t}).apply(null, arguments)`);let s=()=>this.client.executeAsync(t,e),n=()=>this.client.executeAsyncScript(t,e);return"executeAsync"in this.w3cRequests&&this.w3cRequests.executeAsync?s():n().catch(o=>{if(Fe(o))return this.w3cRequests.executeAsync=!0,s();throw o})}).then(t=>({value:t}))}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let s=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return s!=null&&s.targetInfos?s.targetInfos:[]}takeScreenshot(){var t;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ae.GET_SCREENSHOT);return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.takeScreenshot().then(n=>({value:n}))}).finally(()=>{var s;return(s=this.seleniumPerfStats)==null?void 0:s.markEnd(e,Ae.GET_SCREENSHOT)})}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ae.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Ne(e)))}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_SCREENSHOT)}}getElementBySelector(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e)}).then(t=>({value:t}))}elementIdDisplayed(e){return this.addToQueue(()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),s=()=>this.execute(Tu,{ELEMENT:e,[Hr]:e});return"elementIdDisplayed"in this.w3cRequests&&this.w3cRequests.elementIdDisplayed?s():t().catch(n=>{if(Fe(n))return this.w3cRequests.elementIdDisplayed=!0,s();throw n})})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}url(e){return e?this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(dg(e,this.isSafari(),An))}):Promise.resolve()}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(()=>{let s=()=>{let o=[];return o[dE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});return"timeouts"in this.w3cRequests&&this.w3cRequests.timeouts?n():s().catch(o=>{if(Fe(o))return this.w3cRequests.timeouts=!0,n();throw o})})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(n,o){window.scrollTo(n,o)};return this.execute(s,e,t)}setValue(e,t){return this.elementIdClear(Ne(e)).then(()=>this.elementIdValue(Ne(e),t))}getViewportSize(e){return this.execute(uE).then(t=>typeof e=="string"&&e.match(/(width|height)/)?(e=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`,t.value[e]):{width:t.value.screenWidth||0,height:t.value.screenHeight||0})}keys(e){let t=i=>Fa.hasOwnProperty(i)?[Fa[i]]:i.split(""),s=[];if(typeof e=="string")s=t(e);else if(e instanceof Array)for(let i of e)s=s.concat(t(i));else return Promise.reject(new Error("number or type of arguments don't agree with keys protocol command"));let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:s})},o=()=>{let i=s.map(c=>({type:"keyDown",value:c})),a=s.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};return this.w3cRequests.keys?o():this.addToQueue(()=>n().catch(i=>{if(Fe(i))return this.w3cRequests.keys=!0,o();throw i}))}elementIdValue(e,t){return t=Array.isArray(t)?t.join():t,this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.elementSendKeys(e,t)}).then(s=>({value:s}))}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Ne(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),s=await t.$('button[type="submit"]');return await s.isExisting()?s.click():(await t.$("input:last-of-type")).keys("Enter")})}findElementAndPress(e,t,s,n){return this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:t,y:s,button:n})}).then(o=>({value:o}))}rightClick(e,t,s){return this.findElementAndPress(e,t,s,"right")}leftClick(e,t,s){return this.findElementAndPress(e,t,s,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}actions(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.performActions(e)}).then(t=>({value:t}))}doDoubleClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).doubleClick()}).then(t=>({value:t}))}dragAndDrop(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e).dragAndDrop(t)}).then(s=>({value:s}))}buttonDown(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.buttonDown()}).then(e=>({value:e}))}buttonUp(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.buttonUp()}).then(e=>({value:e}))}moveTo(e,t,s){let n={};return typeof t=="number"&&(n.xOffset=t),typeof s=="number"&&(n.yOffset=s),this.isSafari()&&!n.hasOwnProperty("yoffset")&&(n.yOffset=1),this.isSafari()&&!n.hasOwnProperty("xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}uploadFile(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.uploadFile(e)}).then(t=>({value:t}))}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()})}windowHandleSize(e){return this.addToQueue(()=>{let t=async()=>await this.client.getWindowSize(),s=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let n=Math.abs(e.width),o=Math.abs(e.height);t=async()=>await this.client.setWindowSize(n,o),s=async()=>await this.client._setWindowSize(n,o)}return this.w3cRequests.windowHandleSize?t():s().catch(n=>{if(Fe(n))return this.w3cRequests.windowHandleSize=!0,t();throw n})}).then(t=>({value:t}))}setCookie(e,t,s,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getCookies(e).then((s=[])=>s||(typeof e=="string"?null:[]))})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){if(this.w3cRequests={},!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.w3cRequests={},!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}isAppInstalled(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.isAppInstalled(e)}).then(t=>{let s=!!t.value;return An.info(`is app (${e}) installed? ${s}`,t),s})}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 yg,bg=T(()=>{"use strict";yg=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let n=r.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(m){function g(I,w,v){return v>I&&v<w}let f=m.pointerPosition||{},h=s.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,b=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:b}},a=function(m,g){return{screenX:0,screenY:0,clientX:m,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(m,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(m,h)},u=function(m,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(m,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},d=function(){var g;let m=document.activeElement;for(;(g=m.shadowRoot)!=null&&g.activeElement;)m=m.shadowRoot.activeElement;return m},p=function(m){let g=i(m),f=m.event;return t.includes(f)?c(f,g.x,g.y):u(f,g.x,g.y)};try{n.map(g=>p(g)).filter(Boolean).forEach(g=>s.dispatchEvent(g));let m=d();dispatchFocus(r.elementToFocusLocatedElement,m),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(m){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:m.toString(),success:!1})}}});function Dr(r,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function s(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=s();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(r){let o=getLocatedElement(r);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var xi=T(()=>{"use strict"});var Eg={};W(Eg,{WebDriver:()=>Nr});async function gE(r){var e,t;try{let s=(t=(e=r==null?void 0:r.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return s?await mE(s):void 0}catch(s){Ve.info("Error getting cdpAddress",s);return}}var Xe,vg,Ve,rr,pE,wg,mE,sr,fE,Tg,Nr,Cn=T(()=>{"use strict";Xe=E(require("lodash"));U();Oe();Ei();vg=E(require("ua-parser-js"));Bs();j();wu();hg();q();bg();xi();ye();ys();Ve=x("webdriver"),[rr,pE]=[0,2],{extractElementId:wg,getCdpAddressForHost:mE}=H,sr=()=>(Ee(),ie(kr)).getSessionPlayer().codeSnippets,fE=()=>(Ee(),ie(kr)).getSessionPlayer().locatorBuilderUtils,Tg=()=>(Ee(),ie(kr)).getSessionPlayer().utils;Nr=class extends Ii{constructor(){super(),this.started=!1,this.keepAliveTimer=null,this.unsupportedActions={},this._isAlive=!1,this._keepAliveRequests=[],this.cdpUrl=void 0,this.browserClosedCallbacks=[],this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=!1}registerToClosedBrowser(e){this.browserClosedCallbacks.push(e)}unregisterToClosedBrowser(e){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(t=>t!==e)}async init(e,t,s,n,o,i,a,c=new $t,u=!1,d){var f,h,y,b,I,w,v,R;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=(y=(h=(f=e==null?void 0:e.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.ignoreHiddenTagsText,this.browserClosedCallbacks=[];let p=vi(e,t,s,n,o,i,a,d);p.desiredCapabilities&&delete p.desiredCapabilities.marionette,p.capabilities&&delete p.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(d==null?void 0:d.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=c;let m=u?0:1500,g=u?()=>{}:()=>this.executeJS("window.focus()");try{_("before initClient in webdriver.js init");let k=await this.initClient(p,t,a);_("after initResult before getCdpAddress in init"),this.cdpUrl=await gE(k),_("after getCdpAddress in webdriver.js init"),Ve.info(`init new session testName: ${t}`,{sessionId:this.getSessionId(),testResultId:a}),await se(m),await g(),_("after focus and delay in webdriver.js init")}catch(k){Ve.error("failed to init webdriver",{err:k,capabilities:p});let L=((I=(b=e==null?void 0:e.company)==null?void 0:b.activePlan)==null?void 0:I.plan)==="free";throw(w=k.stack)!=null&&w.includes("at startWebDriverSession")&&((v=k.message)!=null&&v.startsWith("Failed to create session"))&&((R=k.message)!=null&&R.includes("Timeout awaiting 'request'"))&&L?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/capabilit(y|ies)/)?new Ws(k.message):new Error("failed to init client driver")}}initUnsupportedActions(e){e&&(this.unsupportedActions={...this.unsupportedActions,move:!0})}isAlive(){return this._isAlive}maxKeepAliveGap(){let e=n=>Xe.zip(Xe.dropRight(n,1),Xe.drop(n,1)),t=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),s=e(t).map(([n,o])=>o-n);return Math.max(...s)}async isClosedBrowserError(e){return["session-not-found","no such window"].includes(e==null?void 0:e.name)?!0:await pg(e)?["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(s=>e.message.includes(s)):!1}start(){if(this.started)return;this.started=!0;let e=async()=>{let t=i=>this._keepAliveRequests.push({start:Date.now(),id:i}),s=(i,a)=>{(this._keepAliveRequests.find(c=>c.id===a)||{})[i]=Date.now()};function n(){return window.getTestimStatus&&window.getTestimStatus()}if(this.queue.getQueueLength()>0)return;let o=z();t(o);try{await this.executeJS(n),this._isAlive=!0,s("end",o),this.browserClosedFailedKeepAlives=0}catch(i){if(s("error",o),i.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ve.warn("close unexpected alert open"),await this.alertAccept().catch(a=>Ve.warn("failed to click on alert",{err:a}));return}if(Ve.warn("err while getting testim status",{err:i}),this._isAlive=!1,await this.isClosedBrowserError(i)){this.browserClosedFailedKeepAlives++;let a=3;this.browserClosedFailedKeepAlives>=a&&this.browserClosedCallbacks.forEach(c=>{try{c(i)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(e,1e4)}switchToLocatedFrame(e){return this.getElement(e).then(async t=>{let s=wg(t.value);return await this.switchToFrame({ELEMENT:s,[Hr]:s}),t})}switchToFrame(e){return this.frame(e)}switchToTopFrame(){return this.frame().catch(e=>{var t;throw(t=e.message)!=null&&t.includes("ECONNREFUSED")?new Gs:e})}getElement(e){let t=this.seleniumPerfStats.markStart(Ae.GET_ELEMENT);return typeof e=="string"||typeof e=="number"?this.getElementBySelector(`[testim_dom_element_id='${e}']`).finally(()=>this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)):e&&e.shadowPath&&e.shadowPath.length||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari()?this.execute(`
|
|
28
28
|
var fn = ${sr().getLocatedElementCode};
|
|
29
29
|
return fn.apply(null, arguments);
|
|
30
|
-
`,e).finally(()=>this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)):this.getElementBySelector(`[testim_dom_element_id='${e&&e.testimId}']`).finally(()=>this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT))}executeJS(e
|
|
30
|
+
`,e).finally(()=>this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)):this.getElementBySelector(`[testim_dom_element_id='${e&&e.testimId}']`).finally(()=>this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT))}executeJS(e,...t){return this.execute(e,...t)}executeJSWithArray(e,t){return t.unshift(e),this.execute.apply(this,t)}executeCodeAsync(e,t,s){return this.timeouts("script",t).then(()=>this.executeAsync(e,s))}async markDynamicParent(e,t,s){function n(o){var i=o.attributeName,a=o.attributeValue,c=getLocatedElement(o.locatedElement);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(i,a)}return this.executeJS(`
|
|
31
31
|
var getLocatedElement = ${sr().getLocatedElementCode};
|
|
32
32
|
var setDynamicParentAttribute = ${n.toString()};
|
|
33
33
|
return setDynamicParentAttribute.apply(null, arguments)
|
|
@@ -39,23 +39,23 @@ ${((x=n.warnings)==null?void 0:x.join(`
|
|
|
39
39
|
var getLocatedElement = ${sr().getLocatedElementCode};
|
|
40
40
|
var getLocation = ${t.toString()};
|
|
41
41
|
return getLocation.apply(null, arguments)
|
|
42
|
-
`,e)}getElementLocation(e){return this.getLocatedElementRect(e.locatedElement)}getTargetText(e){return this.getElementTextJS(e.locatedElement)}getElementTextJS(e){function t(s,n){function o(d){if(!d.childNodes||d.childNodes.length===0)return d;var p=Array.apply(null,d.childNodes).filter(function(m){return m.nodeType===Node.ELEMENT_NODE});return p.forEach(function(m){typeof m.tagName=="string"&&m.tagName.toLowerCase()==="title"?d.removeChild(m):o(m)}),d}function i(d){var p=d.tagName;return p==="INPUT"||p==="TEXTAREA"}function a(d){try{if(d.shadowRoot&&Object.getOwnPropertyDescriptor(d.ownerDocument.defaultView.Node.prototype,"textContent").get.toString().indexOf("[native code]")===-1)return d.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(n&&Array.prototype.some.call(d.children,function(
|
|
42
|
+
`,e)}getElementLocation(e){return this.getLocatedElementRect(e.locatedElement)}getTargetText(e){return this.getElementTextJS(e.locatedElement)}getElementTextJS(e){function t(s,n){function o(d){if(!d.childNodes||d.childNodes.length===0)return d;var p=Array.apply(null,d.childNodes).filter(function(m){return m.nodeType===Node.ELEMENT_NODE});return p.forEach(function(m){typeof m.tagName=="string"&&m.tagName.toLowerCase()==="title"?d.removeChild(m):o(m)}),d}function i(d){var p=d.tagName;return p==="INPUT"||p==="TEXTAREA"}function a(d){try{if(d.shadowRoot&&Object.getOwnPropertyDescriptor(d.ownerDocument.defaultView.Node.prototype,"textContent").get.toString().indexOf("[native code]")===-1)return d.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm,"")}catch{}if(n&&Array.prototype.some.call(d.children,function(g){return g.hidden})){var p=d.cloneNode(!0),m=Array.prototype.filter.call(p.children,function(g){return g.hidden});return m.forEach(function(g){p.removeChild(g)}),p.textContent.replace(/(\r\n|\n|\r)/gm,"")}return d.textContent.replace(/(\r\n|\n|\r)/gm,"")}function c(d){if(i(d))return d.value;if(d instanceof SVGElement){var p=d.cloneNode(!0);return o(p).textContent.replace(/(\r\n|\n|\r)/gm,"")}else return a(d)}var u=getLocatedElement(s);return u?c(u):""}return this.executeJS(`
|
|
43
43
|
var getLocatedElement = ${sr().getLocatedElementCode};
|
|
44
44
|
var extractText = ${t.toString()};
|
|
45
45
|
return extractText.apply(null, arguments)
|
|
46
|
-
`,e,this.ignoreHiddenTagsText).then(s=>s.value)}getHTML(e){let t=sr().getHtmlCode(null,e),s=this.seleniumPerfStats.markStart(Ae.GET_HTML);return this.executeJS(t).then(n=>(this.seleniumPerfStats.markEnd(s,Ae.GET_HTML),n.value)).catch(n=>{this.seleniumPerfStats.markEnd(s,Ae.GET_HTML);let o=Object.assign(new Error,{success:!1,reason:n.toString(),errorType:"internal-error"});throw this.client.requestHandler.sessionID||(o.extraInfo="Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"),o})}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(e,t){let n=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},o=(a,c=1)=>this.windowHandleSize().then(u=>this.execute(n).then(d=>{let p=u.value.width-d.value.screenWidth,m=u.value.height-d.value.screenHeight;return this.windowHandleSize({width:a.width+p,height:a.height+m})}).then(()=>this.execute(n)).then(d=>{if(c<5&&(d.value.screenWidth!==a.width||d.value.screenHeight!==a.height))return o(a,c+1)}));if(typeof e!="object"||typeof e.width!="number"||typeof e.height!="number"||typeof t<"u"&&typeof t!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(typeof t>"u"?!0:t)?o(e):this.windowHandleSize(e)}setViewportSize(e,t){var s=!0;return this.setViewportSizeNEW({width:e,height:t},s)}getBrowserMajorVersion(e){try{return parseInt(e.browser.major,10)}catch(t){return Ve.error("failed to get browser version",{err:t}),0}}getBrowserAndOS(){function e(t,s){var n=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(n[1]))return"Internet Explorer "+s.major;if(n[1]==="Chrome"&&t.match(/\bOPR\/(\d+)/)!==null)return"opera";if(n[1]==="Chrome"&&t.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";n=n[2]?[n[1],n[2]]:[t.appName,t.appVersion,"-?"];var o=t.match(/version\/(\d+)/i);return o!==null&&n.splice(1,1,o[1]),n[0].toLowerCase()}return this.browserAndOS?Promise.resolve(this.browserAndOS):this.executeJS(function(){return typeof window>"u"||!window.navigator||!window.navigator.userAgent?"unknown":window.navigator.userAgent}).then(t=>{let s=t.value,n=(0,
|
|
46
|
+
`,e,this.ignoreHiddenTagsText).then(s=>s.value)}getHTML(e){let t=sr().getHtmlCode(null,e),s=this.seleniumPerfStats.markStart(Ae.GET_HTML);return this.executeJS(t).then(n=>(this.seleniumPerfStats.markEnd(s,Ae.GET_HTML),n.value)).catch(n=>{this.seleniumPerfStats.markEnd(s,Ae.GET_HTML);let o=Object.assign(new Error,{success:!1,reason:n.toString(),errorType:"internal-error"});throw this.client.requestHandler.sessionID||(o.extraInfo="Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated"),o})}maximizeWithoutValidation(){return this.windowHandleMaximize()}setViewportSizeNEW(e,t){let n=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},o=(a,c=1)=>this.windowHandleSize().then(u=>this.execute(n).then(d=>{let p=u.value.width-d.value.screenWidth,m=u.value.height-d.value.screenHeight;return this.windowHandleSize({width:a.width+p,height:a.height+m})}).then(()=>this.execute(n)).then(d=>{if(c<5&&(d.value.screenWidth!==a.width||d.value.screenHeight!==a.height))return o(a,c+1)}));if(typeof e!="object"||typeof e.width!="number"||typeof e.height!="number"||typeof t<"u"&&typeof t!="boolean")throw new Error("number or type of arguments don't agree with setViewportSize command");return(typeof t>"u"?!0:t)?o(e):this.windowHandleSize(e)}setViewportSize(e,t){var s=!0;return this.setViewportSizeNEW({width:e,height:t},s)}getBrowserMajorVersion(e){try{return parseInt(e.browser.major,10)}catch(t){return Ve.error("failed to get browser version",{err:t}),0}}getBrowserAndOS(){function e(t,s){var n=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(n[1]))return"Internet Explorer "+s.major;if(n[1]==="Chrome"&&t.match(/\bOPR\/(\d+)/)!==null)return"opera";if(n[1]==="Chrome"&&t.match(/\bEdge|Edg\/(\d+)/)!==null)return"edge";n=n[2]?[n[1],n[2]]:[t.appName,t.appVersion,"-?"];var o=t.match(/version\/(\d+)/i);return o!==null&&n.splice(1,1,o[1]),n[0].toLowerCase()}return this.browserAndOS?Promise.resolve(this.browserAndOS):this.executeJS(function(){return typeof window>"u"||!window.navigator||!window.navigator.userAgent?"unknown":window.navigator.userAgent}).then(t=>{let s=t.value,n=(0,vg.default)(s),o=n.os;return this.browserAndOS={os:o.name+" "+o.version,browserMajor:this.getBrowserMajorVersion(n),browser:e(t.value,n.browser),userAgent:s,browserVersion:n.browser.version},this.browserAndOS})}getUserAgentInfo(){return this.executeJS(`return ${sr().getUserAgentInfo()}`).then(e=>e.value)}setValue(e,t){return super.setValue(e,t)}getRelativeMoveActions(e,t){let{rect:s,clickOffset:n}=e,o=this.inViewCenter(s),i=Math.floor(n.x-o.x),a=Math.floor(n.y-o.y);return!Tg().isWithinBounds(-o.x,o.x,i)||!Tg().isWithinBounds(-o.y,o.y,a)?(Ve.warn("using center as fallback for offset"),this.getMoveActions(0,0,t)):this.getMoveActions(i,a,t)}computeAbsoluteMovement(e){let{frameOffset:t,rect:s,clickOffset:n}=e,o=s.left+n.x+t.x,i=s.top+n.y+t.y;return{x:o,y:i}}actWithActionsAPI(e,t,s,n){let o=this.getRelativeMoveActions(e,s),i=this.getClickActions(n,t);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(i)}]).catch(a=>{Ve.error("tried to use element origin but failed because of visibility, trying absolute",a);let{x:c,y:u}=this.computeAbsoluteMovement(e),d=this.getMoveActions(c,u);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:d.concat(i)}])})}doubleClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,rr,e,["pointerDown","pointerUp","pointerDown","pointerUp"])}doubleClickWithJS(e){return this.executeCodeAsync(`
|
|
47
47
|
var getLocatedElement = ${sr().getLocatedElementCode};
|
|
48
|
-
var dispatchFocus = ${
|
|
49
|
-
var doubleClick = ${
|
|
48
|
+
var dispatchFocus = ${Dr.toString()};
|
|
49
|
+
var doubleClick = ${yg.toString()};
|
|
50
50
|
var eventData = arguments[0];
|
|
51
51
|
var done = arguments[1];
|
|
52
52
|
return doubleClick.call(null, eventData, done);
|
|
53
|
-
`,e.timeout,e)}getClickActions(e=[],t){return e.map(s=>({type:s,button:t}))}getClickActionList(e=[],t){return[{type:"pointer",id:"mouse",actions:this.getClickActions(e,t)}]}leftClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,rr,e,["pointerDown","pointerUp"])}rightClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,pE,e,["pointerDown","pointerUp"])}rightClick(e,t){return this.unsupportedActions.move?this.rightClickWithActionsAPI(e,t):super.rightClick(e).catch(s=>{if(Fe(s))return this.unsupportedActions.move=!0,this.rightClickWithActionsAPI(e,t);throw s})}leftClick(e,t){return this.unsupportedActions.move?this.leftClickWithActionsAPI(e,t):super.leftClick(e).catch(s=>{if(Fe(s))return this.unsupportedActions.move=!0,this.leftClickWithActionsAPI(e,t);throw s})}dragAndDropOldAPI(e,t){return this.moveTo(e).then(()=>this.buttonDown()).then(()=>this.moveTo(t)).then(()=>this.buttonUp())}calculateElementMiddlePoint(e,t={top:0,left:0}){return this.getLocatedElementRect(e).then(s=>{if(!s||!s.value)throw Ve.warn(`could not find element for locatedElement ${e}`),new Error("could not calculate rect");let{x:n,y:o,width:i,height:a}=s.value;return{x:t.left+n+i/2,y:t.top+o+a/2}})}hover(e,t){if(this.unsupportedActions.move)return this.moveToElementWithActionsAPI(e,t);let{x:s,y:n}=t.clickOffset;return this.moveTo(e,s,n).catch(o=>{if(Fe(o))return this.unsupportedActions.move=!0,this.moveToElementWithActionsAPI(e,t);throw o})}getMoveActions(e=1,t=1,s="viewport",n=0){return[{type:"pointerMove",duration:n,x:Math.floor(e)||1,y:Math.floor(t)||1,origin:s}]}moveWithActionsAPI(e){let t=this.getMoveActions(e.x,e.y);return this.actions([{type:"pointer",id:"mouse",actions:t}])}moveToElementWithActionsAPI(e,t){return this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(t,e)}]).catch(s=>{Ve.error("tried to use element origin but failed because of visibility, trying location",s);let n=this.computeAbsoluteMovement(t);return this.moveWithActionsAPI(n)})}getDragCoordinates(e){let t=e.filter(o=>o.event==="mousemove"||o.event==="pointermove"),s=
|
|
54
|
-
var ${y} = require('${
|
|
55
|
-
`,
|
|
53
|
+
`,e.timeout,e)}getClickActions(e=[],t){return e.map(s=>({type:s,button:t}))}getClickActionList(e=[],t){return[{type:"pointer",id:"mouse",actions:this.getClickActions(e,t)}]}leftClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,rr,e,["pointerDown","pointerUp"])}rightClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,pE,e,["pointerDown","pointerUp"])}rightClick(e,t){return this.unsupportedActions.move?this.rightClickWithActionsAPI(e,t):super.rightClick(e).catch(s=>{if(Fe(s))return this.unsupportedActions.move=!0,this.rightClickWithActionsAPI(e,t);throw s})}leftClick(e,t){return this.unsupportedActions.move?this.leftClickWithActionsAPI(e,t):super.leftClick(e).catch(s=>{if(Fe(s))return this.unsupportedActions.move=!0,this.leftClickWithActionsAPI(e,t);throw s})}dragAndDropOldAPI(e,t){return this.moveTo(e).then(()=>this.buttonDown()).then(()=>this.moveTo(t)).then(()=>this.buttonUp())}calculateElementMiddlePoint(e,t={top:0,left:0}){return this.getLocatedElementRect(e).then(s=>{if(!s||!s.value)throw Ve.warn(`could not find element for locatedElement ${e}`),new Error("could not calculate rect");let{x:n,y:o,width:i,height:a}=s.value;return{x:t.left+n+i/2,y:t.top+o+a/2}})}hover(e,t){if(this.unsupportedActions.move)return this.moveToElementWithActionsAPI(e,t);let{x:s,y:n}=t.clickOffset;return this.moveTo(e,s,n).catch(o=>{if(Fe(o))return this.unsupportedActions.move=!0,this.moveToElementWithActionsAPI(e,t);throw o})}getMoveActions(e=1,t=1,s="viewport",n=0){return[{type:"pointerMove",duration:n,x:Math.floor(e)||1,y:Math.floor(t)||1,origin:s}]}moveWithActionsAPI(e){let t=this.getMoveActions(e.x,e.y);return this.actions([{type:"pointer",id:"mouse",actions:t}])}moveToElementWithActionsAPI(e,t){return this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(t,e)}]).catch(s=>{Ve.error("tried to use element origin but failed because of visibility, trying location",s);let n=this.computeAbsoluteMovement(t);return this.moveWithActionsAPI(n)})}getDragCoordinates(e){let t=e.filter(o=>o.event==="mousemove"||o.event==="pointermove"),s=Xe.first(t).pointerPosition,n=Xe.last(t).pointerPosition;return{xDiff:n.screenX-s.screenX,yDiff:n.screenY-s.screenY}}dragWithMoveTo(e,t,s,n,o){return this.moveTo(e,n,o).then(()=>this.buttonDown()).then(()=>this.moveTo(e,t,s)).then(()=>this.buttonUp())}dragWithActionsAPI(e,t,s,n,o){let i=this.getMoveActions(n,o,e,1),a=this.getClickActions(["pointerDown"],rr),c=this.getMoveActions(t,s,"pointer",1),u=this.getClickActions(["pointerUp"],rr);return this.actions([{type:"pointer",id:"mouse",actions:i.concat(a).concat(c).concat(u)}])}drag(e,t,s,n,o){let{width:i,height:a}=t,c=s-i/2+1,u=n-a/2;return this.getDragCoordinates(o).then(d=>{let{xDiff:p,yDiff:m}=d;return this.unsupportedActions.move?this.dragWithActionsAPI(e,p,m,c,u):this.dragWithMoveTo(e,p,m,c,u).catch(g=>{if(Fe(g))return this.unsupportedActions.move=!0,this.dragWithActionsAPI(e,p,m,c,u);throw g})})}getMoveRelativeSequence(e,t,s,n){let o=m=>m*m,i=(m,g)=>Math.sqrt(o(m.x-g.x)+o(m.y-g.y)),a={x:e,y:t},c={x:s,y:n},u=10,d=Math.round(i(a,c)/u),p=Array.apply([],new Array(d)).map(()=>({x:Math.round((c.x-a.x)/d),y:Math.round((c.y-a.y)/d)}));return[{x:1,y:1}].concat(p)}getMoveAbsoluteSequence(e,t,s,n){return this.getMoveRelativeSequence(e,t,s,n).reduce((i,a)=>{let c=Xe.last(i);return i.concat({x:Math.round(c.x+a.x),y:Math.round(c.y+a.y)})},[{x:Math.round(e),y:Math.round(t)}])}async dragAndDropWithGeneratedMoves(e,t,s){let{fromRect:n,fromX:o,fromY:i,toRect:a,toX:c,toY:u}=s,d=this.getMoveRelativeSequence(n.left+o,n.top+i,a.left+c,a.top+u);await this.moveTo(e,Math.round(o),Math.round(i)),await this.buttonDown();for(let p of d)await this.moveTo(null,p.x,p.y);return await this.moveTo(t,Math.round(c),Math.round(u)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(e){let{fromRect:t,fromX:s,fromY:n,toRect:o,toX:i,toY:a}=e,c=Math.round(t.left+s),u=Math.round(t.top+n),d=Math.round(o.left+i),p=Math.round(o.top+a),m=this.getMoveAbsoluteSequence(t.left+s,t.top+n,o.left+i,o.top+a),g=this.getMoveActions(c,u),f=this.getClickActions(["pointerDown"],rr),h=Xe.flatMap(m,w=>this.getMoveActions(w.x,w.y)),y=this.getMoveActions(d,p),b=this.getClickActions(["pointerUp"],rr),I=g.concat(f).concat(h).concat(y).concat(b);return this.actions([{type:"pointer",id:"mouse",actions:I}])}dragAndDrop(e,t,s){return this.isSafari()?this.unsupportedActions.move?this.dragAndDropWithActionsAPIWithGeneratedMoves(s):this.dragAndDropWithGeneratedMoves(e,t,s).catch(n=>{if(Fe(n))return this.unsupportedActions.move=!0,this.dragAndDropWithActionsAPIWithGeneratedMoves(s);throw n}):this.unsupportedActions.move?this.dragAndDropWithActionsAPI(s):this.dragAndDropOldAPI(e,t).catch(n=>{if(Fe(n))return this.unsupportedActions.move=!0,this.dragAndDropWithActionsAPI(s);throw n})}doubleClickFallback(e,t,s){return this.isSafari()?this.doubleClickWithJS(t):this.doubleClickWithActionsAPI(e,s)}doubleClick(e,t,s){return this.unsupportedActions.move||this.isSafari()?this.doubleClickFallback(e,t,s):this.doDoubleClick(e).catch(n=>{if(Fe(n))return this.unsupportedActions.move=!0,this.doubleClickFallback(e,t,s);throw n})}dragAndDropWithActionsAPI(e){let{fromRect:t,fromX:s,fromY:n,toRect:o,toX:i,toY:a}=e,c=Math.round(t.left+s),u=Math.round(t.top+n),d=Math.round(o.left+i),p=Math.round(o.top+a);return this.moveWithActionsAPI({x:c,y:u}).then(()=>{let m=this.getClickActionList(["pointerDown"],rr);return this.actions(m)}).then(()=>this.moveWithActionsAPI({x:d,y:p})).then(()=>{let m=this.getClickActionList(["pointerUp"],rr);return this.actions(m)})}getTabIds(){return this.windowHandles().then(e=>e.value)}isVisible(e){return this.elementIdDisplayed(wg(e)).then(t=>t.value)}getSource(){return this.source()}getElementRect(e){let t={width:0,height:0,top:0,left:0};return this.getElementLocation(e).catch(s=>Ve.error("error getting element location",{err:s})).then(s=>s!=null&&s.value?{top:s.value.y,left:s.value.x,width:s.value.width,height:s.value.height}:t)}end(){return Ve.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Ve.warn("failed to close session because session is undefined"),clearInterval(this.keepAliveTimer),super.end().catch(()=>{})}inViewCenter(e){return{x:e.width/2,y:e.height/2}}async submit(e){if(this.unsupportedActions.submit)return await super.submitFormManually(e);try{return await super.submitForm(e)}catch(t){if(Fe(t))return this.unsupportedActions.submit=!0,super.submitFormManually();throw t}}}});var vu,Eu,Pi,Su=T(()=>{"use strict";j();ye();Te();vu=x("lab-features-service"),Eu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(vu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let s=this.isLabsEnabledForCompany(t),n=s?await tl(e):[];this.featuresForProject=n,this.labBatman=s}catch(s){vu.error("failed loading lab features",{err:s,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=M.flags[e];this.validateAsLabFeatureFlag(t);let s=t.getValue();if(s==="disabled")return!1;if(s==="enabled")return!0;let{featuresForProject:n,labBatman:o}=this,i=n.find(c=>c.featureFlagName===e),a=i==null?void 0:i.enabled;return Boolean(o&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw vu.error(t,{featureFlagName:e.name}),new Error(t)}},Pi=new Eu});function Rg(r){let e=/^\\\\\?\\/.test(r),t=/[^\u0000-\u0080]+/.test(r);return e||t?r:r.replace(/\\/g,"/")}function hE(r,e,t,s,n={},o=void 0,i=void 0){let a=Object.keys(n).reduce((h,y)=>(h+=`
|
|
54
|
+
var ${y} = require('${Rg(n[y])}');
|
|
55
|
+
`,h),""),c=i?`
|
|
56
56
|
${Iu.default.toString()}
|
|
57
57
|
var fileBuffer = dataUriToBuffer('${i}');
|
|
58
|
-
`:"var fileBuffer = null;";function u(
|
|
58
|
+
`:"var fileBuffer = null;";function u(h,y){function b(){return h.apply(this,y)}return b.prototype=h.prototype,new b}let d=`
|
|
59
59
|
|
|
60
60
|
const getMessage = arguments => {
|
|
61
61
|
const args = Array.prototype.slice.call(arguments);
|
|
@@ -197,8 +197,8 @@ ${((x=n.warnings)==null?void 0:x.join(`
|
|
|
197
197
|
${p}
|
|
198
198
|
|
|
199
199
|
injectCode(params, args, incomingParams, context, code, done);
|
|
200
|
-
`,
|
|
201
|
-
var res = requireOrImportMethod('${
|
|
200
|
+
`,g=[],f=(0,Ai.spawn)(u(Function,["input","done","progress",m]));return te(new Promise(h=>{f.send({incomingParams:e,context:t,code:s}).on("message",y=>{let b=Object.assign({},y,{tstConsoleLogs:g});Ue.debug("Run code worker response",{messageWithLogs:b,transactionId:r}),h(b)}).on("progress",y=>{g.push(y)}).on("error",y=>{y.message==="malformed data: URI"?Ue.error("Run code worker error",{err:y,transactionId:r,fileDataUrl:i}):Ue.error("Run code worker error",{err:y,transactionId:r}),h({tstConsoleLogs:g,status:"failed",result:{resultValue:y==null?void 0:y.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{Ue.debug("Run code worker has been terminated",{transactionId:r})})}),o).catch(h=>{if(!(h instanceof Y))throw h;return Ue.warn("timeout to run code",{transactionId:r,err:h}),{tstConsoleLogs:g,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}).finally(()=>f==null?void 0:f.kill())}function yE(r){try{return{sync:!0,lib:globalThis.require(r)}}catch(e){if(e.code==="ERR_REQUIRE_ESM"){let t=globalThis.require("path");return{sync:!1,lib:Ru.promises.readFile(`${Ts}${t.sep}package.json`).then(n=>{let o=JSON.parse(n);return import(t.join(r,o.main||`${t.sep}index.js`))})}}throw e}}function bE(r,e,t,s,n={},o=void 0,i=void 0){Mr||(Mr=require("worker_threads"));let{Worker:a}=Mr,c=Object.keys(n).reduce((y,b)=>(y+=`
|
|
201
|
+
var res = requireOrImportMethod('${Rg(n[b])}');
|
|
202
202
|
if (res.sync) {
|
|
203
203
|
var ${b} = res.lib;
|
|
204
204
|
} else {
|
|
@@ -207,7 +207,7 @@ ${((x=n.warnings)==null?void 0:x.join(`
|
|
|
207
207
|
`,y),""),u=i?`
|
|
208
208
|
${Iu.default.toString()}
|
|
209
209
|
var fileBuffer = dataUriToBuffer('${i}');
|
|
210
|
-
`:"var fileBuffer = null;";function d(y,b){function
|
|
210
|
+
`:"var fileBuffer = null;";function d(y,b){function I(){return y.apply(this,b)}return I.prototype=y.prototype,new I}let p=`
|
|
211
211
|
const getMessage = arguments => {
|
|
212
212
|
const args = Array.prototype.slice.call(arguments);
|
|
213
213
|
let message = args.shift() + '';
|
|
@@ -323,7 +323,7 @@ ${((x=n.warnings)==null?void 0:x.join(`
|
|
|
323
323
|
});
|
|
324
324
|
}
|
|
325
325
|
}
|
|
326
|
-
`,
|
|
326
|
+
`,g=`
|
|
327
327
|
(async function() {
|
|
328
328
|
// A hack to fix an issue with stringified functions which use require. when compiling to JS, calls to require change to __require.
|
|
329
329
|
const __require = require;
|
|
@@ -366,71 +366,71 @@ ${((x=n.warnings)==null?void 0:x.join(`
|
|
|
366
366
|
injectCode(params, args, incomingParams, context, code);
|
|
367
367
|
});
|
|
368
368
|
})();
|
|
369
|
-
`,f=[],g=new a(h,{eval:!0});return te(new Promise(y=>{g.on("message",b=>{if(b.action==="finish"){let{data:x}=b,w=Object.assign({},x,{tstConsoleLogs:f});Ue.debug("Run code worker response",{messageWithLogs:w,transactionId:r}),y(w)}else b.action==="progress"&&f.push(b.data)}).on("error",b=>{b.message==="malformed data: URI"?Ue.error("Run code worker error",{err:b,transactionId:r,fileDataUrl:i}):Ue.error("Run code worker error",{err:b,transactionId:r}),y({tstConsoleLogs:f,status:"failed",result:{resultValue:b==null?void 0:b.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{Ue.debug("Run code worker has been terminated",{transactionId:r})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:s})}),o).catch(y=>{if(!(y instanceof X))throw y;return Ue.warn("timeout to run code",{transactionId:r,err:y}),{tstConsoleLogs:f,status:"failed",result:{resultValue:y==null?void 0:y.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}).finally(()=>g==null?void 0:g.terminate())}async function wE(r){try{await Ru.promises.rm(r,{recursive:!0,force:!0})}catch(e){Ue.warn("failed to remove install npm packages folder",{err:e})}}function Ih(r,e,t,s){return`${e}_${t}_${r}_${s}`}async function vs(r,e,t,s,n,o){let i=Ih(n,e,r,t),{data:a}=await TE(i,s,o);return a}async function Es(r,e,t,s,n,o,i,a,c,u){var f;let d=Object.fromEntries(((f=t.nodePackageParams)==null?void 0:f.map(g=>[g.paramName,g.testimPackageLocalLocation]))||[]),p=Ih(i,n,e,o);if(u){let g=await pn(u);g&&(c=g)}if(typeof Mr>"u")try{Mr=require("worker_threads")}catch{Mr=!1}Buffer.isBuffer(c)&&(Ue.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let m="data:,";if(c==="data:"&&(Ue.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=m),Mr&&M.flags.enableWorkerThreadsCliCodeExecution.isEnabled()){let g=await bE(p,t,s,r,d,a,c);return Object.assign({},g,{nodeVersion:process.version})}let h=await gE(p,t,s,r,d,a,c);return Object.assign({},h,{nodeVersion:process.version})}async function TE(r,e,t){let s=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=xh(),o=Ts.join(n,`/${r}`),i=global.proxyUri;async function a(){let c="";try{if(c=await Wp(o,s,i,t),Ue.info("npm package install finished",{transactionId:r,output:c,timeout:t}),Number(c.trim().split(" ")[1])<s.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(d=>{let p=$p(o,d.packageName),m=`${d.packageName}@${p}`,h=Ts.resolve(o,"node_modules",d.packageName);return Object.assign({},d,{packageFullName:m,packageLocalLocation:h})}),installFolder:o}}catch(u){throw Ue.warn("npm package install failed",{transactionId:r,err:u}),u}}try{return await te(a(),t)}catch(c){throw c instanceof X&&Ue.warn("timeout to install package",{packages:s,transactionId:r,err:c,timeout:t}),c}}function xh(){return Ts.join(Sh.tmpdir(),"/testim_local_packages")}function Ph(){let r=xh();return wE(r)}var Ru,Sh,Ts,Iu,Ai,Ue,Mr,Fr=T(()=>{"use strict";Ru=E(require("fs")),Sh=E(require("os")),Ts=E(require("path"));U();nn();Iu=E(require("data-uri-to-buffer")),Ai=require("threads");q();j();Te();ye();Ue=I("cli-service");Ai.config.set({basepath:{node:__dirname}})});var nr={};W(nr,{run:()=>EE});function vE(r,e){try{let t=e.defaults.enforceMaximumJsResultSize,s=M.flags.maximumJsResultSize.getValue(),n=JSON.stringify(r).length>s;return t?n:!1}catch{return!1}}var EE,Ah=T(()=>{"use strict";Fr();q();ye();EE=async(r,e,t)=>{let{code:s,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:u,runTimeout:d,fileDataUrl:p,s3filepath:m}=e.data;try{let h=await Es(s,n,o,i,a,c,u,d,p,m);return h&&vE({result:h.result,tstConsoleLogs:h.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:h,success:!0}}catch(h){throw h instanceof X?new Error("Timeout while running action"):h}}});var xu,Rs,Pu=T(()=>{"use strict";j();xu=I("cookies-utils"),Rs=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(s){throw xu.error("failed to set cookie",{err:s}),s}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw xu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw xu.error("failed to remove cookie",{err:t}),t}}}});var Au,Ch,Is,Cu=T(()=>{"use strict";U();Au=E(require("p-retry"));U();j();q();Ch=I("window-utils"),Is=class{constructor(e,t){this.id=e,this.driver=t}getElementFromPoint(e,t){function s(n,o){var i=document.elementFromPoint(n,o);return{testimId:i?i.getAttribute("testim_dom_element_id"):null,tagName:i?i.tagName:null}}return this.driver.executeJS(s,e,t).then(n=>n.value)}getLocation(){return this.driver.getUrl()}stopListeningToScroll(){return Promise.resolve()}resumeListeningToScroll(){return Promise.resolve()}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(s){var n="scrollBehavior"in document.documentElement.style;return n?window.scrollTo({left:s.x,top:s.y,behavior:"instant"}):window.scrollTo(s.x,s.y)}return this.driver.executeJS(t,e)}getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}return this.driver.executeJS(e).then(t=>t.value)}navigate(e,t=15e3){let s=this;async function n(o=3){try{await s.driver.url(e)}catch(i){let a=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&a&&o>0)return Ch.warn("selenium navigation failed. retrying to navigate",{err:i}),await se(1500),n(o-1);throw!i.seleniumStack&&a&&Ch.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}}return Promise.race([n(),se(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),se(e)])}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}getFullPageSize(){function e(){var t=document.body,s=document.documentElement,n=Math.max(t.scrollHeight,t.offsetHeight,s.clientHeight,s.scrollHeight,s.offsetHeight),o=Math.max(t.scrollWidth,t.offsetWidth,s.clientWidth,s.scrollWidth,s.offsetWidth);return{height:n,width:o}}return this.driver.executeJS(e).then(t=>t.value)}extractToNewWindow(){return Promise.resolve()}async checkSize(e){await se(1e3);let t=await this.getViewportSize();return t.width!==e.width||t.height!==e.height?Promise.reject({actualSize:t,expectedSize:e}):{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){var s;if(typeof location<"u")s=location;else if(typeof window<"u"&&typeof window.location<"u")s=window.location;else return!1;return s.href!=="chrome-error://chromewebdata/"&&s.href!=="safari-resource:/ErrorPage.html"&&s.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&s.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new lt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Au.default)(()=>this.driver.getBrowserAndOS(),{retries:3});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Au.default)(()=>this.driver.getUserAgentInfo(),{retries:3})}}});var ku,Ci,kh=T(()=>{"use strict";ku=E(require("p-retry")),Ci=class{constructor(e,t,s={takeScreenshots:!0}){this.tabId=e,this.driver=t,this.options=s}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,s=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),n=()=>Promise.all([s,this.driver.takeScreenshot()]),[o,i]=await(0,ku.default)(n,{retries:e,minTimeout:t}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,s=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,ku.default)(o,{retries:t,minTimeout:s}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}return this.driver.executeJS(e).then(t=>t.value)}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function _h(r,e){let t=e.image||e,s=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data\:[^;]*\;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=r.offset||{top:0,left:0};if(o.top*=s,o.left*=s,!r.elementRect)return SE.warn("missing elementRect",Lh.omit(r,"image")),{};let{elementRect:i}=r,a=await xs.default.read(Buffer.from(n[1],"base64")),c=i.left*s+o.left*s,u=i.top*s+o.top*s,d=i.width*s,p=i.height*s;c<0&&(d+=c,d=d<0?0:d,c=0),u<0&&(p+=u,p=p<0?0:p,u=0);let m=a.bitmap.width,h=a.bitmap.height;if(c+d>m&&(d=m-c),u+p>h&&(p=h-u),p<=0||d<=0)throw new kn("height or width is equal or lower than zero");return{elementImage:await a.crop(c,u,d,p).getBase64Async(xs.default.MIME_PNG)}}async function RE(r,e){let t=await xs.default.read(r.width,r.height);for(let n of e){let o=n.image.match(/^data\:[^;]*\;base64,(.*)$/),i=await xs.default.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,u=>{if(u){c(u);return}a()})})}return await t.getBase64Async(xs.default.MIME_PNG)}function IE(r,e){return RE(r,e)}function xE(){return Promise.resolve()}function PE(r){function e(s){return typeof r[s]=="string"&&r[s].startsWith("data")}function t(s){return xE(r[s]).then(n=>({key:s,url:n}))}return Promise.all(Object.keys(r).filter(e).map(t)).then(s=>s.reduce((n,o)=>(n[o.key]=o.url,n),r))}function Oh(r,e){return e=e||1,r=r||{left:0,top:0,width:0,height:0},{left:e*Math.round(r.left),top:e*Math.round(r.top),width:e*Math.round(r.width),height:e*Math.round(r.height),pixelRatio:e}}var Lh,xs,SE,kn,ki,Nh=T(()=>{"use strict";Lh=E(require("lodash"));U();xs=E(require("jimp"));j();SE=I("image-capture-utils"),kn=class extends Error{constructor(e){super(e),this.rectIsOutsideOfImageError=!0,Object.setPrototypeOf(this,kn.prototype)}};ki=class{constructor(e,t,s){this.windowUtils=t,this.screenshotUtils=s}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){e.areas&&(e=e.areas);let t=await this.screenshotUtils.takeScreenshot(),s=await _h(e,t);return s.screenImage=t.image,s.absoluteScreenHighlight=Oh(e.elementRect,t.devicePixelRatio),s}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){e.areas&&(e=e.areas);let t=await this.screenshotUtils.takeScreenshot();return PE({screenImage:t.image,absoluteScreenHighlight:Oh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:s}=this,n=()=>se(250),o=Boolean(e);async function i(m,h){o?await t.scrollToPositionWithoutAnimation(m):await t.scrollToPosition(m),await n();let f=await s.takeScreenshot(),g=await _h({elementRect:h},f);return{position:{left:m.x+h.left,top:m.y+h.top},size:{width:h.width,height:h.height},image:g.elementImage}}async function a(m){let h=[];for(let f of m){let g=await i(f.scrollPos,f.cropData);h.push(g)}return h}function c(m,h){let f=Math.max(m.width,h.width),g=h.width,y=Math.max(m.height,h.height),b=h.height,x=Array.from({length:Math.ceil(f/g)},(v,R)=>({scrollX:Math.min(R*g,f-g),cropX:R*g-Math.min(R*g,f-g),cropW:g-(R*g-Math.min(R*g,f-g))})),w=Array.from({length:Math.ceil(y/b)},(v,R)=>({scrollY:Math.min(R*b,y-b),cropY:R*b-Math.min(R*b,y-b),cropH:b-(R*b-Math.min(R*b,y-b))}));return x.flatMap(v=>w.map(R=>({scrollPos:{x:v.scrollX,y:R.scrollY},cropData:{top:R.cropY,left:v.cropX,width:v.cropW,height:R.cropH}})))}async function u(m,h){let f=await t.getCurrentScrollPosition(),g=c(m,h),y=await a(g);return await t.scrollToPosition(f),IE(m,y)}let[d,p]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await u(d,p)}}});var Dh,_i,Oi,Mh=T(()=>{"use strict";Dh=E(require("semver"));U();j();Cu();kh();Nh();Ee();_i=I("tab-service"),Oi=class{constructor(e){this.driver=e,this._utils={},this.sessionTabs={},this.pendingTabs={},this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(s=>!t[s].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(s=>{let n=this.getTabInfo(e,s);return`tabId=${s}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}addNewTab(e,t,s,n={}){return this.addedTabs[e].has(t)?Promise.resolve():(this.addedTabs[e].add(t),_i.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${s}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,s,n))}addOpenerStepId(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s}addOpenerStep(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=s.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let s=this.getAllTabInfos(e);Object.keys(s).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,s,n,o={}){let i=await this.getTabDetails(t,e,o),a=z();function c(u){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!u.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:s,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,s,n,o={}){let i=await this.buildTabInfo(e,t,s,n,o),a=new Is(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:()=>Promise.resolve()},windowUtils:a,imageCaptureUtils:new ki(t,a,new Ci(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let s=this.sessionTabs[e].tabInfos[t];return this._utils[s.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(s=>this._utils[s].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let s=this.getAllTabInfos(e),n=Object.keys(s).map(i=>s[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,s){let n=s.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,s,n){let{urlUtils:o}=re(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),u=n(a),d=s.map(p=>o.urlBreaker(p)).map(p=>n(p)).filter(p=>p===c);return c===u&&d.length===1}isSameTab(e,t,s){let{tabMatcher:n}=re();if(n){let u=this.getAllTabInfos(e),d=Object.keys(u).map(p=>u[p]);return n.isSameTab(d,t,s)}if(t.isMain&&s.isMain||t.openerStepId&&s.openerStepId&&t.openerStepId===s.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(u=>o[u].url);if(this.exactUrlMatch(t,s,i))return!0;let a=u=>`${u.domain}/${u.path.join("/")}`;if(this.singleExactMatchForParts(t,s,i,a))return!0;let c=u=>`${u.domain}/${u.path.join("/")}#${u.hash}`;return!!(this.singleExactMatchForParts(t,s,i,c)||t.order===s.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(s=>t[s]).find(s=>s.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(s=>t[s].isMain)}isMainTabExists(e){return this.getMainTabId(e)?Promise.resolve(!0):Promise.resolve(!1)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(s=>this.removeTabInfo(e,s))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(s=>!t[s].isMain).forEach(s=>this.removeTabInfo(e,s)),this.sessionTabs[e].tabCount=1}switchTab(e,t,{forceSwitch:s=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;return typeof n=="number"&&n>1||s?this.driver.switchTab(e):Promise.resolve()}getTabDetails(e,t,s={}){return this.switchTab(e,t,s).then(()=>{if(s.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");return s.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value)),Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]).then(([o,i,a])=>({title:o,url:i,isMainTab:a}),o=>(_i.error("failed to get url or title",{err:o}),{title:"",url:""}))}).catch(n=>{_i.error("failed to switch to tab",{tabId:e,err:n})})}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(s=>!this.getAllTabIds(e).includes(s))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await se(500),await this.waitForTabToOpen(e))}async tryToAddTab(e,t){if(this.pendingTabs[e])return;let s=await this.getUnregisteredTabId(e);s&&(await this.addNewTab(e,s),await this.addFrameHandler(s),this.sessionTabs[e].currentTab=null)}addNewPopup(e,t){let s=this.getAllTabInfos(e);return Object.keys(s).find(o=>s[o].openerStepId===t)?Promise.resolve():this.pendingTabs[e]?(_i.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t,Promise.resolve()):(this.pendingTabs[e]=t,this.waitForTabToOpen(e).then(o=>this.addNewTab(e,o,this.pendingTabs[e]).then(()=>this.addFrameHandler(o)).then(()=>delete this.pendingTabs[e]).then(()=>this.sessionTabs[e].currentTab=null)))}waitToPendingTabs(e,t){let n=3e3,o=this;return t?new Promise(i=>{function a(){o.pendingTabs[e]===t&&n-500>0?(n-=500,setTimeout(a,500)):i()}a()}):Promise.resolve()}isMainTabIncognito(){return Promise.resolve(!1)}isInvalidStepVersion(e){let t=Dh.lt(e._version||e.version,"1.2.0"),s=!!e.parameterValues,n=s&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!s||n)}getTabIdByTabInfo(e,t){var i,a;let{tabMatcher:s,commonConstants:n}=re();if(this.isInvalidStepVersion(t))return Promise.reject({success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((i=t.useCurrentTab)!=null&&i.call(t))return this.driver.getCurrentTabId().then(c=>{if(c)return c;let u=this.getMainTabId(e);if(u)return u;throw new Error("Current tab not found")});let o=(a=t.tabInfo)==null?void 0:a.openerStepId;return this.waitToPendingTabs(e,o).then(()=>{let c;if(s){let u=this.getAllTabIds(e).map(d=>Object.assign({},this.getTabInfo(e,d),{tabId:d})).filter(d=>!d.isClosed);c=s.matchTabs(t,u)}else{let u=t.tabInfo;u?c=this.getAllTabIds(e).find(d=>{let p=this.getTabInfo(e,d);return this.isSameTab(e,p,u)}):c=this.getMainTabId(e)}return c?this.sessionTabs[e].currentTab===c?c:this.switchTab(c,e).then(()=>(this.sessionTabs[e].currentTab=c,c)).catch(u=>{let d=["no such window","no window found","the window could not be found"];if(u.message&&d.some(p=>u.message.toLowerCase().includes(p)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[c].isClosed=!0,this.getTabIdByTabInfo(e,t);throw u}):this.tryToAddTab(e,o).then(()=>{throw new Error("No tab ID found")})})}}});var _u,Li,Ou=T(()=>{"use strict";_u=class{constructor(){}select(){return console.log(`
|
|
369
|
+
`,f=[],h=new a(g,{eval:!0});return te(new Promise(y=>{h.on("message",b=>{if(b.action==="finish"){let{data:I}=b,w=Object.assign({},I,{tstConsoleLogs:f});Ue.debug("Run code worker response",{messageWithLogs:w,transactionId:r}),y(w)}else b.action==="progress"&&f.push(b.data)}).on("error",b=>{b.message==="malformed data: URI"?Ue.error("Run code worker error",{err:b,transactionId:r,fileDataUrl:i}):Ue.error("Run code worker error",{err:b,transactionId:r}),y({tstConsoleLogs:f,status:"failed",result:{resultValue:b==null?void 0:b.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{Ue.debug("Run code worker has been terminated",{transactionId:r})}),h.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:s})}),o).catch(y=>{if(!(y instanceof Y))throw y;return Ue.warn("timeout to run code",{transactionId:r,err:y}),{tstConsoleLogs:f,status:"failed",result:{resultValue:y==null?void 0:y.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}).finally(()=>h==null?void 0:h.terminate())}async function wE(r){try{await Ru.promises.rm(r,{recursive:!0,force:!0})}catch(e){Ue.warn("failed to remove install npm packages folder",{err:e})}}function Ig(r,e,t,s){return`${e}_${t}_${r}_${s}`}async function vs(r,e,t,s,n,o){let i=Ig(n,e,r,t),{data:a}=await TE(i,s,o);return a}async function Es(r,e,t,s,n,o,i,a,c,u){var f;let d=Object.fromEntries(((f=t.nodePackageParams)==null?void 0:f.map(h=>[h.paramName,h.testimPackageLocalLocation]))||[]),p=Ig(i,n,e,o);if(u){let h=await pn(u);h&&(c=h)}if(typeof Mr>"u")try{Mr=require("worker_threads")}catch{Mr=!1}Buffer.isBuffer(c)&&(Ue.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let m="data:,";if(c==="data:"&&(Ue.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=m),Mr&&M.flags.enableWorkerThreadsCliCodeExecution.isEnabled()){let h=await bE(p,t,s,r,d,a,c);return Object.assign({},h,{nodeVersion:process.version})}let g=await hE(p,t,s,r,d,a,c);return Object.assign({},g,{nodeVersion:process.version})}async function TE(r,e,t){let s=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=xg(),o=Ts.join(n,`/${r}`),i=global.proxyUri;async function a(){let c="";try{if(c=await Wp(o,s,i,t),Ue.info("npm package install finished",{transactionId:r,output:c,timeout:t}),Number(c.trim().split(" ")[1])<s.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(d=>{let p=$p(o,d.packageName),m=`${d.packageName}@${p}`,g=Ts.resolve(o,"node_modules",d.packageName);return Object.assign({},d,{packageFullName:m,packageLocalLocation:g})}),installFolder:o}}catch(u){throw Ue.warn("npm package install failed",{transactionId:r,err:u}),u}}try{return await te(a(),t)}catch(c){throw c instanceof Y&&Ue.warn("timeout to install package",{packages:s,transactionId:r,err:c,timeout:t}),c}}function xg(){return Ts.join(Sg.tmpdir(),"/testim_local_packages")}function Pg(){let r=xg();return wE(r)}var Ru,Sg,Ts,Iu,Ai,Ue,Mr,Fr=T(()=>{"use strict";Ru=E(require("fs")),Sg=E(require("os")),Ts=E(require("path"));U();nn();Iu=E(require("data-uri-to-buffer")),Ai=require("threads");q();j();Te();ye();Ue=x("cli-service");Ai.config.set({basepath:{node:__dirname}})});var nr={};W(nr,{run:()=>EE});function vE(r,e){try{let t=e.defaults.enforceMaximumJsResultSize,s=M.flags.maximumJsResultSize.getValue(),n=JSON.stringify(r).length>s;return t?n:!1}catch{return!1}}var EE,Ag=T(()=>{"use strict";Fr();q();ye();EE=async(r,e,t)=>{let{code:s,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:u,runTimeout:d,fileDataUrl:p,s3filepath:m}=e.data;try{let g=await Es(s,n,o,i,a,c,u,d,p,m);return g&&vE({result:g.result,tstConsoleLogs:g.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:g,success:!0}}catch(g){throw g instanceof Y?new Error("Timeout while running action"):g}}});var xu,Rs,Pu=T(()=>{"use strict";j();xu=x("cookies-utils"),Rs=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(s){throw xu.error("failed to set cookie",{err:s}),s}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw xu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw xu.error("failed to remove cookie",{err:t}),t}}}});var Au,Cg,Is,Cu=T(()=>{"use strict";U();Au=E(require("p-retry"));U();j();q();Cg=x("window-utils"),Is=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function s(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(s,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(s){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:s.x,top:s.y,behavior:"instant"}):window.scrollTo(s.x,s.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let s=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return Cg.warn("selenium navigation failed. retrying to navigate",{err:o}),await se(1500),s(n-1);throw!o.seleniumStack&&i&&Cg.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([s(),se(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),se(e)])}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let s=document.body,n=document.documentElement,o=Math.max(s.scrollHeight,s.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(s.scrollWidth,s.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await se(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let s;if(typeof location<"u")s=location;else if(typeof window<"u"&&typeof window.location<"u")s=window.location;else return!1;return s.href!=="chrome-error://chromewebdata/"&&s.href!=="safari-resource:/ErrorPage.html"&&s.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&s.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new lt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Au.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Au.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var ku,Ci,kg=T(()=>{"use strict";ku=E(require("p-retry")),Ci=class{constructor(e,t,s={takeScreenshots:!0}){this.tabId=e,this.driver=t,this.options=s}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,s=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),n=()=>Promise.all([s,this.driver.takeScreenshot()]),[o,i]=await(0,ku.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,s=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,ku.default)(o,{retries:t,minTimeout:s,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}return this.driver.executeJS(e).then(t=>t.value)}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function _g(r,e){let t=e.image||e,s=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data\:[^;]*\;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=r.offset||{top:0,left:0};if(o.top*=s,o.left*=s,!r.elementRect)return SE.warn("missing elementRect",Lg.omit(r,"image")),{};let{elementRect:i}=r,a=await xs.default.read(Buffer.from(n[1],"base64")),c=i.left*s+o.left*s,u=i.top*s+o.top*s,d=i.width*s,p=i.height*s;c<0&&(d+=c,d=d<0?0:d,c=0),u<0&&(p+=u,p=p<0?0:p,u=0);let m=a.bitmap.width,g=a.bitmap.height;if(c+d>m&&(d=m-c),u+p>g&&(p=g-u),p<=0||d<=0)throw new kn("height or width is equal or lower than zero");return{elementImage:await a.crop(c,u,d,p).getBase64Async(xs.default.MIME_PNG)}}async function RE(r,e){let t=await xs.default.read(r.width,r.height);for(let n of e){let o=n.image.match(/^data\:[^;]*\;base64,(.*)$/),i=await xs.default.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,u=>{if(u){c(u);return}a()})})}return await t.getBase64Async(xs.default.MIME_PNG)}function IE(r,e){return RE(r,e)}function xE(){return Promise.resolve()}function PE(r){function e(s){return typeof r[s]=="string"&&r[s].startsWith("data")}function t(s){return xE(r[s]).then(n=>({key:s,url:n}))}return Promise.all(Object.keys(r).filter(e).map(t)).then(s=>s.reduce((n,o)=>(n[o.key]=o.url,n),r))}function Og(r,e){return e=e||1,r=r||{left:0,top:0,width:0,height:0},{left:e*Math.round(r.left),top:e*Math.round(r.top),width:e*Math.round(r.width),height:e*Math.round(r.height),pixelRatio:e}}var Lg,xs,SE,kn,ki,Dg=T(()=>{"use strict";Lg=E(require("lodash"));U();xs=E(require("jimp"));j();SE=x("image-capture-utils"),kn=class extends Error{constructor(e){super(e),this.rectIsOutsideOfImageError=!0,Object.setPrototypeOf(this,kn.prototype)}};ki=class{constructor(e,t,s){this.windowUtils=t,this.screenshotUtils=s}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){e.areas&&(e=e.areas);let t=await this.screenshotUtils.takeScreenshot(),s=await _g(e,t);return s.screenImage=t.image,s.absoluteScreenHighlight=Og(e.elementRect,t.devicePixelRatio),s}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){e.areas&&(e=e.areas);let t=await this.screenshotUtils.takeScreenshot();return PE({screenImage:t.image,absoluteScreenHighlight:Og(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:s}=this,n=()=>se(250),o=Boolean(e);async function i(m,g){o?await t.scrollToPositionWithoutAnimation(m):await t.scrollToPosition(m),await n();let f=await s.takeScreenshot(),h=await _g({elementRect:g},f);return{position:{left:m.x+g.left,top:m.y+g.top},size:{width:g.width,height:g.height},image:h.elementImage}}async function a(m){let g=[];for(let f of m){let h=await i(f.scrollPos,f.cropData);g.push(h)}return g}function c(m,g){let f=Math.max(m.width,g.width),h=g.width,y=Math.max(m.height,g.height),b=g.height,I=Array.from({length:Math.ceil(f/h)},(v,R)=>({scrollX:Math.min(R*h,f-h),cropX:R*h-Math.min(R*h,f-h),cropW:h-(R*h-Math.min(R*h,f-h))})),w=Array.from({length:Math.ceil(y/b)},(v,R)=>({scrollY:Math.min(R*b,y-b),cropY:R*b-Math.min(R*b,y-b),cropH:b-(R*b-Math.min(R*b,y-b))}));return I.flatMap(v=>w.map(R=>({scrollPos:{x:v.scrollX,y:R.scrollY},cropData:{top:R.cropY,left:v.cropX,width:v.cropW,height:R.cropH}})))}async function u(m,g){let f=await t.getCurrentScrollPosition(),h=c(m,g),y=await a(h);return await t.scrollToPosition(f),IE(m,y)}let[d,p]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await u(d,p)}}});var Ng,_i,Oi,Mg=T(()=>{"use strict";Ng=E(require("semver"));U();j();Cu();kg();Dg();Ee();_i=x("tab-service"),Oi=class{constructor(e){this.driver=e,this._utils={},this.sessionTabs={},this.pendingTabs={},this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(s=>!t[s].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(s=>{let n=this.getTabInfo(e,s);return`tabId=${s}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}addNewTab(e,t,s,n={}){return this.addedTabs[e].has(t)?Promise.resolve():(this.addedTabs[e].add(t),_i.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${s}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,s,n))}addOpenerStepId(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s}addOpenerStep(e,t,s){this.sessionTabs[e].tabInfos[t].openerStepId=s.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=s.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let s=this.getAllTabInfos(e);Object.keys(s).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,s,n,o={}){let i=await this.getTabDetails(t,e,o),a=z();function c(u){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!u.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:s,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,s,n,o={}){let i=await this.buildTabInfo(e,t,s,n,o),a=new Is(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:()=>Promise.resolve()},windowUtils:a,imageCaptureUtils:new ki(t,a,new Ci(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let s=this.sessionTabs[e].tabInfos[t];return this._utils[s.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(s=>this._utils[s].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let s=this.getAllTabInfos(e),n=Object.keys(s).map(i=>s[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,s){let n=s.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,s,n){let{urlUtils:o}=re(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),u=n(a),d=s.map(p=>o.urlBreaker(p)).map(p=>n(p)).filter(p=>p===c);return c===u&&d.length===1}isSameTab(e,t,s){let{tabMatcher:n}=re();if(n){let u=this.getAllTabInfos(e),d=Object.keys(u).map(p=>u[p]);return n.isSameTab(d,t,s)}if(t.isMain&&s.isMain||t.openerStepId&&s.openerStepId&&t.openerStepId===s.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(u=>o[u].url);if(this.exactUrlMatch(t,s,i))return!0;let a=u=>`${u.domain}/${u.path.join("/")}`;if(this.singleExactMatchForParts(t,s,i,a))return!0;let c=u=>`${u.domain}/${u.path.join("/")}#${u.hash}`;return!!(this.singleExactMatchForParts(t,s,i,c)||t.order===s.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(s=>t[s]).find(s=>s.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(s=>t[s].isMain)}isMainTabExists(e){return this.getMainTabId(e)?Promise.resolve(!0):Promise.resolve(!1)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(s=>this.removeTabInfo(e,s))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(s=>!t[s].isMain).forEach(s=>this.removeTabInfo(e,s)),this.sessionTabs[e].tabCount=1}switchTab(e,t,{forceSwitch:s=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;return typeof n=="number"&&n>1||s?this.driver.switchTab(e):Promise.resolve()}getTabDetails(e,t,s={}){return this.switchTab(e,t,s).then(()=>{if(s.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");return s.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value)),Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]).then(([o,i,a])=>({title:o,url:i,isMainTab:a}),o=>(_i.error("failed to get url or title",{err:o}),{title:"",url:""}))}).catch(n=>{_i.error("failed to switch to tab",{tabId:e,err:n})})}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(s=>!this.getAllTabIds(e).includes(s))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await se(500),await this.waitForTabToOpen(e))}async tryToAddTab(e,t){if(this.pendingTabs[e])return;let s=await this.getUnregisteredTabId(e);s&&(await this.addNewTab(e,s),await this.addFrameHandler(s),this.sessionTabs[e].currentTab=null)}addNewPopup(e,t){let s=this.getAllTabInfos(e);return Object.keys(s).find(o=>s[o].openerStepId===t)?Promise.resolve():this.pendingTabs[e]?(_i.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t,Promise.resolve()):(this.pendingTabs[e]=t,this.waitForTabToOpen(e).then(o=>this.addNewTab(e,o,this.pendingTabs[e]).then(()=>this.addFrameHandler(o)).then(()=>delete this.pendingTabs[e]).then(()=>this.sessionTabs[e].currentTab=null)))}waitToPendingTabs(e,t){let n=3e3,o=this;return t?new Promise(i=>{function a(){o.pendingTabs[e]===t&&n-500>0?(n-=500,setTimeout(a,500)):i()}a()}):Promise.resolve()}isMainTabIncognito(){return Promise.resolve(!1)}isInvalidStepVersion(e){let t=Ng.lt(e._version||e.version,"1.2.0"),s=!!e.parameterValues,n=s&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!s||n)}getTabIdByTabInfo(e,t){var i,a;let{tabMatcher:s,commonConstants:n}=re();if(this.isInvalidStepVersion(t))return Promise.reject({success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((i=t.useCurrentTab)!=null&&i.call(t))return this.driver.getCurrentTabId().then(c=>{if(c)return c;let u=this.getMainTabId(e);if(u)return u;throw new Error("Current tab not found")});let o=(a=t.tabInfo)==null?void 0:a.openerStepId;return this.waitToPendingTabs(e,o).then(()=>{let c;if(s){let u=this.getAllTabIds(e).map(d=>Object.assign({},this.getTabInfo(e,d),{tabId:d})).filter(d=>!d.isClosed);c=s.matchTabs(t,u)}else{let u=t.tabInfo;u?c=this.getAllTabIds(e).find(d=>{let p=this.getTabInfo(e,d);return this.isSameTab(e,p,u)}):c=this.getMainTabId(e)}return c?this.sessionTabs[e].currentTab===c?c:this.switchTab(c,e).then(()=>(this.sessionTabs[e].currentTab=c,c)).catch(u=>{let d=["no such window","no window found","the window could not be found"];if(u.message&&d.some(p=>u.message.toLowerCase().includes(p)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[c].isClosed=!0,this.getTabIdByTabInfo(e,t);throw u}):this.tryToAddTab(e,o).then(()=>{throw new Error("No tab ID found")})})}}});var _u,Li,Ou=T(()=>{"use strict";_u=class{constructor(){}select(){return console.log(`
|
|
370
370
|
internal error - cant use port selector in selenium!!!!
|
|
371
|
-
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Li=new _u});var Ps,Lu=T(()=>{"use strict";Pu();Ee();Ps=class{constructor(e,t){this.driver=e,this._abortedSteps=[],this.cookieUtils=t||new Rs(this.driver)}get sessionPlayerInit(){return re()}getTimeStamp(){return Date.now()}getTestimId(e){if(!e)return;let{locatorBuilderUtils:t}=this.sessionPlayerInit,s=t.TESTIM_ID_FIELD_NAME;return t.isEmptyResult(e)?t.EMPTY_RESULT_ID:e.getAttribute(s)}resetAbort(){this._abortedSteps=[]}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}restoreNativeAlerts(){}executeOverloadNativeAlertsInFrame(){}getClickOffset(e,t){let{utils:s}=this.sessionPlayerInit;return e&&s.isWithinBounds(0,t.width,e.x)&&s.isWithinBounds(0,t.height,e.y)?{xOffset:e.x,yOffset:e.y}:{xOffset:t.width/2,yOffset:t.height/2}}executeInAut(e,t){return this.driver.executeJS(t).then(s=>s.value)}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t,s){return this.driver.markDynamicParent(e,t,s)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e,t){return this.cookieUtils.set(e)}getNextDynamicParent(e,t){let s=`return ${this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t)}`;return this.driver.executeJS(s).then(n=>n.value)}}});function
|
|
372
|
-
Action required: Please allow opening a websockets connection to ${ge} 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",()=>{Di.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let s={query:{projectId:e},requestTimeout:$h,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=`${ge}/${t}`,this._socket=Fu.connect(this.url,s),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let s={query:{projectId:e},requestTimeout:$h,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=`${ge}/${t}`,this._socket=Fu.connect(this.url,s),this.addSocketHandlers()}emitPromise(e,t){let s={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(s[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Wh.default)(()=>te(n(),NE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(s).length>0&&Di.error("Bad acknowledge from socket emit",{errorneousEvents:s})}),this.emitPromiseQueue}}});var Uu,jr,Gh=T(()=>{"use strict";Mi();Uu=class extends or{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,s,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===s&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,s){return this.emitPromise("testResult:join",{resultId:t,testId:s})}async joinToTestResult(t,s){this.rooms[t]||(this.joinRoom(t,s),await this.emitJoinRoom(t,s))}emitLeaveRoom(t,s){return this.emitPromise("testResult:leave",{resultId:t,testId:s})}leaveTestResult(t,s){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,s)):Promise.resolve()}getSocket(){return this._socket}},jr=new Uu});var qh={};W(qh,{testResultService:()=>Qe});var Vh,ju,Qe,As=T(()=>{"use strict";Vh=require("events");_n();ae();ye();Gh();ju=class extends Vh.EventEmitter{init(e){if(M.flags.useNewWSCLI.isEnabled()){We.onConnect=()=>this.emit("socket-connected");return}jr.init(e),jr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return M.flags.useNewWSCLI.isEnabled()?We.addFilter(`${e}:testResult`,{resultId:e,testId:t},[rt.TEST_RESULT_UPDATED,rt.TEST_RESULT_CREATED]):jr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(M.flags.useNewWSCLI.isEnabled()){We.removeFilter(`${e}:testResult`,[rt.TEST_RESULT_UPDATED,rt.TEST_RESULT_CREATED]);return}await jr.leaveTestResult(e,t)}listenToTestResult(e,t,s){if(M.flags.useNewWSCLI.isEnabled()){We.listenTo(`${e}:testResult`,[rt.TEST_RESULT_UPDATED,rt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>s(n));return}jr.listenToTestResult(e,t,s)}getSocket(){if(!M.flags.useNewWSCLI.isEnabled())return jr.getSocket()}},Qe=new ju});var $,ce=T(()=>{"use strict";Ee();$=class{constructor(e,t,s,n={},o=void 0,i=void 0,a={}){this.step=e,this.context=t,this.frameHandler=s,this.frameId=0,this.stepActionUtils=o,this.locateElementPlayer=i,this.exportsGlobal=n,this.exportsTest=a}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return re()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(e,t){var s;try{return{success:!0,...await this.performAction(e,t)}}catch(n){let o=(n==null?void 0:n.message)||((s=n==null?void 0:n.seleniumStack)==null?void 0:s.message),i=n==null?void 0:n.displayMessage;return{success:!1,reason:o,exception:n,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${o}`,error:i||o}}}}}});function FE(){let r=t=>Math.round(t/1024/1024*100)/100,e=process.memoryUsage();return{isOverThreshold:r(e.rss)>ME,rss:`${r(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${r(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${r(e.heapUsed)} MB -> actual memory used during the execution`,external:`${r(e.external)} MB -> V8 external memory`}}function UE(r,e,t){let s=FE();s.isOverThreshold&&ir.info(`using ${r} to parse html`,{memoryUsage:s,testName:e,testResultId:t})}function jE(r){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await r.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return r.getElementRect(e)},getOffsets(e){return Promise.resolve([e.frameOffset||{}])},getOptimizedDom(e){let s=new Hh.DOMParser().parseFromString("<html><body></body></html>","text/html");return s.body.outerHTML=e,Object.assign(s,{parsedUsingLinkedom:!0})},htmlStringToDom(e,t,s,n,o=!1){UE(o?"linkedom":"jsdom",r.testName,r.testResultId);let i;if(o)i=this.getOptimizedDom(e);else{let a=new Fi.VirtualConsole;i=new Fi.JSDOM(e,{virtualConsole:a}).window.document}return Object.assign(i,{TESTIM_URL:t})},shouldUseNativeVisibilityCheck(e,t,s,n){return e.opacity===0||e.isShadowed?!1:s===void 0||n===void 0?!0:M.flags.useClickimVisibilityChecks.isEnabled()?!1:t.isSafari()?M.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0},async isVisible(e,t,s,n,o,i,a){let{locatorBuilderUtils:c,codeSnippets:u,visibilityUtils:d,positionUtils:p}=re();if(this.shouldUseNativeVisibilityCheck(n,r,d,p))return r.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await r.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let f=[p.calculateElementMiddlePoint(s),p.calculateClickPoint(n.clickOffset,s)].filter(Boolean),g=u.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,f,!1,n),y;try{y=await r.execute(`return ${g}`)}catch(R){throw ir.error("failed to execute getVisibilityCode",{err:R}),R}let{value:b}=y||{},x=b.elementVisibilityInfo||DE,[w,v]=b.elementsFromPointResults||[null,null];return d.checkElementVisibility(x,n,v,w,a,t)},scrollToElement(e,t){let{codeSnippets:s}=re(),n=s.scrollToElement;return r.execute(n(t))}}}var Fi,Hh,ir,DE,ME,On,zh=T(()=>{"use strict";Fi=require("jsdom");ce();j();ye();Ee();Hh=require("linkedom"),ir=I("locate-step-action"),DE={opacity:1,clientRects:{}},ME=4e3;On=class extends ${execute(){return this.driver.getHTML(this.step)}static getUtils(e){return Object.assign(jE(e),{useLocatedElement:!0})}static getFrameIdByTestimFrameId(...e){throw ir.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(...e){throw ir.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(...e){throw ir.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(...e){throw ir.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(...e){throw ir.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(...e){throw ir.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Kh,Jh=T(()=>{"use strict";Kh=function(r,e,t,s,n,o,i,a){function c(b,x){if(!x)return{success:!1};elementScrollTo(x,b.x,b.y);let w=x.scrollLeft,v=x.scrollTop;return{success:Math.abs(v-b.y)<1&&Math.abs(w-b.x)<1,actualX:w,actualY:v}}function u(b,x,w,v,R,k,L){if(!w)return{x:v,y:R};let S=getLocatedElement(x);if(s&&!S)return{x:b.scrollWidth,y:b.scrollHeight};if(!S)throw new Error("could not find target element");let O=S.getBoundingClientRect(),A=0,D=0,B=Math.max(window.innerHeight-(O.height+10),0),V=Math.max(window.innerWidth-(O.width+10),0);return A=L?b.scrollTop+O.top-Math.min(R,B):b.scrollTop,D=k?b.scrollLeft+O.left-Math.min(v,V):b.scrollLeft,{x:Math.round(D),y:Math.round(A)}}let d=!r;if(r=d?document.scrollingElement||document.documentElement:getLocatedElement(r),!r)throw new Error("could not find target to scroll on");let p={top:r.scrollTop,left:r.scrollLeft},m=u(r,e,t,n,o,i,a),h=c(m,r);d&&!document.scrollingElement&&!h.success&&p.top===r.scrollTop&&p.left===r.scrollLeft&&(r=document.body,m=u(r,e,t,n,o,i,a),h=c(m,r));let f=h.actualX,g=h.actualY,y=getLocatedElement(e);if(t&&s&&!y)return{success:!1,expectedPosition:m};if(t){if(!y)throw new Error("could not find target to scroll to");let b=y.getBoundingClientRect();f=b.left,g=b.top}return{success:h.success,actualX:f,actualY:g}}});var Ui,Xh=T(()=>{"use strict";Jh();ce();Ui=class extends ${getFailureString(e,t,s,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${s}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${s}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,s){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(d,p,m){d.scrollTo(p,m)}:function(d,p,m){d.scrollTop=m,d.scrollLeft=p},u=`
|
|
371
|
+
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Li=new _u});var Ps,Lu=T(()=>{"use strict";Pu();Ee();Ps=class{constructor(e,t){this.driver=e,this._abortedSteps=[],this.cookieUtils=t||new Rs(this.driver)}get sessionPlayerInit(){return re()}getTimeStamp(){return Date.now()}getTestimId(e){if(!e)return;let{locatorBuilderUtils:t}=this.sessionPlayerInit,s=t.TESTIM_ID_FIELD_NAME;return t.isEmptyResult(e)?t.EMPTY_RESULT_ID:e.getAttribute(s)}resetAbort(){this._abortedSteps=[]}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}restoreNativeAlerts(){}executeOverloadNativeAlertsInFrame(){}getClickOffset(e,t){let{utils:s}=this.sessionPlayerInit;return e&&s.isWithinBounds(0,t.width,e.x)&&s.isWithinBounds(0,t.height,e.y)?{xOffset:e.x,yOffset:e.y}:{xOffset:t.width/2,yOffset:t.height/2}}executeInAut(e,t){return this.driver.executeJS(t).then(s=>s.value)}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t,s){return this.driver.markDynamicParent(e,t,s)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e,t){return this.cookieUtils.set(e)}getNextDynamicParent(e,t){let s=`return ${this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t)}`;return this.driver.executeJS(s).then(n=>n.value)}}});function Ug(r){class e{constructor(s,n){this.frameManager=s,this.locateElementPlayer=n,this._cache={}}cacheResults(s,n){this._cache[s]=n}getResultsFromCache(s){return this._cache[s]}cacheFrameLocateResults(s){if(s!=null&&s.seleniumFrameElement&&s.frameLocateResultUrl){let n=Fg(s.seleniumFrameElement);n&&this.cacheResults(n,s.frameLocateResultUrl)}}async foundFrameCallback(s,n,o){let{frameOffset:i,locatedElement:a}=s,{locatorBuilderUtils:c}=re();if(c.isEmptyResult(a)){let m="got empty result in frame result, not rejected from locate element player";throw AE.error(m),new Error(m)}let u=await r.switchToLocatedFrame(a),d=Fg(u.value),p=this.getResultsFromCache(d);return{frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:u.value,frameLocateResultUrl:p}}locate(s,n,o,i,a,c){let u=new this.locateElementPlayer(i);return s.targetId=`frameLocator_${n}`,u.locate(s,o,s.targetId).then(d=>(d.isVisible=!0,u.handleLocateResult(d,c,s).catch(()=>{throw new Error}))).then(d=>{let{locatedElement:p}=i.data[s.targetId];return r.getElementLocationWithPadding(p).then(m=>{let g=m.value||{top:0,left:0};return d.frameOffset={top:o.frameOffset.top+g.top,left:o.frameOffset.left+g.left},d})}).then(d=>(u.addFrameDataToContext&&u.addFrameDataToContext(d.targetId,d.locateResult),this.foundFrameCallback(d,a,s.testimFrameId))).then(d=>(this.currentFrameHandler=d,d))}async findFrame(s,n,o,i){let a=M.flags.enableFrameSwitchOptimization.isEnabled(),u=o.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,p=Boolean(u)&&u.stepId===s.id&&u.results.length>d;if(a&&!p&&this.currentFrameHandler){let y=n.findIndex(b=>b.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let b=n.slice(y+1),I=0;for(let w of b)I++,this.currentFrameHandler=await this.locate(w,I,this.currentFrameHandler,o,i,s);return this.currentFrameHandler}}let m=await i.getTopFrameHandler();m.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===m?this.currentFrameHandler:r.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=m;let f=0,h=m;for(let y of n)f++,h=await this.locate(y,f,h,o,i,s);return h}}return e}var AE,CE,kE,Fg,jg=T(()=>{"use strict";j();ye();Ee();AE=x("frame-locator"),CE="ELEMENT",kE="element-6066-11e4-a52e-4f735466cecf",Fg=r=>r?r[CE]||r[kE]:null});var Di,Du=T(()=>{"use strict";le();Di=()=>{try{if(Wd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var Nu,Bg,Ur,_E,Mu,We,_n=T(()=>{"use strict";U();It();Nu=E(require("ws")),Bg=require("events");j();le();Ur=x("socket-ng-service"),_E=5e3,Mu=class extends Bg.EventEmitter{constructor(){super(...arguments);this.clientId=z();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Ur.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),_E)}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(s){Ur.error("failed to parse or trigger event",{err:s})}}connect(t){let s=this.formatUrl(Gd);return Kt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Nu.default(`${s}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Ur.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Ur.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Nu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Ur.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){Ur.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(s){Ur.error("failed to stringify message for sending",{err:s})}}listenOnce(t,s,n){let o=i=>{s(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,s,n,o){function i(c){n(c)&&o(c)}(Array.isArray(s)?s:[s]).forEach(c=>{var d,p;(d=this.listeners)[p=`${t}:${c}`]||(d[p]=[]);let u=i.bind(this);this.listeners[`${t}:${c}`].push(u),this.on(c,u)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let s=this.filterMap[t];this.sendMessage({type:"add-filter",filter:s})})}addFilter(t,s,n,o=!1){return new Promise(i=>{let a=z(),c={query:s,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",u=>u.id===a,i),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,s){Object.keys(this.listeners).length!==0&&s.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,s){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(s)?s:[s];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},We=new Mu});var Wg,Fu,OE,LE,DE,$g,Ni,or,Mi=T(()=>{"use strict";Wg=E(require("p-retry")),Fu=E(require("socket.io-client"));le();U();j();OE=50,LE=10,DE=5e3,$g=10*1e3,Ni=x("base socket service"),or=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Ni.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let s=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,s)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,s)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Ni.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${s==null?void 0:s.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===LE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=OE)throw new Error(`Can't connect to Testim Servers.
|
|
372
|
+
Action required: Please allow opening a websockets connection to ${he} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Ni.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let s={query:{projectId:e},requestTimeout:$g,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${he}/${t}`,this._socket=Fu.connect(this.url,s),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let s={query:{projectId:e},requestTimeout:$g,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${he}/${t}`,this._socket=Fu.connect(this.url,s),this.addSocketHandlers()}emitPromise(e,t){let s={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(s[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Wg.default)(()=>te(n(),DE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(s).length>0&&Ni.error("Bad acknowledge from socket emit",{errorneousEvents:s})}),this.emitPromiseQueue}}});var Uu,jr,Gg=T(()=>{"use strict";Mi();Uu=class extends or{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,s,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===s&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,s){return this.emitPromise("testResult:join",{resultId:t,testId:s})}async joinToTestResult(t,s){this.rooms[t]||(this.joinRoom(t,s),await this.emitJoinRoom(t,s))}emitLeaveRoom(t,s){return this.emitPromise("testResult:leave",{resultId:t,testId:s})}leaveTestResult(t,s){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,s)):Promise.resolve()}getSocket(){return this._socket}},jr=new Uu});var qg={};W(qg,{testResultService:()=>Qe});var Vg,ju,Qe,As=T(()=>{"use strict";Vg=require("events");_n();ae();ye();Gg();ju=class extends Vg.EventEmitter{init(e){if(M.flags.useNewWSCLI.isEnabled()){We.onConnect=()=>this.emit("socket-connected");return}jr.init(e),jr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return M.flags.useNewWSCLI.isEnabled()?We.addFilter(`${e}:testResult`,{resultId:e,testId:t},[rt.TEST_RESULT_UPDATED,rt.TEST_RESULT_CREATED]):jr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(M.flags.useNewWSCLI.isEnabled()){We.removeFilter(`${e}:testResult`,[rt.TEST_RESULT_UPDATED,rt.TEST_RESULT_CREATED]);return}await jr.leaveTestResult(e,t)}listenToTestResult(e,t,s){if(M.flags.useNewWSCLI.isEnabled()){We.listenTo(`${e}:testResult`,[rt.TEST_RESULT_UPDATED,rt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>s(n));return}jr.listenToTestResult(e,t,s)}getSocket(){if(!M.flags.useNewWSCLI.isEnabled())return jr.getSocket()}},Qe=new ju});var $,ce=T(()=>{"use strict";Ee();$=class{constructor(e,t,s,n={},o=void 0,i=void 0,a={}){this.step=e,this.context=t,this.frameHandler=s,this.frameId=0,this.stepActionUtils=o,this.locateElementPlayer=i,this.exportsGlobal=n,this.exportsTest=a}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return re()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(e,t){var s;try{return{success:!0,...await this.performAction(e,t)}}catch(n){let o=(n==null?void 0:n.message)||((s=n==null?void 0:n.seleniumStack)==null?void 0:s.message),i=n==null?void 0:n.displayMessage;return{success:!1,reason:o,exception:n,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${o}`,error:i||o}}}}}});function FE(){let r=t=>Math.round(t/1024/1024*100)/100,e=process.memoryUsage();return{isOverThreshold:r(e.rss)>ME,rss:`${r(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${r(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${r(e.heapUsed)} MB -> actual memory used during the execution`,external:`${r(e.external)} MB -> V8 external memory`}}function UE(r,e,t){let s=FE();s.isOverThreshold&&ir.info(`using ${r} to parse html`,{memoryUsage:s,testName:e,testResultId:t})}function jE(r){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await r.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return r.getElementRect(e)},getOffsets(e){return Promise.resolve([e.frameOffset||{}])},getOptimizedDom(e){let s=new Hg.DOMParser().parseFromString("<html><body></body></html>","text/html");return s.body.outerHTML=e,Object.assign(s,{parsedUsingLinkedom:!0})},htmlStringToDom(e,t,s,n,o=!1){UE(o?"linkedom":"jsdom",r.testName,r.testResultId);let i;if(o)i=this.getOptimizedDom(e);else{let a=new Fi.VirtualConsole;i=new Fi.JSDOM(e,{virtualConsole:a}).window.document}return Object.assign(i,{TESTIM_URL:t})},shouldUseNativeVisibilityCheck(e,t,s,n){return e.opacity===0||e.isShadowed?!1:s===void 0||n===void 0?!0:M.flags.useClickimVisibilityChecks.isEnabled()?!1:t.isSafari()?M.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0},async isVisible(e,t,s,n,o,i,a){let{locatorBuilderUtils:c,codeSnippets:u,visibilityUtils:d,positionUtils:p}=re();if(this.shouldUseNativeVisibilityCheck(n,r,d,p))return r.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await r.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let f=[p.calculateElementMiddlePoint(s),p.calculateClickPoint(n.clickOffset,s)].filter(Boolean),h=u.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,f,!1,n),y;try{y=await r.execute(`return ${h}`)}catch(R){throw ir.error("failed to execute getVisibilityCode",{err:R}),R}let{value:b}=y||{},I=b.elementVisibilityInfo||NE,[w,v]=b.elementsFromPointResults||[null,null];return d.checkElementVisibility(I,n,v,w,a,t)},scrollToElement(e,t){let{codeSnippets:s}=re(),n=s.scrollToElement;return r.execute(n(t))}}}var Fi,Hg,ir,NE,ME,On,zg=T(()=>{"use strict";Fi=require("jsdom");ce();j();ye();Ee();Hg=require("linkedom"),ir=x("locate-step-action"),NE={opacity:1,clientRects:{}},ME=4e3;On=class extends ${execute(){return this.driver.getHTML(this.step)}static getUtils(e){return Object.assign(jE(e),{useLocatedElement:!0})}static getFrameIdByTestimFrameId(...e){throw ir.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(...e){throw ir.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(...e){throw ir.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(...e){throw ir.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(...e){throw ir.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(...e){throw ir.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var Kg,Jg=T(()=>{"use strict";Kg=function(r,e,t,s,n,o,i,a){function c(b,I){if(!I)return{success:!1};elementScrollTo(I,b.x,b.y);let w=I.scrollLeft,v=I.scrollTop;return{success:Math.abs(v-b.y)<1&&Math.abs(w-b.x)<1,actualX:w,actualY:v}}function u(b,I,w,v,R,k,L){if(!w)return{x:v,y:R};let S=getLocatedElement(I);if(s&&!S)return{x:b.scrollWidth,y:b.scrollHeight};if(!S)throw new Error("could not find target element");let O=S.getBoundingClientRect(),A=0,N=0,B=Math.max(window.innerHeight-(O.height+10),0),V=Math.max(window.innerWidth-(O.width+10),0);return A=L?b.scrollTop+O.top-Math.min(R,B):b.scrollTop,N=k?b.scrollLeft+O.left-Math.min(v,V):b.scrollLeft,{x:Math.round(N),y:Math.round(A)}}let d=!r;if(r=d?document.scrollingElement||document.documentElement:getLocatedElement(r),!r)throw new Error("could not find target to scroll on");let p={top:r.scrollTop,left:r.scrollLeft},m=u(r,e,t,n,o,i,a),g=c(m,r);d&&!document.scrollingElement&&!g.success&&p.top===r.scrollTop&&p.left===r.scrollLeft&&(r=document.body,m=u(r,e,t,n,o,i,a),g=c(m,r));let f=g.actualX,h=g.actualY,y=getLocatedElement(e);if(t&&s&&!y)return{success:!1,expectedPosition:m};if(t){if(!y)throw new Error("could not find target to scroll to");let b=y.getBoundingClientRect();f=b.left,h=b.top}return{success:g.success,actualX:f,actualY:h}}});var Ui,Yg=T(()=>{"use strict";Jg();ce();Ui=class extends ${getFailureString(e,t,s,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${s}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${s}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,s){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(d,p,m){d.scrollTo(p,m)}:function(d,p,m){d.scrollTop=m,d.scrollLeft=p},u=`
|
|
373
373
|
var getLocatedElement = ${n.getLocatedElementCode};
|
|
374
374
|
var elementScrollTo = ${c.toString()};
|
|
375
|
-
var scroll = ${
|
|
375
|
+
var scroll = ${Kg.toString()};
|
|
376
376
|
return scroll.apply(null, arguments)
|
|
377
|
-
`;try{let d=await this.driver.executeJSWithArray(u,[s,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop]);if(!(d!=null&&d.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:m,actualY:h}=d.value;return p?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,m,h)}}}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 e=this.context,t=this.step,s=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,s):this.scrollOnElement(t,s)}}});var Yh,Qh=T(()=>{"use strict";Yh=function(r){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let s={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(r.fromLocatedElement),o=getLocatedElement(r.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let u=document.createEvent("CustomEvent");u.initCustomEvent(c,!0,!0,null),u.dataTransfer=s,a.dispatchEvent?a.dispatchEvent(u):a.fireEvent&&a.fireEvent(`on${c}`,u)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var Zh,eg=T(()=>{"use strict";Zh=(r,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function s(w,v){var L;function R(S){function O(B){return o(B).find(V=>Array.apply(null,V.classList||[]).includes("Select-control"))}function A(B){let V=O(B);return V?V.querySelector("INPUT"):null}let D=A(S);D&&D.focus()}let k=(L=w.quirks)==null?void 0:L.isReactSelect;v.type==="mousedown"&&k&&R(w.element)}function n(w,v){var k;let R=(k=w.quirks)==null?void 0:k.isCKEditorFrame;v.type==="click"&&R&&document.body.focus()}function o(w){return w?[w].concat(o(w.parentNode)):[]}function i(w){let v={status:"done",result:w,success:!0};x.isNonTextableElemnet&&(v.reason="Set text on non input element"),e(v)}function a(w){w=w||{},e({status:"failed",result:w,success:!1})}function c(w){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),w.dispatchEvent(v)}function u(w){let v={},R=w.getBoundingClientRect(),k=R.left+R.width/2,L=R.top+R.height/2,A=h("mousemove",v,k,L,0);w.dispatchEvent(A)}function d(w,v){function R(A,D,B){return B>A&&B<D}let k=w.pointerPosition||{},L=v.getBoundingClientRect(),S=k.originX&&R(L.left,L.left+L.width,k.originX)?k.originX:L.left+L.width/2,O=k.originY&&R(L.top,L.top+L.height,k.originY)?k.originY:L.top+L.height/2;return{x:S,y:O}}function p(w,v,R){return{screenX:0,screenY:0,clientX:v,clientY:R,ctrlKey:Boolean(w.ctrl),altKey:Boolean(w.alt),shiftKey:Boolean(w.shift),metaKey:Boolean(w.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(w,v,R,k){if(!window.PointerEvent)return;let L=p(v,R,k);return L.pointerType="mouse",L.isPrimary=!0,new window.PointerEvent(w,L)}function h(w,v,R,k,L){let S=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return S.initMouseEvent(w,!0,!0,document.defaultView,1,0,0,R,k,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),S}function f(w,v){let R=["pointerup","pointerdown","pointermove"],k=v.modifiers||{},L=d(w,v.element),S=v.button||0,O=w.event;return R.includes(O)?m(O,k,L.x,L.y):h(O,k,L.x,L.y,S)}function g(){var v;let w=document.activeElement;for(;(v=w.shadowRoot)!=null&&v.activeElement;)w=w.shadowRoot.activeElement;return w}function y(w){w.events.map(v=>{try{return f(v,w)}catch{return}}).filter(Boolean).forEach(v=>{w.element.dispatchEvent(v),s(w,v),n(w,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}var x={element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,quirks:r.quirks,modifiers:r.modifiers,button:r.button};if(!x.element){a("element not found");return}c(x.element),u(x.element);try{y(x);let w=g(),v=x.quirks,R=v==null?void 0:v.isReactSelect,k=v==null?void 0:v.isCKEditorFrame;!R&&!k&&dispatchFocus(r.elementToFocusLocatedElement,w),i()}catch(w){a(w.toString())}}});var tg,rg=T(()=>{"use strict";tg=function(r,e){let t=typeof Event=="function",s=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(w){e({status:"done",result:w,success:!0})}function i(w){w=w||{},e({status:"failed",result:w,success:!1})}function a(w){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),w.dispatchEvent(v)}function c(w){let v={},R=w.getBoundingClientRect(),k=R.left+R.width/2,L=R.top+R.height/2,A=m("mousemove",v,k,L,0);w.dispatchEvent(A)}function u(w,v){function R(A,D,B){return B>A&&B<D}let k=w.pointerPosition||{};if(x.isDrag)return{x:k.originX||0,y:k.originY||0};let L=v.getBoundingClientRect(),S=k.originX&&R(L.left,L.left+L.width,k.originX)?k.originX:L.left+L.width/2,O=k.originY&&R(L.top,L.top+L.height,k.originY)?k.originY:L.top+L.height/2;return{x:S,y:O}}function d(w,v,R){return{screenX:0,screenY:0,clientX:v,clientY:R,ctrlKey:Boolean(w.ctrl),altKey:Boolean(w.alt),shiftKey:Boolean(w.shift),metaKey:Boolean(w.meta),bubbles:!0,cancelable:!0,composed:!0}}function p(w,v,R,k,L){if(s){let O=d(v,R,k);return O.pointerType="mouse",O.isPrimary=!0,new window.PointerEvent(w,O)}let S=document.createEvent("PointerEvent");return S.initPointerEvent(w,!0,!0,document.defaultView,1,0,0,R,k,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),S}function m(w,v,R,k,L){let S=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return S.initMouseEvent(w,!0,!0,document.defaultView,1,0,0,R,k,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),S}function h(w,v){let R=["pointerup","pointerdown","pointermove"],k=v.modifiers||{},L=u(w,v.element),S=v.button||0,O=w.event;return R.includes(O)?p(O,k,L.x,L.y,S):m(O,k,L.x,L.y,S)}function f(w,v){function R(){return w.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return R()}function g(w,v,R){try{let k=h(v.events[w],v);f(k,v)||v.element.dispatchEvent(k)}catch{}if(w+1===v.events.length)R();else{let k=Math.min(v.events[w+1].timeStamp-v.events[w].timeStamp,n);setTimeout(()=>{g(w+1,v,R)},k)}}function y(w,v){g(0,w,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let x={eventIndex:0,element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,quirks:r.quirks,isDoubleClick:r.isDoubleClick,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement,allEventsOnSameElement:r.allEventsOnSameElement};if(!x.element){i("element not found");return}a(x.element),c(x.element),y(x,()=>{o()})}});var sg,ng=T(()=>{"use strict";sg=function(r,e){let t=typeof MouseEvent=="function",s=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(A){e({status:"done",result:A,success:!0})}function a(A){A=A||{},e({status:"failed",result:A,success:!1,keep:!0})}function c(A){return A!=null&&A.toLowerCase?(A=A.toLowerCase(),A==="text"?"text/plain":A==="url"?"text/uri-list":A):A}function u(){try{return new DataTransfer}catch{return{data:{},setData(D,B){o[c(D)]=B},getData(D){return o[c(D)]}}}}let d=["drag","dragstart","dragend"],p=["pointerup","pointerdown","pointermove"],m=d.concat(["drop","dragenter","dragover"]);function h(A){let D=A;for(;D&&D!==document.documentElement;){if(D.draggable)return D;D=D.parentElement}return null}function f(A,D,B){let V=D.element,Y=B.dispatchDragEventsOnClosestDraggable;if(d.includes(A.type)&&Y){if(!V&&D.lastDraggedElement)return D.lastDraggedElement;let Z=h(V);if(Z)return D.lastDraggedElement=Z,Z}return V}function g(A,D,B){function V(qr,C,N){return N>qr&&N<C}let Y=A.pointerPosition||{};if(D)return{x:Y.originX||0,y:Y.originY||0};let Z=B.getBoundingClientRect(),fe=Y.originX&&V(Z.left,Z.left+Z.width,Y.originX)?Y.originX:Z.left+Z.width/2,kt=Y.originY&&V(Z.top,Z.top+Z.height,Y.originY)?Y.originY:Z.top+Z.height/2;return{x:fe,y:kt}}function y(A,D,B){let V=(D==null?void 0:D.modifiers)||{},Y=g(A,B.isDrag,B.element),Z=(D==null?void 0:D.button)||0,fe=A.event;return p.includes(fe)?x(fe,V,Y.x,Y.y,Z):m.includes(fe)?v(fe,V,Y.x,Y.y,Z):w(fe,V,Y.x,Y.y,Z)}function b(A,D,B){return{screenX:0,screenY:0,clientX:D,clientY:B,ctrlKey:Boolean(A.ctrl),altKey:Boolean(A.alt),shiftKey:Boolean(A.shift),metaKey:Boolean(A.meta),bubbles:!0,cancelable:!0,composed:!0}}function x(A,D,B,V,Y){if(n){let fe=b(D,B,V);return fe.pointerType="mouse",fe.isPrimary=!0,new window.PointerEvent(A,fe)}let Z=document.createEvent("PointerEvent");return Z.initPointerEvent(A,!0,!0,document.defaultView,1,0,0,B,V,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),Y,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),Z}function w(A,D,B,V,Y){let Z=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return Z.initMouseEvent(A,!0,!0,document.defaultView,1,0,0,B,V,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),Y,document.body?document.body.parentNode:document.documentElement),Z}function v(A,D,B,V){if(A==="dragstart"&&(window.TSTA||(window.TSTA={}),window.TSTA.dataTransfer=u()),!s){let fe=document.createEvent("CustomEvent");return fe.initCustomEvent(A,!0,!0,null),fe.dataTransfer=window.TSTA.dataTransfer,fe}let Y=b(D,B,V),Z=new window.DragEvent(A,Y);return Object.defineProperties(Z,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),Z}function R(A,D,B){let V=f(A,D,B);V&&V.dispatchEvent(A)}function k(A,D){function B(){return A.event==="click"&&D.isDrag&&!D.allEventsOnSameElement}return B()}function L(A,D,B){if(B){let V=Math.min(B.timeStamp-D.timeStamp,40);setTimeout(()=>{S(A)},V)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function S(A){let D,B=A.events[A.eventIndex],V=A.events[++A.eventIndex];try{A.element=getLocatedElement(B.locatedElement),D=y(B,r,A)}catch(Y){return a(`exception in get event in drag step:${Y.message}`)}if(k(B,A))return L(A,B,V);if(D)try{R(D,A,B)}catch(Y){return a(`exception in executeEvent in drag step:${Y.message}`)}else return a(`cannot execute event ${B.event}`);L(A,B,V)}let O={eventIndex:0,allEventsOnSameElement:r.allEventsOnSameElement,events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement};setTimeout(()=>{try{S(O)}catch(A){a(A)}},0)}});var Ln,ji,og=T(()=>{"use strict";Ln=E(require("lodash"));ce();xi();Qh();eg();rg();ye();ng();ji=class extends ${getDnDRectsAndOffsets(e,t,s,n){let o=this.stepActionUtils.getClickOffset(s,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.xOffset,fromY:o.yOffset,toRect:t.rectWithoutFrameOffset,toX:i.xOffset,toY:i.yOffset}}async clickJs(){var c;let e=this.step,t=this.context,s=t.data[e.targetId||"targetId"],n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return;let i={isRoot:s.isRoot,locatedElement:s.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},a=`
|
|
377
|
+
`;try{let d=await this.driver.executeJSWithArray(u,[s,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop]);if(!(d!=null&&d.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:m,actualY:g}=d.value;return p?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,m,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 e=this.context,t=this.step,s=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,s):this.scrollOnElement(t,s)}}});var Xg,Qg=T(()=>{"use strict";Xg=function(r){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let s={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(r.fromLocatedElement),o=getLocatedElement(r.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let u=document.createEvent("CustomEvent");u.initCustomEvent(c,!0,!0,null),u.dataTransfer=s,a.dispatchEvent?a.dispatchEvent(u):a.fireEvent&&a.fireEvent(`on${c}`,u)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var Zg,eh=T(()=>{"use strict";Zg=(r,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function s(w,v){var L;function R(S){function O(B){return o(B).find(V=>Array.apply(null,V.classList||[]).includes("Select-control"))}function A(B){let V=O(B);return V?V.querySelector("INPUT"):null}let N=A(S);N&&N.focus()}let k=(L=w.quirks)==null?void 0:L.isReactSelect;v.type==="mousedown"&&k&&R(w.element)}function n(w,v){var k;let R=(k=w.quirks)==null?void 0:k.isCKEditorFrame;v.type==="click"&&R&&document.body.focus()}function o(w){return w?[w].concat(o(w.parentNode)):[]}function i(w){let v={status:"done",result:w,success:!0};I.isNonTextableElemnet&&(v.reason="Set text on non input element"),e(v)}function a(w){w=w||{},e({status:"failed",result:w,success:!1})}function c(w){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),w.dispatchEvent(v)}function u(w){let v={},R=w.getBoundingClientRect(),k=R.left+R.width/2,L=R.top+R.height/2,A=g("mousemove",v,k,L,0);w.dispatchEvent(A)}function d(w,v){function R(A,N,B){return B>A&&B<N}let k=w.pointerPosition||{},L=v.getBoundingClientRect(),S=k.originX&&R(L.left,L.left+L.width,k.originX)?k.originX:L.left+L.width/2,O=k.originY&&R(L.top,L.top+L.height,k.originY)?k.originY:L.top+L.height/2;return{x:S,y:O}}function p(w,v,R){return{screenX:0,screenY:0,clientX:v,clientY:R,ctrlKey:Boolean(w.ctrl),altKey:Boolean(w.alt),shiftKey:Boolean(w.shift),metaKey:Boolean(w.meta),bubbles:!0,cancelable:!0,composed:!0}}function m(w,v,R,k){if(!window.PointerEvent)return;let L=p(v,R,k);return L.pointerType="mouse",L.isPrimary=!0,new window.PointerEvent(w,L)}function g(w,v,R,k,L){let S=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return S.initMouseEvent(w,!0,!0,document.defaultView,1,0,0,R,k,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),S}function f(w,v){let R=["pointerup","pointerdown","pointermove"],k=v.modifiers||{},L=d(w,v.element),S=v.button||0,O=w.event;return R.includes(O)?m(O,k,L.x,L.y):g(O,k,L.x,L.y,S)}function h(){var v;let w=document.activeElement;for(;(v=w.shadowRoot)!=null&&v.activeElement;)w=w.shadowRoot.activeElement;return w}function y(w){w.events.map(v=>{try{return f(v,w)}catch{return}}).filter(Boolean).forEach(v=>{w.element.dispatchEvent(v),s(w,v),n(w,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}var I={element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,quirks:r.quirks,modifiers:r.modifiers,button:r.button};if(!I.element){a("element not found");return}c(I.element),u(I.element);try{y(I);let w=h(),v=I.quirks,R=v==null?void 0:v.isReactSelect,k=v==null?void 0:v.isCKEditorFrame;!R&&!k&&dispatchFocus(r.elementToFocusLocatedElement,w),i()}catch(w){a(w.toString())}}});var th,rh=T(()=>{"use strict";th=function(r,e){let t=typeof Event=="function",s=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(w){e({status:"done",result:w,success:!0})}function i(w){w=w||{},e({status:"failed",result:w,success:!1})}function a(w){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),w.dispatchEvent(v)}function c(w){let v={},R=w.getBoundingClientRect(),k=R.left+R.width/2,L=R.top+R.height/2,A=m("mousemove",v,k,L,0);w.dispatchEvent(A)}function u(w,v){function R(A,N,B){return B>A&&B<N}let k=w.pointerPosition||{};if(I.isDrag)return{x:k.originX||0,y:k.originY||0};let L=v.getBoundingClientRect(),S=k.originX&&R(L.left,L.left+L.width,k.originX)?k.originX:L.left+L.width/2,O=k.originY&&R(L.top,L.top+L.height,k.originY)?k.originY:L.top+L.height/2;return{x:S,y:O}}function d(w,v,R){return{screenX:0,screenY:0,clientX:v,clientY:R,ctrlKey:Boolean(w.ctrl),altKey:Boolean(w.alt),shiftKey:Boolean(w.shift),metaKey:Boolean(w.meta),bubbles:!0,cancelable:!0,composed:!0}}function p(w,v,R,k,L){if(s){let O=d(v,R,k);return O.pointerType="mouse",O.isPrimary=!0,new window.PointerEvent(w,O)}let S=document.createEvent("PointerEvent");return S.initPointerEvent(w,!0,!0,document.defaultView,1,0,0,R,k,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),S}function m(w,v,R,k,L){let S=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return S.initMouseEvent(w,!0,!0,document.defaultView,1,0,0,R,k,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),S}function g(w,v){let R=["pointerup","pointerdown","pointermove"],k=v.modifiers||{},L=u(w,v.element),S=v.button||0,O=w.event;return R.includes(O)?p(O,k,L.x,L.y,S):m(O,k,L.x,L.y,S)}function f(w,v){function R(){return w.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return R()}function h(w,v,R){try{let k=g(v.events[w],v);f(k,v)||v.element.dispatchEvent(k)}catch{}if(w+1===v.events.length)R();else{let k=Math.min(v.events[w+1].timeStamp-v.events[w].timeStamp,n);setTimeout(()=>{h(w+1,v,R)},k)}}function y(w,v){h(0,w,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let I={eventIndex:0,element:r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,quirks:r.quirks,isDoubleClick:r.isDoubleClick,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement,allEventsOnSameElement:r.allEventsOnSameElement};if(!I.element){i("element not found");return}a(I.element),c(I.element),y(I,()=>{o()})}});var sh,nh=T(()=>{"use strict";sh=function(r,e){let t=typeof MouseEvent=="function",s=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(A){e({status:"done",result:A,success:!0})}function a(A){A=A||{},e({status:"failed",result:A,success:!1,keep:!0})}function c(A){return A!=null&&A.toLowerCase?(A=A.toLowerCase(),A==="text"?"text/plain":A==="url"?"text/uri-list":A):A}function u(){try{return new DataTransfer}catch{return{data:{},setData(N,B){o[c(N)]=B},getData(N){return o[c(N)]}}}}let d=["drag","dragstart","dragend"],p=["pointerup","pointerdown","pointermove"],m=d.concat(["drop","dragenter","dragover"]);function g(A){let N=A;for(;N&&N!==document.documentElement;){if(N.draggable)return N;N=N.parentElement}return null}function f(A,N,B){let V=N.element,X=B.dispatchDragEventsOnClosestDraggable;if(d.includes(A.type)&&X){if(!V&&N.lastDraggedElement)return N.lastDraggedElement;let Z=g(V);if(Z)return N.lastDraggedElement=Z,Z}return V}function h(A,N,B){function V(qr,C,D){return D>qr&&D<C}let X=A.pointerPosition||{};if(N)return{x:X.originX||0,y:X.originY||0};let Z=B.getBoundingClientRect(),fe=X.originX&&V(Z.left,Z.left+Z.width,X.originX)?X.originX:Z.left+Z.width/2,kt=X.originY&&V(Z.top,Z.top+Z.height,X.originY)?X.originY:Z.top+Z.height/2;return{x:fe,y:kt}}function y(A,N,B){let V=(N==null?void 0:N.modifiers)||{},X=h(A,B.isDrag,B.element),Z=(N==null?void 0:N.button)||0,fe=A.event;return p.includes(fe)?I(fe,V,X.x,X.y,Z):m.includes(fe)?v(fe,V,X.x,X.y,Z):w(fe,V,X.x,X.y,Z)}function b(A,N,B){return{screenX:0,screenY:0,clientX:N,clientY:B,ctrlKey:Boolean(A.ctrl),altKey:Boolean(A.alt),shiftKey:Boolean(A.shift),metaKey:Boolean(A.meta),bubbles:!0,cancelable:!0,composed:!0}}function I(A,N,B,V,X){if(n){let fe=b(N,B,V);return fe.pointerType="mouse",fe.isPrimary=!0,new window.PointerEvent(A,fe)}let Z=document.createEvent("PointerEvent");return Z.initPointerEvent(A,!0,!0,document.defaultView,1,0,0,B,V,Boolean(N.ctrl),Boolean(N.alt),Boolean(N.shift),Boolean(N.meta),X,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),Z}function w(A,N,B,V,X){let Z=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return Z.initMouseEvent(A,!0,!0,document.defaultView,1,0,0,B,V,Boolean(N.ctrl),Boolean(N.alt),Boolean(N.shift),Boolean(N.meta),X,document.body?document.body.parentNode:document.documentElement),Z}function v(A,N,B,V){if(A==="dragstart"&&(window.TSTA||(window.TSTA={}),window.TSTA.dataTransfer=u()),!s){let fe=document.createEvent("CustomEvent");return fe.initCustomEvent(A,!0,!0,null),fe.dataTransfer=window.TSTA.dataTransfer,fe}let X=b(N,B,V),Z=new window.DragEvent(A,X);return Object.defineProperties(Z,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),Z}function R(A,N,B){let V=f(A,N,B);V&&V.dispatchEvent(A)}function k(A,N){function B(){return A.event==="click"&&N.isDrag&&!N.allEventsOnSameElement}return B()}function L(A,N,B){if(B){let V=Math.min(B.timeStamp-N.timeStamp,40);setTimeout(()=>{S(A)},V)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function S(A){let N,B=A.events[A.eventIndex],V=A.events[++A.eventIndex];try{A.element=getLocatedElement(B.locatedElement),N=y(B,r,A)}catch(X){return a(`exception in get event in drag step:${X.message}`)}if(k(B,A))return L(A,B,V);if(N)try{R(N,A,B)}catch(X){return a(`exception in executeEvent in drag step:${X.message}`)}else return a(`cannot execute event ${B.event}`);L(A,B,V)}let O={eventIndex:0,allEventsOnSameElement:r.allEventsOnSameElement,events:r.events,eventType:r.eventType,eventData:r.eventData,stepId:r.id,testResultId:r.testResultId,isDrag:r.isDrag,useRecordedMousedown:r.useRecordedMousedown,trackActiveElement:r.trackActiveElement};setTimeout(()=>{try{S(O)}catch(A){a(A)}},0)}});var Ln,ji,oh=T(()=>{"use strict";Ln=E(require("lodash"));ce();xi();Qg();eh();rh();ye();nh();ji=class extends ${getDnDRectsAndOffsets(e,t,s,n){let o=this.stepActionUtils.getClickOffset(s,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.xOffset,fromY:o.yOffset,toRect:t.rectWithoutFrameOffset,toX:i.xOffset,toY:i.yOffset}}async clickJs(){var c;let e=this.step,t=this.context,s=t.data[e.targetId||"targetId"],n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return;let i={isRoot:s.isRoot,locatedElement:s.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},a=`
|
|
378
378
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
379
|
-
var dispatchFocus = ${
|
|
380
|
-
var doClick = ${
|
|
379
|
+
var dispatchFocus = ${Dr.toString()};
|
|
380
|
+
var doClick = ${Zg.toString()};
|
|
381
381
|
var eventData = arguments[0];
|
|
382
382
|
var done = arguments[1];
|
|
383
383
|
return doClick.call(null, eventData, done);
|
|
384
384
|
`;try{return(c=(await this.driver.executeCodeAsync(a,n,i)).value)!=null&&c.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}isWithinBounds(e,t,s){return s>e&&s<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let s=this.context.data[this.step.targetId||"targetId"].rectWithoutFrameOffset,n=this.isWithinBounds(s.left,s.left+s.width,e.originX),o=this.isWithinBounds(s.top,s.top+s.height,e.originY),i=n?0:s.left+s.width/2-e.originX,a=o?0:s.top+s.height/2-e.originY;return{xOffset:i,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let s=Ln.cloneDeep(e);return s.event=t,s}fixAbsoluteDragEventSequence(){let e=this.step.events.find(o=>["mousedown","pointerdown"].includes(o.event));if(e){let o=this.step.events.indexOf(e);this.step.events.splice(o,0,this.generateEventOfType(e,"mouseover"))}let{recordPointerMoveEvents:t=!1}=this.context.project.defaults||{},s=this.step.events.find(o=>o.event==="mouseup")||t&&this.step.events.find(o=>o.event==="pointerup"),n=Ln.findLastIndex(this.step.events,o=>o.event==="mousemove")||t&&Ln.findLastIndex(this.step.events,o=>o.event==="pointermove");s&&n>0&&!this.step.allEventsOnSameElement&&this.step.events.splice(n+1,0,this.generateEventOfType(s,"mouseover")),this.step.isHTML5Drag&&!this.step.toElement&&(this.step.events=this.addDragendIfNeeded(this.step.events)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var c,u;let e=this.step,t=this.context,s=t.data[e.targetId||"targetId"],n=t.data.timeToPlayStep+3e3;if(!((c=this.step.events)!=null&&c.length))return;this.fixAbsoluteDragEventSequence();let o=e.events,i={isRoot:s.isRoot,locatedElement:s.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},a=`
|
|
385
385
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
386
|
-
var dispatchFocus = ${
|
|
387
|
-
var doDragPath = ${
|
|
386
|
+
var dispatchFocus = ${Dr.toString()};
|
|
387
|
+
var doDragPath = ${th.toString()};
|
|
388
388
|
return doDragPath.apply(null, arguments);
|
|
389
|
-
`;try{return(u=(await this.driver.executeCodeAsync(a,n,i)).value)!=null&&u.success?{success:!0}:{success:!1}}catch(d){return{success:!1,reason:d.message,exception:d}}}chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:s,rectWithoutFrameOffset:n,rect:o}=e,{xOffset:i,yOffset:a}=this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n),c={frameOffset:{x:o.left-n.left,y:o.top-n.top},rect:n,clickOffset:{x:i,y:a}};if(M.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return Promise.resolve({keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"});if(this.step.isDoubleClick){let m={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(s,m,c)}if(this.step.isDrag){if(this.step.toElement){let m=this.context.data.toElement;if(this.step.isHTML5Drag){if(M.flags.usePortedHtml5DragDrop.isEnabled()){let y=this.generateHTML5DragEventSequence(),b=this.context.data.timeToPlayStep+3e3,
|
|
389
|
+
`;try{return(u=(await this.driver.executeCodeAsync(a,n,i)).value)!=null&&u.success?{success:!0}:{success:!1}}catch(d){return{success:!1,reason:d.message,exception:d}}}chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:s,rectWithoutFrameOffset:n,rect:o}=e,{xOffset:i,yOffset:a}=this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n),c={frameOffset:{x:o.left-n.left,y:o.top-n.top},rect:n,clickOffset:{x:i,y:a}};if(M.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return Promise.resolve({keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"});if(this.step.isDoubleClick){let m={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(s,m,c)}if(this.step.isDrag){if(this.step.toElement){let m=this.context.data.toElement;if(this.step.isHTML5Drag){if(M.flags.usePortedHtml5DragDrop.isEnabled()){let y=this.generateHTML5DragEventSequence(),b=this.context.data.timeToPlayStep+3e3,I=this.context.data[this.step.targetId||"targetId"],w={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:y,eventData:{modifiers:this.step.modifiers,button:this.step.button},quirks:this.step.quirks,isDrag:this.step.isDrag,useRecordedMousedown:this.step.useRecordedMousedown,allEventsOnSameElement:this.step.allEventsOnSameElement,elementToFocusLocatedElement:I.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:I.locatedElement,isRoot:I.isRoot},v=`
|
|
390
390
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
391
|
-
var dnd = ${
|
|
391
|
+
var dnd = ${sh.toString()};
|
|
392
392
|
var eventData = arguments[0];
|
|
393
393
|
var done = arguments[1];
|
|
394
394
|
return dnd.call(null, eventData, done);
|
|
395
395
|
`;return this.driver.executeCodeAsync(v,b,w)}let f=`
|
|
396
396
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
397
|
-
var dnd = ${
|
|
397
|
+
var dnd = ${Xg.toString()};
|
|
398
398
|
var eventData = arguments[0];
|
|
399
399
|
return dnd.call(null, eventData);
|
|
400
|
-
`,
|
|
400
|
+
`,h={fromLocatedElement:t,toLocatedElement:m.locatedElement};return this.driver.executeJS(f,h)}let g=this.getDnDRectsAndOffsets(e,m,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(s,m.seleniumElement,g)}return this.dragPathJs()}let d=this.driver.isSafari()&&this.step.button===2,p=this.driver.isSafari()&&e.tagName==="SELECT";return this.driver.isSafari()&&p?Promise.resolve({keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}):!p&&(!this.step.nativeEvents||d)?this.clickJs():this.step.button===2?this.driver.rightClick(s,c):this.driver.leftClick(s,c)}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(s=>s.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,s;if(!((s=(t=this.context.data)==null?void 0:t.toElement)!=null&&s.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)),s=e[t-1];if(!s||s.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else s.fireOnTarget=!0;return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,s){let n=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>o.locatedElement=n(o)?s:t),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,s=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return s=this.fixEventSequence(s),s=this.addElementLocatedElementToDragEvents(s,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&s.forEach(n=>n.dispatchDragEventsOnClosestDraggable=!0),s}}});var Dn,ih=T(()=>{"use strict";ce();Dn=class extends ${async performAction(e){let{step:t,context:s,frameHandler:n,sessionPlayerInit:{paramEvaluator:o,utils:i,commonConstants:a}}=this,c=this.getTarget();try{let u=await this.stepActionUtils.extractTargetText(c),d,p;if(o){let m=o.computeExpression(t.expression2,s,this.exportsGlobal,this.exportsTest);d=u,p=m.evaluatedText}else{let m=await e.executeStep(t.expression2,s,n,this.exportsGlobal,this.locateElementPlayer,this.exportsTest);d=u,p=m.evaluatedText}try{return i.compareOrMatch(p,d)?{success:!0}:{success:!1,errorType:a.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(p),actual:d}}}catch{return{success:!1,errorType:a.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:p.toString(),actual:d}}}}catch(u){return{success:!1,reason:u.message,exception:u,shouldRetry:!0}}}}});var ah,BE,Bi,ch=T(()=>{"use strict";ah=E(require("lodash"));ce();j();BE=x("evaluate-expression-step-action"),Bi=class extends ${async execute(){let e=this.step,t=this.context,s=this.exportsGlobal,n=this.exportsTest;try{BE.info("runner running incoming params evaluation");let o=t.incomingParams||{};ah.isEmpty(o)&&(o=this.sessionPlayerInit.stepParamBuilder.getStepInputs(e,t,s,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],u=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),p=Function.apply(Function,i.concat([u])).apply(null,a);return t.data[e.targetName]=p,t.data[e.targetId]=p,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:p,data:t.data}}catch(o){let{stepResult:i}=this.sessionPlayerInit.commonConstants;throw{errorType:i.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:o.toString()},success:!1}}}}});var lh,uh=T(()=>{"use strict";lh=function(r,e){let t=typeof Event=="function",s=r.isRoot?document.documentElement:getLocatedElement(r.locatedElement),n={eventIndex:0,element:s,events:r.events,eventType:r.eventType,quirks:r.quirks};if(!s)throw new Error("element not found");window.__unloadNavigator=function(){fe()},window.addEventListener("unload",window.__unloadNavigator);let o=["keydown","keyup","keypress"],i=15;function a(C){try{if(!t)return;let D=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return C.eventData&&(D.data=C.eventData.data),D}catch{}}function c(C){try{let D=document.createEvent("TextEvent");D.data=C.eventData.data;let F=1,G=C.eventData.locale||"en-US";return D.initTextEvent("textInput",!0,!0,window,C.eventData.data,F,G),D}catch{}}function u(C){return a(C)||c()}function d(C,D,F){try{return new KeyboardEvent(C,{bubbles:!0,cancelable:!0,location:D.location||0,key:D.key||"",ctrlKey:Boolean(F.ctrl),shiftKey:Boolean(F.shift),altKey:Boolean(F.alt),metaKey:Boolean(F.meta)})}catch{}}function p(C,D,F){try{let G=document.createEvent("KeyboardEvent");return G.initKeyEvent(C,!0,!0,null,Boolean(F.ctrl),Boolean(F.alt),Boolean(F.shift),Boolean(F.meta),D.key||"",0),G}catch{}}function m(C,D,F){try{let G=document.createEvent("Events");return G.initEvent(C,!0,!0),G.altKey=Boolean(F.alt),G.ctrlKey=Boolean(F.ctrl),G.metaKey=Boolean(F.meta),G.shiftKey=Boolean(F.shift),G.keyCode=D.key||"",G}catch{}}function g(C,D,F){return d(C,D,F)||p(C,D,F)||m(C,D,F)}function f(C){let D=o.indexOf(C.event);if(typeof D!="number"||D<0)return null;let F=C.eventData,G=F.modifiers||{},me=g(C.event,F,G);return Object.defineProperties(me,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),me._keyCode_=F.keyCode,me._charCode_=F.charCode||0,me}function h(C){return C.event==="textInput"?u(C):f(C)}function y(C,D){return function(){var G;return C.event==="textInput"&&!((G=D.quirks)!=null&&G.isAuth0Form)}()}function b(C,D){return C.event==="keyup"&&D.event==="keydown"?i:0}function I(C,D,F){let G=b(D,F);return Math.min(F.timeStamp-D.timeStamp,G)}function w(C){let D=Object.getOwnPropertyDescriptor(C,"value");if(!D)return;let F=C.value;C.value=`${F}#`,D.configurable&&delete C.value,C.value=F;let G=document.createEvent("HTMLEvents");G.initEvent("input",!0,!1),C.dispatchEvent(G),Object.defineProperty(C,"value",D)}function v(C){if(C.isInput)try{if(w(C.element),t)C.element.dispatchEvent(new Event("change"));else{let D=document.createEvent("HTMLEvents");D.initEvent("change",!1,!0),C.element.dispatchEvent(D)}}catch{}}function R(C,D,F){F?setTimeout(()=>{N(C)},I(C,D,F)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(C),fe())}function k(C,D){return(C==="change"||C==="blur")&&D.element.tagName==="OPTION"}function L(C,D,F){return k(C.type,D)?D.element.parentElement:F.locatedElement?getLocatedElement(F.locatedElement):D.element}function S(C,D){let F=C.firstChild,G;for(;F;){if(F.nodeType===3){if(D.offset--<=0)return F}else if(F.nodeType===1&&(G=S(F,D),G))return G;F=F.nextSibling}return null}function O(C,D){if(!(!C||!D)){if(!isNaN(D.start))C.selectionStart=D.start,C.selectionEnd=D.end;else if(!isNaN(D.nodeOffset)){let F;if(C.firstChild?F=S(C,{offset:D.nodeOffset}):F=C,F){let G=window.getSelection(),me=document.createRange();try{G.removeAllRanges(),me.setStart(F,D.textOffset),me.setEnd(F,D.textOffset),G.addRange(me)}catch{}}}}}function A(C,D,F){if(D.isFocusable&&D.isSelectable(C)&&C.type!=="submit")try{O(D.element,F.eventData.selection)}catch{}let G=L(C,D,F);if(!G)throw new Error("could not find element");C.type==="submit"&&G.action?G.submit():G.dispatchEvent(C)}function N(C){let D,F=C.events[C.eventIndex],G=C.events[++C.eventIndex];try{D=h(F)}catch(me){return kt(`exception in get event in text step:${me.message}`)}if(y(F,C))return R(C,F,G);if(D)try{A(D,C,F)}catch(me){return kt(`exception in executeEvent in text step:${me.message}`)}else if(C.noEventExecuter)C.noEventExecuter(C,F);else return kt(`cannot execute event ${F.event}`);R(C,F,G)}function B(C){let D=C.tagName;return D==="INPUT"||D==="TEXTAREA"}function V(C){return C.getAttribute?Boolean(C.getAttribute("contenteditable")==="true"):!1}function X(C,D){if(C.isInput){C.element.value=D.eventData.text;let F=document.createEvent("Event");F.initEvent("input",!0,!1),C.element.dispatchEvent(F)}else C.isContentEditable&&(C.element.innerHTML=D.eventData.text)}function Z(){var D;let C=document.activeElement;for(;(D=C.shadowRoot)!=null&&D.activeElement;)C=C.shadowRoot.activeElement;return C}function fe(C){let D={status:"done",result:C,success:!0};n.isNonTextableElemnet&&(D.reason="Set text on non input element"),e(D)}function kt(C){C=C||{};let D={status:"failed",result:C,success:!1};n.isNonTextableElemnet&&(D.reason="Set text on non input element"),e(D)}try{n.isInput=B(n.element),n.isContentEditable=V(n.element),!n.isInput&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=n.isInput||n.isContentEditable,n.isSelectable=function(C){return C.type!=="keyup"},n.noEventExecuter=X}catch(C){kt(`exception in set text step:${C.message}`);return}let qr=Z();dispatchFocus(r.elementToFocusLocatedElement,qr),N(n)}});var $i,dh=T(()=>{"use strict";ce();xi();U();uh();$i=class extends ${async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Ne(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var d;let e=this.step,t=this.context,s=t.data[e.targetId||"targetId"],n=t.data.timeToPlayStep+3e3,o=e.events,{setTextDraftJs:i}=this.sessionPlayerInit.codeSnippets;if(s.isDraftEditor&&i)return this.driver.executeJS(i(s.locatedElement,t.stepText));if(!(o!=null&&o.length))return;let a={eventType:e.type,events:o,quirks:e.quirks,locatedElement:s.locatedElement,isRoot:s.isRoot,elementToFocusLocatedElement:s.elementToFocusLocatedElement},c=`
|
|
401
401
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
402
|
-
var dispatchFocus = ${
|
|
403
|
-
var setText = ${
|
|
402
|
+
var dispatchFocus = ${Dr};
|
|
403
|
+
var setText = ${lh.toString()};
|
|
404
404
|
var eventData = arguments[0];
|
|
405
405
|
var done = arguments[1];
|
|
406
406
|
return setText.call(null, eventData, done);
|
|
407
|
-
`,u=await this.driver.executeCodeAsync(c,n,a);return{success:Boolean((d=u.value)==null?void 0:d.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let s=0;s<e.length;s++)await this.driver.elementIdValue(
|
|
407
|
+
`,u=await this.driver.executeCodeAsync(c,n,a);return{success:Boolean((d=u.value)==null?void 0:d.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let s=0;s<e.length;s++)await this.driver.elementIdValue(Ne(t.seleniumElement),e[s]),s<e.length-1&&await se(this.step.delayBetweenChars)}async setValueAppendNative(){let e=[],t=this.context,s=this.getTarget();if(s!=null&&s.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Ne(s.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;if(this.step.appendText){if(this.step.nativeEvents)return this.setValueAppendNative();let{stepResult:s}=this.sessionPlayerInit.commonConstants;return{success:!1,errorType:s.TEXT_ACTION_FAILURE,resultInfo:{error:"'Append Text' is only supported in Native Mode"}}}return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var ph,mh=T(()=>{"use strict";ph=function(r,e){var d;function t(p,m){let g=`data-testim-${p}`,f="Native sessionStorage is not available";function h(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(h))throw new Error(f);let y=JSON.parse(window.sessionStorage.getItem(g)||"{}"),b=Object.assign({},y,m);window.sessionStorage.setItem(g,JSON.stringify(b))}catch(y){let b=y.message.toLowerCase().includes("quota"),I=y.message===f;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||b||I){let w=document.head.querySelector("#testim-storage-backup");w||(w=document.createElement("meta"),w.id="testim-storage-backup",document.head.append(w));let v=JSON.parse(w.getAttribute(g)||"{}"),R=Object.assign({},v,m);if(w.setAttribute(g,JSON.stringify(R)),b||I){try{window.sessionStorage.removeItem(g)}catch{}(window.TSTA=window.TSTA||{}).useFallbackStorage=!0}return}throw y}}function s(p){return p.function?p.function.args.map(m=>m!=null&&m.locatedElement?getLocatedElement(m.locatedElement):m):p.directParams.map(m=>m.selector?document.querySelector(m.selector):m.value).concat(p.otherParams)}function n(p,m){function g(){return p.apply(this,m)}return g.prototype=p.prototype,new g}let o={},i={},a={},c=r.functionParams,u=r.transactionId;try{let p=s(r);p.push(o,i,a);let m=((d=r.function)==null?void 0:d.params)||c,f=(e||n(Function,m)).apply(null,p);typeof Promise<"u"&&f instanceof Promise?(t(u,{type:"promise"}),f.then(h=>{t(u,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})},h=>{t(u,{status:"failed",success:!1,result:{resultValue:h.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(u,{status:"done",success:!0,result:{resultValue:f,exports:o,exportsTest:i,exportsGlobal:a}})}catch(p){t(u,{status:"failed",success:!1,result:{resultValue:p.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}}});var Wi,Bu,ar,Gi=T(()=>{"use strict";Wi=E(require("lodash"));U();ce();j();mh();ye();Bu=x("base-js-step-action"),ar=class extends ${isExceedingMaxResultSize(e,t){try{let s=t.project.defaults.enforceMaximumJsResultSize,n=M.flags.maximumJsResultSize.getValue(),o=JSON.stringify(e).length>n;return s?o:(o&&Bu.warn(`js result size exceeded ${n}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(e){return this.driver.executeJS(t=>{let s=`data-testim-${t}`;try{return window.sessionStorage.getItem(s)}catch(n){if(n.message.includes("sessionStorage")||n.message.includes("The operation is insecure")){let o=document.head.querySelector("#testim-storage-backup");return o?o.getAttribute(s):"{}"}throw n}},e)}constructJSFunParams(e){let t=e.incomingParams,s=["context",...t.as.functionParameters,"exports","exportsTest","exportsGlobal"],n=[e.context,...t.as.functionArguments];return s.push(e.code),n.forEach(o=>{Wi.isObject(o)&&mo(o,"seleniumElement",Wi.isEqual)}),{function:{params:s,args:n},transactionId:e.transactionId,browser:e.browser,browserMajor:e.browserMajor}}checkStatus(e){let t=this,s=t.context.config.retryTimeout,n=t.context.data.timeToPlayStep-s;async function o(){let i;try{i=await t.executeGetStatus(e)}catch(u){Bu.warn("failed to get js status",{err:u}),i={value:{status:"exception"}}}let a;try{a=JSON.parse(i?i.value:"{}")}catch{Bu.warn("non object value",{selRes:i}),a={status:"exception"}}let c=t.stepActionUtils.abortedSteps.find(u=>u.id===t.step.id);return c||(a?a.status&&a.status==="done"?a:a.status&&a.status==="failed"?{success:!1,shouldRetry:!0,result:a.result}:n-s<=0?Object.assign(a,{success:!1,shouldRetry:!0}):(n-=s,await se(s),o()):{success:!0})}return o()}executeInAut(e){let t=M.flags.experimentalPreCodeCompilation.isEnabled(),s=M.flags.experimentalAsyncCustomCode.isEnabled(),n=this.constructJSFunParams(e),o=n.function.args.some(u=>Boolean(u==null?void 0:u.locatedElement)),i="undefined";if(t){let u=n.function.params.slice(0,-1);i=s?`async function(${u.join(",")}) {
|
|
408
408
|
${e.code}
|
|
409
409
|
};`:`function(${u.join(",")}) {
|
|
410
410
|
${e.code}
|
|
411
411
|
};`,n.function.params.pop()}let{codeSnippets:a}=this.sessionPlayerInit,c=`
|
|
412
412
|
${o?`var getLocatedElement = ${a.getLocatedElementCode};`:";"}
|
|
413
|
-
var runCode = ${
|
|
413
|
+
var runCode = ${ph.toString()};
|
|
414
414
|
var eventData = arguments[0];
|
|
415
415
|
var funcToRun = ${i};
|
|
416
416
|
return runCode.call(null, eventData, funcToRun);
|
|
417
|
-
`;return t?this.driver.executeJS(c,n).catch(u=>this.handleExecutionError(u)):this.driver.executeJS(c,n)}codeExecDone(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants,{context:s}=this,{result:n={},tstConsoleLogs:o,nodeVersion:i,navigateToDifferentDomain:a}=e;n.exports&&(s.data.exports=n.exports);let c={nodeVersion:i,tstConsoleLogs:o,data:s.data};return this.isFailedResult(n.resultValue)?Object.assign(c,{success:!1,errorType:t.JS_ASSERTION_FAILED}):this.isExceedingMaxResultSize({result:n,tstConsoleLogs:o},s)?Object.assign(c,{success:!1,errorType:t.JS_RESULT_MAX_SIZE_EXCEEDED}):(Object.assign(c,{success:!0,exportsTest:n.exportsTest,exportsGlobal:n.exportsGlobal}),a&&(c.navigateToDifferentDomain=a)),Promise.resolve(c)}codeExecFailed(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants,{context:s}=this;if(e.type==="promise")return Promise.resolve({data:s.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:t.JS_ASSERTION_FAILED});if(e.reason==="stopped")return Promise.resolve(Object.assign({},e,{errorType:t.STOPPED}));let{result:n={},tstConsoleLogs:o}=e,i={tstConsoleLogs:o,data:s.data,exportsGlobal:n.exportsGlobal,exportsTest:n.exportsTest,success:!1,errorType:t.UNWRAPPED_AUT_REJECT,resultInfo:{error:n.resultValue}};return Promise.resolve(i)}checkCodeResponse(e){return e!=null&&e.success?this.codeExecDone(e):this.codeExecFailed(e)}async performAction(){let e=this.step,t=this.context;this.startTimestamp=Date.now();let s={transactionId:`${t.testResultId}:${e.id}`,id:e.id,eventType:e.type,code:e.code,incomingParams:t.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:t.config,data:t.data},testResultId:t.testResultId},n=await this.driver.getBrowserAndOS();Object.assign(s,{browser:n.browser,browserMajor:n.browserMajor}),this.context.isPendingPromise||await this.executeInAut(s);let o=await this.checkStatus(s.transactionId);return await this.checkCodeResponse(o)}handleExecutionError(e){throw(e==null?void 0:e.name)==="javascript error"?new Error(e.message):e}}});var Wt,
|
|
417
|
+
`;return t?this.driver.executeJS(c,n).catch(u=>this.handleExecutionError(u)):this.driver.executeJS(c,n)}codeExecDone(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants,{context:s}=this,{result:n={},tstConsoleLogs:o,nodeVersion:i,navigateToDifferentDomain:a}=e;n.exports&&(s.data.exports=n.exports);let c={nodeVersion:i,tstConsoleLogs:o,data:s.data};return this.isFailedResult(n.resultValue)?Object.assign(c,{success:!1,errorType:t.JS_ASSERTION_FAILED}):this.isExceedingMaxResultSize({result:n,tstConsoleLogs:o},s)?Object.assign(c,{success:!1,errorType:t.JS_RESULT_MAX_SIZE_EXCEEDED}):(Object.assign(c,{success:!0,exportsTest:n.exportsTest,exportsGlobal:n.exportsGlobal}),a&&(c.navigateToDifferentDomain=a)),Promise.resolve(c)}codeExecFailed(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants,{context:s}=this;if(e.type==="promise")return Promise.resolve({data:s.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:t.JS_ASSERTION_FAILED});if(e.reason==="stopped")return Promise.resolve(Object.assign({},e,{errorType:t.STOPPED}));let{result:n={},tstConsoleLogs:o}=e,i={tstConsoleLogs:o,data:s.data,exportsGlobal:n.exportsGlobal,exportsTest:n.exportsTest,success:!1,errorType:t.UNWRAPPED_AUT_REJECT,resultInfo:{error:n.resultValue}};return Promise.resolve(i)}checkCodeResponse(e){return e!=null&&e.success?this.codeExecDone(e):this.codeExecFailed(e)}async performAction(){let e=this.step,t=this.context;this.startTimestamp=Date.now();let s={transactionId:`${t.testResultId}:${e.id}`,id:e.id,eventType:e.type,code:e.code,incomingParams:t.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:t.config,data:t.data},testResultId:t.testResultId},n=await this.driver.getBrowserAndOS();Object.assign(s,{browser:n.browser,browserMajor:n.browserMajor}),this.context.isPendingPromise||await this.executeInAut(s);let o=await this.checkStatus(s.transactionId);return await this.checkCodeResponse(o)}handleExecutionError(e){throw(e==null?void 0:e.name)==="javascript error"?new Error(e.message):e}}});var Wt,fh=T(()=>{"use strict";Gi();Wt=class extends ar{isFailedResult(e){return e===!1}}});var Cs,gh=T(()=>{"use strict";Gi();Cs=class extends ar{isFailedResult(e){return!e}}});var $E,Vi,hh=T(()=>{"use strict";ce();U();$E={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},Vi=class extends ${setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Ne(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push($E[t]),this.setWithValueApi(e)}}});function yh(r,e){function t(s,n){let o=Element.prototype.matches,i=o&&isNativeFunction(o)?o:document.createElement(s.tagName).__proto__.matches;do{if(i.call(s,n))return s;s=s.parentElement||s.parentNode}while(s!==null&&s.nodeType===1);return null}try{let s=getLocatedElement(r);if(!s)return{success:!1,status:"failed",result:"option element not found"};let n=t(s,"select");return n?(n.focus(),s.selected?{success:!0,status:"done"}:(s.selected=!0,["input","change"].map(i=>{let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}).forEach(i=>{if(e){n.dispatchEvent(i);return}s.dispatchEvent(i)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(s){return{success:!1,status:"failed",result:s.toString()}}}var bh=T(()=>{"use strict"});var qi,wh=T(()=>{"use strict";ce();bh();U();ye();qi=class extends ${async performAction(){var p,m;let e=this.context.data[this.step.targetId||"targetId"],{seleniumElement:t,locatedElement:s}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((p=this.step.element)==null?void 0:p.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(Ne(t))}catch(g){if(!g.message.includes("Cannot check the displayedness of a non-Element argument"))throw g}let c=M.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),u=`
|
|
418
418
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
419
419
|
var isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
|
|
420
|
-
var selectOption = ${
|
|
420
|
+
var selectOption = ${yh.toString()};
|
|
421
421
|
return selectOption.apply(null, arguments);
|
|
422
|
-
`;return(m=(await this.driver.executeJSWithArray(u,[s,c])).value)!=null&&m.success?{success:!0}:{success:!1}}}});var Hi,
|
|
422
|
+
`;return(m=(await this.driver.executeJSWithArray(u,[s,c])).value)!=null&&m.success?{success:!0}:{success:!1}}}});var Hi,Th=T(()=>{"use strict";ce();Hi=class extends ${async performAction(){await this.driver.submit(this.getTarget().seleniumElement)}}});var WE,zi,vh=T(()=>{"use strict";ce();WE=(r,e,t,s)=>({x:t,y:s,width:e,height:r,get top(){return this.y},get left(){return this.x},get right(){return this.x+this.width},get bottom(){return this.y+this.height},toJSON(){}}),zi=class extends ${getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:s,rect:n}=e,{width:o,height:i}=n,a=o/2,c=i/2,u=this.step.element.clickOffset;if(u&&this.step.shouldAccountForMouseOffsetInHover){let{x:p,y:m}=u;this.sessionPlayerInit.utils.isWithinTargetRect(WE(i,o,0,0),p,m)&&(a=p,c=m)}let d={frameOffset:{x:n.left-s.left,y:n.top-s.top},rect:s,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,d),{success:!0}}}});var Eh,Sh=T(()=>{"use strict";Eh=function(r,e){function s(a,c){function u(f,h,y){return y>f&&y<h}let d=a.pointerPosition||{},p=c.getBoundingClientRect(),m=d.originX&&u(p.left,p.left+p.width,d.originX)?d.originX:p.left+p.width/2,g=d.originY&&u(p.top,p.top+p.height,d.originY)?d.originY:p.top+p.height/2;return{x:m,y:g}}function n(a,c,u){let d=s(a,u),p=(c==null?void 0:c.modifiers)||{},m={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:d.x,clientY:d.y,bubbles:!0,cancelable:!0,ctrl:Boolean(p.ctrl),alt:Boolean(p.alt),shift:Boolean(p.shift),meta:Boolean(p.meta)};return new WheelEvent("wheel",m)}function o(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let u=a.shift(),d=n(u,r.eventData,c),p=a[0]?Math.min(a[0].timeStamp-u.timeStamp,200):200;c.dispatchEvent(d),setTimeout(()=>{o(a,c)},p)}let i=getLocatedElement(r.locatedElement);o(r.events,i)}});var Ki,Rh=T(()=>{"use strict";ce();Sh();Ki=class extends ${async performAction(){var c;let e=this.step,t=this.context,s=e.events;if(!(s!=null&&s.length))return;let n={events:s,eventData:{modifiers:e.modifiers,button:e.button},locatedElement:this.getTarget().locatedElement},o=t.data.timeToPlayStep+3e3,i=`
|
|
423
423
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
424
|
-
var wheel = ${
|
|
424
|
+
var wheel = ${Eh.toString()};
|
|
425
425
|
var eventData = arguments[0];
|
|
426
426
|
var done = arguments[1];
|
|
427
427
|
return wheel.call(null, eventData, done);
|
|
428
|
-
`;return{success:((c=(await this.driver.executeCodeAsync(i,o,n)).value)==null?void 0:c.state)==="success"}}}});var
|
|
428
|
+
`;return{success:((c=(await this.driver.executeCodeAsync(i,o,n)).value)==null?void 0:c.state)==="success"}}}});var Ih,xh=T(()=>{"use strict";Ih=function(r,e){let t=getLocatedElement(r);if(!t)throw new Error("element not found");function s(){let i=-1,a=0,c=[],u={waitOn(){let d=++i;return function(p){d in c||(c[d]=p,a++,e.length===a&&u.endWithCallback(c))}},endWith(d){u.endWithCallback=d}};return u}function n(i,a,c){let u=new XMLHttpRequest;u.open("GET",i),u.responseType="blob",u.onload=function(){if(this.status>=200&&this.status<300)c({blob:u.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},u.onerror=function(){throw new Error("Failed to load blob")},u.send()}let o=s();e.forEach(i=>{n(i.url,i.name,o.waitOn())}),o.endWith(i=>{let a=createDropEvent(i);t.dispatchEvent(a)})}});var GE,Ji,Ph=T(()=>{"use strict";ce();j();xh();ye();GE=x("drop-file-step-action"),Ji=class extends ${async performAction(){let{codeSnippets:e,utils:t}=this.sessionPlayerInit,s=this.context.data[this.step.targetId||"targetId"],n=M.flags.overrideAzureStorageUrl.isEnabled(),o=await t.addTokenToFileUrl(this.context.project.id,this.step.fileUrls,this.stepActionUtils.testimServicesApi,n,GE),i=`
|
|
429
429
|
var getLocatedElement = ${e.getLocatedElementCode};
|
|
430
430
|
var createDropEvent = ${e.createDropEvent.toString()};
|
|
431
|
-
var downloadFileAndFireDropEvent = ${
|
|
431
|
+
var downloadFileAndFireDropEvent = ${Ih.toString()};
|
|
432
432
|
return downloadFileAndFireDropEvent.apply(null, arguments)
|
|
433
|
-
`;return await this.driver.executeJSWithArray(i,[s.locatedElement,o])}}});function
|
|
433
|
+
`;return await this.driver.executeJSWithArray(i,[s.locatedElement,o])}}});function kh(r={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
|
|
434
434
|
var input = getLocatedElement(locatedElement);
|
|
435
435
|
if(input) {
|
|
436
436
|
function parents(element, _elements) {
|
|
@@ -472,7 +472,7 @@ Action required: Please allow opening a websockets connection to ${ge} in your f
|
|
|
472
472
|
input.removeAttribute("disabled");
|
|
473
473
|
input.focus();
|
|
474
474
|
}
|
|
475
|
-
}`}async function qE(r,e){let t=null;try{t=(await nc(r)).body}catch(n){if(VE.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let s=`${
|
|
475
|
+
}`}async function qE(r,e){let t=null;try{t=(await nc(r)).body}catch(n){if(VE.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let s=`${Ah.tmpdir()}/${e}`;return await Ch.promises.writeFile(s,t),s}function HE(r){return de(r,e=>qE(e.url,e.name))}function zE(r,e){return e(r)}async function _h(r,e){let t=await HE(r),s=await de(t,n=>zE(n,e));return Array.isArray(s)&&s.map(n=>n==null?void 0:n.value)}var Ah,Ch,VE,Oh=T(()=>{"use strict";Ah=E(require("os"));Rt();Ch=require("fs");U();j();VE=x("input-file-utils")});function JE(){return`async function downloadAndUpload(locatedElement, fileUrls) {
|
|
476
476
|
const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
|
|
477
477
|
const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
|
|
478
478
|
const attachTo = document.body || document.documentElement;
|
|
@@ -549,22 +549,22 @@ Action required: Please allow opening a websockets connection to ${ge} in your f
|
|
|
549
549
|
element.dispatchEvent(new Event("change", { bubbles: true }));
|
|
550
550
|
}
|
|
551
551
|
element.removeEventListener("change", changeFiredHandler, true);
|
|
552
|
-
}`}var Xi,
|
|
552
|
+
}`}var Yi,Xi,Lh=T(()=>{"use strict";Oh();ce();j();U();ye();Yi=x("input-file-step-action"),Xi=class extends ${uploadFile(e){return this.driver.uploadFile(e)}forceInputToBeVisible(e,t){Yi.info("workaround - stepaction - move element to visible position");let s=`
|
|
553
553
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
554
|
-
var getVisibleElement = ${
|
|
554
|
+
var getVisibleElement = ${kh(t)};
|
|
555
555
|
return getVisibleElement.apply(null, arguments);
|
|
556
|
-
`;return this.driver.executeJS(s,e.locatedElement)}async safariPreUploadActions(e){let t={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(e,t)}catch(s){throw
|
|
556
|
+
`;return this.driver.executeJS(s,e.locatedElement)}async safariPreUploadActions(e){let t={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(e,t)}catch(s){throw Yi.error("failed to set input file in Safari recovery",{err:s}),s}}async uploadFilesAndForceVisibility(e,t){try{this.driver.isSafari()&&await this.safariPreUploadActions(t),await this.uploadFiles(e,t)}catch(s){let n="The element is not editable",o="The element is not focusable",i="An element command could not be completed because the element is not visible on the page.",a="element not interactable",c="element is not pointer- or keyboard interactable",u="invalid element state: Element is not currently interactable and may not be manipulated",d="Element must not be hidden, disabled or read-only",p="is not reachable by keyboard",m=s?s.message:"";if(m===u||m.startsWith(d)||m.startsWith(n)||m.startsWith(o)||m.startsWith(i)||m.includes(p)||m.includes(a)||m.includes(c)){await this.forceInputToBeVisible(t),await this.uploadFiles(e,t);return}throw Yi.error("failed to set input file",{err:s}),s}}async uploadFiles(e,t){for(let s of e)await this.driver.elementIdValue(Ne(t.seleniumElement),s)}async performAction(){let e=this.context.data[this.step.targetId||"targetId"],t=M.flags.overrideAzureStorageUrl.isEnabled(),s=M.flags.useJsInputCodeInSafari.isEnabled(),n=M.flags.useJsInputCodeInFirefox.isEnabled(),o=M.flags.downloadToBase64.isEnabled(),i=await this.sessionPlayerInit.utils.addTokenToFileUrl(this.context.project.id,this.step.fileUrls,this.stepActionUtils.testimServicesApi,t,Yi),a=this.driver.isSafari()&&(s||i.length>1),c=this.driver.isFirefox()&&(n||i.length>1);if(o&&(i=await Promise.all(i.map(async({name:d,url:p})=>{let m=await vr(p);return{name:d,url:`data:${m.type};base64,${Buffer.from(m.body).toString("base64")}`}}))),a||c){await this.driver.executeJSWithArray(`
|
|
557
557
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
558
558
|
const downloadAndUploadFile = ${JE()};
|
|
559
|
-
return downloadAndUploadFile.apply(null, arguments);`,[e.locatedElement,i]);return}let u=await _g(i,this.uploadFile.bind(this));await this.uploadFilesAndForceVisibility(u,e)}}});var Qi,Zi,Ng=T(()=>{"use strict";Qi=require("url");ce();Zi=class extends ${async updateBaseUrl(e){let t=new Qi.URL(e),s=new Qi.URL(this.context.recordedBaseUrl),n=new Qi.URL(this.context.baseUrl);return t.host===s.host&&s.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var ea,Dg=T(()=>{"use strict";ce();U();ea=class extends ${async performAction(){await se(this.step.durationMS)}}});var ta,Mg=T(()=>{"use strict";ce();ta=class extends ${async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Dn,Fg=T(()=>{"use strict";ce();Dn=class extends ${async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:s}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(s,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return new Promise(s=>{t(e,s)})}async performAction(){let{commonConstants:e}=this.sessionPlayerInit,t=this.step,s=this.context,n={id:t.id,url:s.apiUrl,method:t.method,headers:s.apiHeaders,body:s.apiBody,timeout:s.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:s.fileUrls},o;t.sendViaWebApp?o=await this.runApiInAut(n):o=await this.runApiInBg(n);let 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 ra,Ug=T(()=>{"use strict";ce();ra=class extends ${async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports=this.context.data.exports||{},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var sa,jg=T(()=>{"use strict";ce();na();sa=class extends ${async performAction(){return await ks(this.step,this.context,this.driver,this.stepActionUtils.testimServicesApi.authenticationManager.getLoggedUserInfo(),this.frameHandler.frameManager)}}});var Bg,$g,$u,Wu,Wg=T(()=>{"use strict";Bg=E(require("@applitools/spec-driver-webdriverio")),$g=require("@applitools/eyes-sdk-core");to();Ee();$u=class{constructor(){let{EyeSdkBuilder:e}=re(),t=Ud["@applitools/eyes-sdk-core"]||"N/A";this.sdk=(0,$g.makeSDK)({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:Bg.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,s,n){let{EyeSdkBuilder:o}=re(),i=await this.sdk.makeManager({type:e?"vg":"classic",concurrency:t});return o.rememberCreatedBatch(s,n),i}},Wu=new $u});var Vg,Gg,Mn,qg=T(()=>{"use strict";Vg=E(require("lodash"));ce();j();Wg();Gg=I("pixel-validation-step-action"),Mn=class extends ${async performAction(){var d,p;let{shouldUseVisualGrid:e,applitoolsSdkConfig:t,applitoolsSdkLogger:s,testResultId:n}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},i=((p=t.batch)==null?void 0:p.id)||n,a=await Wu.getManager(e,this.context.config.applitoolsConcurrency||5,i,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},u;try{let m=await a.openEyes({driver:this.driver.client,config:t,logger:s}),f={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Vg.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(f,o.applitoolsStepSettings),Gg.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await m.check({settings:f}),u={isApplitoolsSdkResult:!0,success:!0,eyesResults:await m.close()}}catch(m){Gg.error("Applitools SDK step failed",{err:m,info:m.info}),u={isApplitoolsSdkResult:!0,success:!1,err:m}}return await Wu.handleApplitoolsSdkResult(this.context,u,this.step)}}});var _s,Gu=T(()=>{"use strict";U();Fr();Gi();_s=class extends ar{async executeCliCode(){var f,g,y;let{step:e,context:t}=this,s=this.stepActionUtils.driver.isMobile;if(!((y=(g=(f=t.company)==null?void 0:f.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!s)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o,id:i}=e,{incomingParams:a,testResultId:c,retryIndex:u,stepResultId:d}=t,p={config:t.config,data:t.data},m=t.data.timeToPlayStep,h=await Es(o,i,a,p,c,u,d,m);return await this.checkCodeResponse(h)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof X?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var cr,Hg=T(()=>{"use strict";Gu();cr=class extends _s{isFailedResult(e){return e===!1}}});var oa,zg=T(()=>{"use strict";Gu();oa=class extends _s{isFailedResult(e){return!e}}});var ia,Kg=T(()=>{"use strict";U();Fr();ce();q();ia=class extends ${async performAction(){let{context:e}=this,{stepId:t,packageData:s,resultId:n,retryIndex:o,stepResultId:i,timeToPlayBeforeExec:a}=e;try{return{data:await vs(t,n,o,s,i,a),success:!0}}catch(c){return c instanceof dt?{success:!1,code:"invalid-node-package",message:c.message}:c instanceof X?{success:!1,code:"timeout"}:{success:!1,reason:c.message,exception:c}}}}});var Os,Jg=T(()=>{"use strict";ce();Os=class extends ${async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}}});var je,Xg=T(()=>{"use strict";ce();je=class extends ${async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var aa,Yg=T(()=>{"use strict";ce();aa=class extends ${async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});function XE(r,e){Object.keys(r).forEach(t=>{e.registerStepAction(t,r[t])})}function ca(r,e){XE(YE,e),e.registerLocateStepActionUtils&&e.registerLocateStepActionUtils(On.getUtils(r))}var YE,Vu=T(()=>{"use strict";zh();Xh();og();ig();cg();dg();fg();hg();gg();wg();Tg();vg();Rg();Pg();Lg();Ng();Dg();Mg();Fg();Ug();jg();qg();Hg();zg();Kg();Jg();Xg();Yg();YE={locate:On,scroll:Ui,mouse:ji,submit:Hi,text:$i,"special-key":Vi,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":Cs,"skip-code-step":Cs,"element-code-step":Cs,"evaluate-expression":Bi,"text-validation":Nn,"wait-for-text-validation":Nn,"select-option":qi,"drop-file":Ji,"input-file":Yi,hover:zi,navigation:Zi,wheel:Ki,sleep:ea,refresh:ta,"api-validation":Dn,"api-action":Dn,"api-code-step":Wt,"extract-text":ra,"simple-ui-verification":Mn,"wait-for-simple-ui-verification":Mn,"cli-validation-download-file":Os,"cli-wait-for-download-file":Os,"network-validation-step":Os,"cli-validation-code-step":cr,"cli-wait-for-code-step":cr,"cli-action-code-step":cr,"cli-api-code-step":cr,"cli-condition-step":oa,"node-package":ia,"email-code-step":Wt,"cli-email-code-step":cr,"tdk-hybrid":sa,"sfdc-recorded-step":aa,"sfdc-step-login":je,"sfdc-step-loginas":je,"sfdc-step-logout":je,"sfdc-step-sobjectcreate":je,"sfdc-step-sobjectdelete":je,"sfdc-step-findrecord":je,"sfdc-step-quickaction":je,"sfdc-step-sobjectedit":je,"sfdc-step-sobjectvalidate":je,"sfdc-step-launchapp":je,"sfdc-step-closeconsoletabs":je,"sfdc-step-relatedlistaction":je,"sfdc-step-permission-validation":je}});var qu,Fn,Hu=T(()=>{"use strict";qu=class{on(){}},Fn=new qu});var Qg,QE,Zg,ZE,Ls,zu=T(()=>{"use strict";Qg=E(require("lodash")),QE=1e3,Zg=["simple-ui-verification","wait-for-simple-ui-verification"],ZE=[...Zg,"custom-validation","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation"],Ls=class{constructor(e){this.resetStepVariables(),this.resetRetryVariables(),this.isDebuggerConnected=e}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let s=Date.now();this.currentRetryStart=s,this.lastUpdateTime=s}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let s=this.getTotalStepRunTime(e),n=ZE.includes(e.stepType)?[s]:t(s);this.resetStepVariables(s,n),e.context.data.maxTotalStepTime=s}getStepTimes(){return this.totalStepTimesReport.push(this.currentRetryTimesReport),Qg.cloneDeep(this.totalStepTimesReport)}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let s=e.context.config.stepTimeout;return Zg.includes(e.stepType)&&(s=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(s=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:s}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let s=Date.now()-e.startTimestamp;return t-s}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+QE}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}calcAndroidScrollTimeout(e){let s=2e3;return e.step.isScrollToElement&&(s=4e3),e.step.events.length*s+5e3}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,s=e.step.type,n=3e4,o;return s==="sleep"?o=e.step.durationMS+t:s==="android-scroll"?o=Math.max(this.calcAndroidScrollTimeout(e),n):o=Math.max(this.getTotalStepTimeLeftToPlay(e),n),o}setStepPhaseTime(e){let t=Date.now(),s=t-this.lastUpdateTime;this.lastUpdateTime=t,this.currentRetryTimesReport[e]=s}reportGetTabTime(){this.setStepPhaseTime("tab")}reportGetFrameTime(){this.setStepPhaseTime("frame")}reportCalcConditionTime(){this.setStepPhaseTime("condition")}reportPreLocateActionsTime(){this.setStepPhaseTime("pre-locate")}reportFindElementsTime(){this.setStepPhaseTime("locate")}reportStepActionTime(){this.setStepPhaseTime("action")}}});var Ku={};W(Ku,{SeleniumTestPlayer:()=>Un});var Un,la=T(()=>{"use strict";U();Cn();Pu();Mh();Ou();Lu();jh();Nu();Ee();As();Vu();Hu();zu();Un=class{constructor(e,t,s,n="code",o=new Dr,i,a){let{sessionPlayer:c,commonConstants:u,stepActionFactory:d}=re();this.driver=o,this.id=e;let p=new Ps(this.driver);this.stepActionFactory=new d(p),ca(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Oi(this.driver),this.driver.tabService=this.tabService,this.windowCreationListener=Fn,this.playbackTimeoutCalculator=new Ls(Ni()),this.tabService.createSesion(e);let m=Uh(this.driver);this.sessionPlayer=new c(e,this.tabService,new Rs(this.driver),Fn,m,Li,null,null,p,this.stepActionFactory,this.playbackTimeoutCalculator,Qe.getSocket(),n),this.sessionPlayer.setShouldMonitorPerformance&&this.sessionPlayer.setShouldMonitorPerformance(s),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(u.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>{})}onDone(){let{commonConstants:e}=re(),t=1e3*60*2;return te(this.driver.end(),t).catch(s=>{if(s instanceof X)return this.driver.forceEnd().catch(()=>null)}).then(()=>{this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),this.sessionPlayer=null,this.tabService=null,this.stepActionFactory=null,this.driver=null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},s=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(s);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var ry={};W(ry,{buildCodeTests:()=>Ju});async function eS(r,e,t,s,n){try{return await ey(r,e,t,s,n)}catch(o){if((o==null?void 0:o.code)==="ENOENT")return lr.compiler=null,lr.webpackConfig=null,s&&(s.data={}),await ey(r,e,t,s,n);throw o}}async function ey(r,e={mode:"development"},t=void 0,s=void 0,n=void 0){let o=await he("webpack"),i=ur.cloneDeep(e);e.externals={testim:"__testim"},e.devtool||(e.devtool="inline-source-map"),e.plugins||(e.plugins=[]),e.plugins.push(new o.DefinePlugin(tS(t)),new o.DefinePlugin({"process.argv":JSON.stringify(process.argv)})),r=r.map(f=>ua.resolve(f));let a=r.map(()=>z(30));if(e.optimization={minimize:!1},Number(process.versions.node.split(".")[0])>=17){let f=require("crypto"),g=f.createHash;f.createHash=(y,b)=>g(y==="md4"?"sha256":y,b)}e.entry=Object.fromEntries(ur.zip(r,a).map(([f,g])=>[g,f])),e.output=Object.assign({devtoolModuleFilenameTemplate:f=>`file:///${f.absoluteResourcePath}`,filename:"[name].bundle.js"},e.output);let u;s?(ur.isEqual(lr.webpackConfig,i)&&lr.compiler||(lr.webpackConfig=i,lr.compiler=o(e)),u=lr.compiler):u=o(e);let d=s||new ty.default;u.outputFileSystem=d;let p=pt(f=>{n==null||n.addEventListener("abort",()=>{f(new Be,void 0)})});try{let f=await Promise.race([pt(g=>u.run(g)),p]);if(f!=null&&f.hasErrors()){let{errors:g}=f.toJson(),y=g.map(b=>`
|
|
560
|
-
${typeof b=="string"?b:b.message||"Unknown error"}`).join("");throw new Error(y)}}catch(f){let
|
|
559
|
+
return downloadAndUploadFile.apply(null, arguments);`,[e.locatedElement,i]);return}let u=await _h(i,this.uploadFile.bind(this));await this.uploadFilesAndForceVisibility(u,e)}}});var Qi,Zi,Dh=T(()=>{"use strict";Qi=require("url");ce();Zi=class extends ${async updateBaseUrl(e){let t=new Qi.URL(e),s=new Qi.URL(this.context.recordedBaseUrl),n=new Qi.URL(this.context.baseUrl);return t.host===s.host&&s.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var ea,Nh=T(()=>{"use strict";ce();U();ea=class extends ${async performAction(){await se(this.step.durationMS)}}});var ta,Mh=T(()=>{"use strict";ce();ta=class extends ${async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Nn,Fh=T(()=>{"use strict";ce();Nn=class extends ${async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:s}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(s,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return new Promise(s=>{t(e,s)})}async performAction(){let{commonConstants:e}=this.sessionPlayerInit,t=this.step,s=this.context,n={id:t.id,url:s.apiUrl,method:t.method,headers:s.apiHeaders,body:s.apiBody,timeout:s.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:s.fileUrls},o;t.sendViaWebApp?o=await this.runApiInAut(n):o=await this.runApiInBg(n);let 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 ra,Uh=T(()=>{"use strict";ce();ra=class extends ${async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports=this.context.data.exports||{},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var sa,jh=T(()=>{"use strict";ce();na();sa=class extends ${async performAction(){return await ks(this.step,this.context,this.driver,this.stepActionUtils.testimServicesApi.authenticationManager.getLoggedUserInfo(),this.frameHandler.frameManager)}}});var Bh,$h,$u,Wu,Wh=T(()=>{"use strict";Bh=E(require("@applitools/spec-driver-webdriverio")),$h=require("@applitools/eyes-sdk-core");to();Ee();$u=class{constructor(){let{EyeSdkBuilder:e}=re(),t=Ud["@applitools/eyes-sdk-core"]||"N/A";this.sdk=(0,$h.makeSDK)({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:Bh.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,s,n){let{EyeSdkBuilder:o}=re(),i=await this.sdk.makeManager({type:e?"vg":"classic",concurrency:t});return o.rememberCreatedBatch(s,n),i}},Wu=new $u});var Vh,Gh,Mn,qh=T(()=>{"use strict";Vh=E(require("lodash"));ce();j();Wh();Gh=x("pixel-validation-step-action"),Mn=class extends ${async performAction(){var d,p;let{shouldUseVisualGrid:e,applitoolsSdkConfig:t,applitoolsSdkLogger:s,testResultId:n}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},i=((p=t.batch)==null?void 0:p.id)||n,a=await Wu.getManager(e,this.context.config.applitoolsConcurrency||5,i,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},u;try{let m=await a.openEyes({driver:this.driver.client,config:t,logger:s}),f={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Vh.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(f,o.applitoolsStepSettings),Gh.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await m.check({settings:f}),u={isApplitoolsSdkResult:!0,success:!0,eyesResults:await m.close()}}catch(m){Gh.error("Applitools SDK step failed",{err:m,info:m.info}),u={isApplitoolsSdkResult:!0,success:!1,err:m}}return await Wu.handleApplitoolsSdkResult(this.context,u,this.step)}}});var _s,Gu=T(()=>{"use strict";U();Fr();Gi();_s=class extends ar{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,s=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!s)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o,id:i}=e,{incomingParams:a,testResultId:c,retryIndex:u,stepResultId:d}=t,p={config:t.config,data:t.data},m=t.data.timeToPlayStep,g=await Es(o,i,a,p,c,u,d,m);return await this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof Y?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var cr,Hh=T(()=>{"use strict";Gu();cr=class extends _s{isFailedResult(e){return e===!1}}});var oa,zh=T(()=>{"use strict";Gu();oa=class extends _s{isFailedResult(e){return!e}}});var ia,Kh=T(()=>{"use strict";U();Fr();ce();q();ia=class extends ${async performAction(){let{context:e}=this,{stepId:t,packageData:s,resultId:n,retryIndex:o,stepResultId:i,timeToPlayBeforeExec:a}=e;try{return{data:await vs(t,n,o,s,i,a),success:!0}}catch(c){return c instanceof dt?{success:!1,code:"invalid-node-package",message:c.message}:c instanceof Y?{success:!1,code:"timeout"}:{success:!1,reason:c.message,exception:c}}}}});var Os,Jh=T(()=>{"use strict";ce();Os=class extends ${async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}}});var je,Yh=T(()=>{"use strict";ce();je=class extends ${async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var aa,Xh=T(()=>{"use strict";ce();aa=class extends ${async performAction(){var s,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(s=this.step).getStepPreview)==null?void 0:n.call(s)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});function YE(r,e){Object.keys(r).forEach(t=>{e.registerStepAction(t,r[t])})}function ca(r,e){YE(XE,e),e.registerLocateStepActionUtils&&e.registerLocateStepActionUtils(On.getUtils(r))}var XE,Vu=T(()=>{"use strict";zg();Yg();oh();ih();ch();dh();fh();gh();hh();wh();Th();vh();Rh();Ph();Lh();Dh();Nh();Mh();Fh();Uh();jh();qh();Hh();zh();Kh();Jh();Yh();Xh();XE={locate:On,scroll:Ui,mouse:ji,submit:Hi,text:$i,"special-key":Vi,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":Cs,"skip-code-step":Cs,"element-code-step":Cs,"evaluate-expression":Bi,"text-validation":Dn,"wait-for-text-validation":Dn,"select-option":qi,"drop-file":Ji,"input-file":Xi,hover:zi,navigation:Zi,wheel:Ki,sleep:ea,refresh:ta,"api-validation":Nn,"api-action":Nn,"api-code-step":Wt,"extract-text":ra,"simple-ui-verification":Mn,"wait-for-simple-ui-verification":Mn,"cli-validation-download-file":Os,"cli-wait-for-download-file":Os,"network-validation-step":Os,"cli-validation-code-step":cr,"cli-wait-for-code-step":cr,"cli-action-code-step":cr,"cli-api-code-step":cr,"cli-condition-step":oa,"node-package":ia,"email-code-step":Wt,"cli-email-code-step":cr,"tdk-hybrid":sa,"sfdc-recorded-step":aa,"sfdc-step-login":je,"sfdc-step-loginas":je,"sfdc-step-logout":je,"sfdc-step-sobjectcreate":je,"sfdc-step-sobjectdelete":je,"sfdc-step-findrecord":je,"sfdc-step-quickaction":je,"sfdc-step-sobjectedit":je,"sfdc-step-sobjectvalidate":je,"sfdc-step-launchapp":je,"sfdc-step-closeconsoletabs":je,"sfdc-step-relatedlistaction":je,"sfdc-step-permission-validation":je}});var qu,Fn,Hu=T(()=>{"use strict";qu=class{on(){}},Fn=new qu});var Qh,QE,Zh,ZE,Ls,zu=T(()=>{"use strict";Qh=E(require("lodash")),QE=1e3,Zh=["simple-ui-verification","wait-for-simple-ui-verification"],ZE=[...Zh,"custom-validation","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation"],Ls=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let s=Date.now();this.currentRetryStart=s,this.lastUpdateTime=s}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let s=this.getTotalStepRunTime(e),n=ZE.includes(e.stepType)?[s]:t(s);this.resetStepVariables(s,n),e.context.data.maxTotalStepTime=s}getStepTimes(){return this.totalStepTimesReport.push(this.currentRetryTimesReport),Qh.cloneDeep(this.totalStepTimesReport)}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let s=e.context.config.stepTimeout;return Zh.includes(e.stepType)&&(s=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(s=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:s}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let s=Date.now()-e.startTimestamp;return t-s}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+QE}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}calcAndroidScrollTimeout(e){let s=2e3;return e.step.isScrollToElement&&(s=4e3),e.step.events.length*s+5e3}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,s=e.step.type,n=3e4,o;return s==="sleep"?o=e.step.durationMS+t:s==="android-scroll"?o=Math.max(this.calcAndroidScrollTimeout(e),n):o=Math.max(this.getTotalStepTimeLeftToPlay(e),n),o}setStepPhaseTime(e){let t=Date.now(),s=t-this.lastUpdateTime;this.lastUpdateTime=t,this.currentRetryTimesReport[e]=s}reportGetTabTime(){this.setStepPhaseTime("tab")}reportGetFrameTime(){this.setStepPhaseTime("frame")}reportCalcConditionTime(){this.setStepPhaseTime("condition")}reportPreLocateActionsTime(){this.setStepPhaseTime("pre-locate")}reportFindElementsTime(){this.setStepPhaseTime("locate")}reportStepActionTime(){this.setStepPhaseTime("action")}}});var Ku={};W(Ku,{SeleniumTestPlayer:()=>Un});var Un,la=T(()=>{"use strict";U();Cn();Pu();Mg();Ou();Lu();jg();Du();Ee();As();Vu();Hu();zu();Un=class{constructor(e,t,s,n="code",o=new Nr,i,a){let{sessionPlayer:c,commonConstants:u,stepActionFactory:d}=re();this.driver=o,this.id=e;let p=new Ps(this.driver);this.stepActionFactory=new d(p),ca(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Oi(this.driver),this.driver.tabService=this.tabService,this.windowCreationListener=Fn,this.playbackTimeoutCalculator=new Ls(Di()),this.tabService.createSesion(e);let m=Ug(this.driver);this.sessionPlayer=new c(e,this.tabService,new Rs(this.driver),Fn,m,Li,null,null,p,this.stepActionFactory,this.playbackTimeoutCalculator,Qe.getSocket(),n),this.sessionPlayer.setShouldMonitorPerformance&&this.sessionPlayer.setShouldMonitorPerformance(s),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(u.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>{})}onDone(){let{commonConstants:e}=re(),t=1e3*60*2;return te(this.driver.end(),t).catch(s=>{if(s instanceof Y)return this.driver.forceEnd().catch(()=>null)}).then(()=>{this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),this.sessionPlayer=null,this.tabService=null,this.stepActionFactory=null,this.driver=null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},s=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(s);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var ry={};W(ry,{buildCodeTests:()=>Ju});async function eS(r,e,t,s,n){try{return await ey(r,e,t,s,n)}catch(o){if((o==null?void 0:o.code)==="ENOENT")return lr.compiler=null,lr.webpackConfig=null,s&&(s.data={}),await ey(r,e,t,s,n);throw o}}async function ey(r,e={mode:"development"},t=void 0,s=void 0,n=void 0){let o=await ge("webpack"),i=ur.cloneDeep(e);e.externals={testim:"__testim"},e.devtool||(e.devtool="inline-source-map"),e.plugins||(e.plugins=[]),e.plugins.push(new o.DefinePlugin(tS(t)),new o.DefinePlugin({"process.argv":JSON.stringify(process.argv)})),r=r.map(f=>ua.resolve(f));let a=r.map(()=>z(30));if(e.optimization={minimize:!1},Number(process.versions.node.split(".")[0])>=17){let f=require("crypto"),h=f.createHash;f.createHash=(y,b)=>h(y==="md4"?"sha256":y,b)}e.entry=Object.fromEntries(ur.zip(r,a).map(([f,h])=>[h,f])),e.output=Object.assign({devtoolModuleFilenameTemplate:f=>`file:///${f.absoluteResourcePath}`,filename:"[name].bundle.js"},e.output);let u;s?(ur.isEqual(lr.webpackConfig,i)&&lr.compiler||(lr.webpackConfig=i,lr.compiler=o(e)),u=lr.compiler):u=o(e);let d=s||new ty.default;u.outputFileSystem=d;let p=pt(f=>{n==null||n.addEventListener("abort",()=>{f(new Be,void 0)})});try{let f=await Promise.race([pt(h=>u.run(h)),p]);if(f!=null&&f.hasErrors()){let{errors:h}=f.toJson(),y=h.map(b=>`
|
|
560
|
+
${typeof b=="string"?b:b.message||"Unknown error"}`).join("");throw new Error(y)}}catch(f){let h=f.message.match(/Entry module not found: Error: Can't resolve '(.*)'/);throw h&&h.length===2?e.output&&e.output.library==="tdk"?new P(`Could not open dev-kit functions file in ${h[1]}`):new P(`Can't find test files in: '${h[1]}'`):new P(`Compilation Webpack Error in tests: ${f.message}`)}return{tests:[r.map((f,h)=>({code:d.readFileSync(ua.resolve("./dist",`${a[h]}.bundle.js`)),name:f})).map(({code:f,name:h})=>({code:f.toString(),baseUrl:"",name:ua.resolve(h),testConfig:{},testConfigId:null,testId:z(),resultId:z(),isTestsContainer:!0}))],runName:`Testim Dev Kit Run ${new Date().toLocaleString()}`}}function tS(r){let e=ur.fromPairs(Object.keys(process.env).filter(s=>/^TDK_/i.test(s)||s==="BASE_URL").map(s=>[s,process.env[s]])),t={BASE_URL:r==null?void 0:r.baseUrl};return{"process.env":rS({...t,...e})}}function rS(r){return Object.fromEntries(Object.entries(r).map(([e,t])=>[e,JSON.stringify(t)]))}var ur,ua,ty,lr,Ju,Yu=T(()=>{"use strict";ur=E(require("lodash")),ua=E(require("path"));U();ty=E(require("memory-fs"));q();yt();lr={compiler:null,webpackConfig:null};Ju=eS});var oy={};W(oy,{compileFunctionsLibrary:()=>td,findTestFolder:()=>Br,findTests:()=>Xu,getLocalLocatorContents:()=>Qu,getLocalLocators:()=>jn,saveLocators:()=>ed,saveTest:()=>Zu});async function jn(){let r=await Br(process.cwd()),e=Ze.join(r,"locators","locators.js");function t(n){let o=n.toString().replace("module.exports =","return").replace(/require/g,"(x => /locator.(.*).json/.exec(x)[1])");return new Function(o)()}let s=await it.promises.readFile(e).then(t,()=>({}));return Object.fromEntries(Object.keys(s).map(n=>[n.replace(/"/g,'\\"'),s[n]]))}async function Xu(r=process.cwd()){let e=await Br(r),t=await it.promises.readdir(e,{withFileTypes:!0}),s=["webpack.config.js","tsconfig.js",".DS_Store","functions.js"],n=[".html",".json"];return t.filter(o=>!s.includes(o.name)&&!n.some(i=>o.name.endsWith(i))&&o.isFile()&&!o.name.startsWith(".")).map(o=>o.name)}async function sS(r){let e=Object.entries(r),t=e.map(([,n])=>n),s=await Promise.all(t);for(let n=0;n<s.length;n++)e[n][1]=s[n];return Object.fromEntries(e)}async function Qu(r,e=!1,t=process.cwd()){let s={};if(e){let n=await Br(t);for(let o of Object.values(r))s[o]=it.promises.readFile(Ze.join(n,"locators",`locator.${o}.json`)).then(JSON.parse)}try{return await sS(s)}catch(n){return console.error(n),{}}}async function Zu({body:r,name:e,locators:t,language:s="javascript"}){let n=await Br(process.cwd()),o=Ze.join(n,"locators","locators.js"),i=Ze.join(n,e);if(!i.startsWith(n))throw new Error("A test name must be a valid file name and inside the tests directory");if(s==="javascript"?i.endsWith(".js")&&!i.endsWith(".test.js")?i=`${i.substr(0,i.length-3)}.test.js`:i.endsWith(".test.js")||(i+=".test.js"):i.endsWith(".ts")&&!i.endsWith(".test.ts")?i=`${i.substr(0,i.length-3)}.test.ts`:i.endsWith(".test.ts")||(i=`${i}.test.ts`),i.endsWith("locators/locators.js"))throw new Error("Cannot override locators file from the internet as it is evaluated by the runner");await it.promises.writeFile(i,r),await it.promises.mkdir(Ze.join(n,"locators")).catch(()=>{});for(let{id:u,body:d}of t)await it.promises.writeFile(Ze.join(n,"locators",`locator.${u}.json`),JSON.stringify(d));let a=Object.fromEntries(t.map(({name:u,id:d})=>[u,d])),c=await jn();Object.assign(c,a),await ny(o,c)}async function ny(r,e){let t=`module.exports = {
|
|
561
561
|
`;for(let[s,n]of Object.entries(e))t+=` "${s}": require('./locator.${n}.json'),
|
|
562
|
-
`;t+="};",await it.promises.writeFile(r,t)}async function ed(r,{mergeIntoExisting:e}={mergeIntoExisting:!1}){let t=await Br(process.cwd()),s=Ze.join(t,"locators","locators.js");await it.promises.mkdir(Ze.join(t,"locators")).catch(()=>{});for(let{name:o,id:i,elementLocator:a}of r)await it.promises.writeFile(Ze.join(t,"locators",`locator.${i}.json`),JSON.stringify({name:o,id:i,elementLocator:a}));let n=Object.fromEntries(r.map(({name:o,id:i})=>[o,i]));if(e){let o=await jn();Object.assign(n,o)}await ny(s,n)}async function td({fileSystem:r,bypassWebpack:e}={},t=void 0){let s=await Br(process.cwd());if(t!=null&&t.aborted)throw new Be;let n=Ze.join(s,"functions.js");if(e!=null&&e.testim){let i=require("module"),a=i.prototype.require;i.prototype.require=function(u){return u==="testim"?e.testim:a.apply(this,arguments)};try{return delete require.cache[require.resolve(n)],require(n)}finally{i.prototype.require=a}}return(await Ju([n],{output:{libraryTarget:"umd",library:"tdk",globalObject:"globalThis"},cache:{type:"memory"},mode:"development"},{},r,t)).tests[0][0].code}var sy,Ze,it,Br,rd=T(()=>{"use strict";sy=E(require("lodash")),Ze=E(require("path")),it=require("fs");q();Xu();Br=sy.memoize(async r=>(await it.promises.readdir(r)).includes("tests")&&(await it.promises.stat(Ze.join(r,"tests"))).isDirectory()?Ze.join(r,"tests"):r)});var iy={};W(iy,{getArgumentsFromContext:()=>$r});async function $r(r,e,t){let s=nS(r.parameterNames.map(n=>n.displayName),e.incomingParams.as);return await Promise.all(s.map(n=>typeof n=="object"&&n.locatedElement?t(n):n))}function nS(r,e){let t=[];for(let s of r){let n=e.functionParameters.indexOf(s);t.push(e.functionArguments[n])}return t}var Bn=T(()=>{"use strict"});var cy={};W(cy,{execute:()=>aS});async function cS(r,e,t,s,n,o){var a;let i;try{let{WebDriver:c}=await oS("selenium-webdriver");if(o.aborted)throw new ay;let{Executor:u,HttpClient:d}=require("selenium-webdriver/http"),p=r.driver.client.options,m=p.path,f=`${p.protocol}://${p.hostname}:${p.port}`+m,g=new d(f),y=new c(r.getSessionId(),new u(g));await lS(y,r.driver);let x=await iS(t,s,v=>y.findElement({css:v.selector})),w=e.bind(null,y,...x);return i=function(){g.send=async function(){throw new ay}},o.addEventListener("abort",i),await w(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}async function lS(r,e){if(e.cdpUrl){let t=await r.getAllWindowHandles();for(let s of t)if(await r.switchTo().window(s),await r.executeScript("return window.__isMainTestimTab"))break}}var ay,oS,iS,aS,ly=T(()=>{"use strict";({AbortError:ay}=(q(),ie(np))),{lazyRequire:oS}=(yt(),ie(_l)),{getArgumentsFromContext:iS}=(Bn(),ie(iy)),aS=cS});var uy={};W(uy,{execute:()=>uS});async function dS(r,e,t,s,n,o){var a;let i;try{let c=await he("puppeteer");if(o.aborted)throw new Be;let u=await c.connect({browserWSEndpoint:r.driver.cdpUrl,defaultViewport:null,product:"chrome"});if(o.aborted)throw u.disconnect(),new Be;i=function(){u.disconnect()},o.addEventListener("abort",i);let d=await u.pages(),p;for(let y of d)if(await y.evaluate(()=>window.__isMainTestimTab)){p=y;break}let m=p||d.at(-1),f=await $r(t,s,y=>m.$(y.selector));return await e.bind(null,m,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{o.removeEventListener("abort",i)}}var uS,dy=T(()=>{"use strict";q();yt();Bn();uS=dS});var py={};W(py,{execute:()=>pS});async function mS(r,e,t,s,n,o){var a;let i;try{let c=await he("playwright");if(o.aborted)throw new Be;let u=await c.chromium.connect({wsEndpoint:r.driver.cdpUrl});if(o.aborted)throw u.disconnect(),new Be;i=function(){u.disconnect()},o.addEventListener("abort",i);let m=(await(await u.newContext({viewport:null})).pages()).at(-1),f=await $r(t,s,y=>m.$(y.selector));return await e.bind(null,m,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}var pS,my=T(()=>{"use strict";q();yt();Bn();pS=mS});var hy={};W(hy,{execute:()=>fS});async function hS(r,e,t,s,n,o,i,a){function c(){r.sessionPlayer.stopPlaying()}a.addEventListener("abort",c);function u(A){if(o.parameterValues){let D=o.parameterValues.find(B=>B.type==="locate"&&B.id===A.locatorId);return{elementLocator:D.elementLocator,id:D.id,name:"Hybrid Step Locator"}}return A.locatedElement.shadowPath?A.locatedElement.shadowPath[0]:A}let d=await $r(o,t,u),p=e.bind(null,...d),m=z(),h=z(),f=t.testResultId,g=t.config.baseUrl,y=fy.cloneDeep(t);y.loginData=s;let x=re().manifestVersion||"runner",w=!1,v=null,R="master",k=`Execute TDK Function '${o.functionName}'`,L=!0,S={fn:p,bypassSetup:!0,isBeforeOrAfterTest:!0,name:k,sourceCode:p.toString(),sourceName:p.name,testId:m,resultId:z()},O=typeof e.results=="boolean"&&!e.results;try{_("tdkHybridStepPlayback before addAllTabs"),n?(r.sessionPlayer.playbackAutUtils.frameManager=n,r.sessionPlayer.frameManager=n):await r.addAllTabs(null,{loadInfo:!0,checkForMainTab:!0,takeScreenshots:!O},[r.driver.initialUrl]),r.sessionPlayer.playbackManager.dontAssociateChildResult=!0,r.sessionPlayer.playbackManager.onlyLocalReporting=O,_("tdkHybridStepPlayback before playTestByCode");let A=await new Promise((D,B)=>{i==="agent"&&gS(r,D);function V(){B(new Be),a.removeEventListener("abort",V)}a.addEventListener("abort",V),r.sessionPlayer.playTestByCode(m,h,f,g,y,x,D,w,v,R,[S],k,L).catch(B)});return _("tdkHybridStepPlayback after playTestByCode"),{success:A.success,shouldRetry:!1,resultInfo:{testId:m,executionId:h,resultId:S.resultId}}}catch(A){return{success:!1,error:A,shouldRetry:!1}}finally{a.removeEventListener("abort",c)}}function gS(r,e){let{commonConstants:t}=re();r.sessionPlayer.playbackManager.on(t.playback.START,({testResult:s})=>{let n=s.runnerStatus;Object.defineProperty(s,"runnerStatus",{get(){return n},set(o){n=o,o==="FINISHED"&&e(s)}})})}var fy,fS,gy=T(()=>{"use strict";fy=E(require("lodash"));Oe();U();q();Bn();Ee();fS=hS});var da={};W(da,{abort:()=>od,execute:()=>ks,run:()=>wS});async function ks(r,e,t,s,n,o="cli"){let i=new by.AbortController,{signal:a}=i;nd.set(e.stepResultId,i);try{_("before seleniumTestPlayer require");let{SeleniumTestPlayer:c}=(la(),ie(Ku)),{compileFunctionsLibrary:u}=(rd(),ie(oy)),{functionName:d}=r,p={},m=!1,h=new c(e.id,p,m,Nt.CODEFUL,t);sd=h.sessionPlayer.codeSessionPlayer.proxy;let f=r.bypassWebpack?{testim:sd.wrappedSteps()}:!1;_("before compileFunctionsLibrary",{bypassWebpack:Boolean(r.bypassWebpack)});let g;try{g=await u({fileSystem:yS,bypassWebpack:f},a)}catch(b){return{success:!1,shouldRetry:!1,reason:`Unable to compile functions library. ${b.message}`,extraInfo:b.stack}}typeof globalThis>"u"&&(global.globalThis=process);let y;if(f?y=g[d]:(global.globalThis.__testim=sd.wrappedSteps(),(0,eval)(g),y=globalThis.tdk[d]),_("after hybridFunction obtain and eval"),!y)return{success:!1,shouldRetry:!1,reason:`Could not find function '${d}' locally. Please make sure you have a functions.js file with a '${d}' function defined`,extraInfo:Object.keys(globalThis.tdk)};if(y.type==="selenium"){let b=(ly(),ie(cy)).execute;return await b(h,y,r,e,o,a)}if(y.type==="puppeteer"){if(!h.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running puppeteer code requires the remote debugging protocol to be open. Please contact Testim support."};_("before puppeteerPlayback");let b=(dy(),ie(uy)).execute;try{return await b(h,y,r,e,o,a)}finally{_("after puppeteerPlayback")}}if(y.type==="playwright"){if(!h.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running playwright code requires the remote debugging protocol to be open. Please contact Testim support."};let b=(my(),ie(py)).execute;return await b(h,y,r,e,o,a)}if(y.type==="tdk"||!y.type){let b=(gy(),ie(hy)).execute;_("before tdkPlayback");try{return await b(h,y,e,s,n,r,o,a)}finally{_("after tdkPlayback")}}return{success:!1,shouldRetry:!1,reason:`unknown hybrid format ${y.type}`}}catch(c){bS.info("error running hybrid step",{err:c});return}finally{nd.delete(e.stepResultId)}}function od(r){let e=nd.get(r);if(e)e.abort();else throw new Error("No such stepResultId")}var yy,by,yS,bS,nd,sd,wS,na=T(()=>{"use strict";yy=E(require("memory-fs"));Oe();by=require("abort-controller");j();ae();yS=new yy.default,bS=I("hybrid-step-playback"),nd=new Map,wS=(r,e,t,s)=>{let{step:n,context:o}=e.data;return ks(n,o,r,s.loginData)}});var id={};W(id,{run:()=>TS});var TS,wy=T(()=>{"use strict";U();Fr();q();TS=async(r,e)=>{let{stepId:t,testResultId:s,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await vs(t,s,n,i,o,a),success:!0}}catch(c){if(c instanceof dt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof X)return{success:!1,code:"timeout"};throw c}}});async function vy(r,e,t,s){try{return await nl(r,e,t,s)}catch{pa.error("failed to report remote step state",{projectId:r,resultId:e,stepId:t});return}}async function ES(r,e,t,s,n){return pa.info("finished to run remote step",{stepId:t,sessionId:n}),await vy(r,e,t,{status:"completed",success:!0,failureReason:null,data:s})}async function Ty(r,e,t,s,n){return pa.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:s}),await vy(r,e,t,{status:"completed",success:!1,failureReason:s})}async function Ey(r,e,t,s){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o,userData:i}=r,a=t.type,c=e.getSessionId(),u=t.id;pa.info("start play remote step",{stepType:a,stepId:u,sessionId:c});let d=vS[a];if(!d)return await Ty(n,s,u,`Failed to find step type ${a}`,c);try{let p=await d.run(e,t,o,i);return await ES(n,s,u,p,c)}catch(p){return await Ty(n,s,u,p.message,c)}}var pa,vS,Sy=T(()=>{"use strict";Ah();na();Te();wy();j();pa=I("step-playback"),vS={"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":id,"tdk-hybrid":da}});var Ry={};W(Ry,{remoteStepServiceSocketIO:()=>RS});var ad,RS,Iy=T(()=>{"use strict";Mi();ad=class extends or{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,s){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&s(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},RS=new ad});var xy={};W(xy,{remoteStepService:()=>Ns});var cd,$n,ld,Ns,ma=T(()=>{"use strict";_n();ae();ye();({REMOTE_STEP_SAVED:cd}=rt),ld=class{async init(e){M.flags.useNewWSCLI.isEnabled()||($n=(await Promise.resolve().then(()=>(Iy(),Ry))).remoteStepServiceSocketIO,$n.init(e))}joinToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?We.addFilter(`${e}:remoteStep`,{resultId:e},[cd]):$n.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(M.flags.useNewWSCLI.isEnabled()){We.listenTo(`${e}:remoteStep`,[cd],s=>s.resultId===e&&s.remoteStep&&s.remoteStep.status==="pending",s=>t(s.remoteStep));return}$n.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?(We.removeFilter(`${e}:remoteStep`,[cd]),Promise.resolve()):$n.unlistenToRemoteStep(e)}},Ns=new ld});var Ay,Cy,ky,Se,IS,_y,Py,fa,Oy=T(()=>{"use strict";Ay=E(require("lodash"));U();le();Oe();ds();It();Te();Sy();Cy=E(require("p-retry")),ky=require("url");j();Jo();ys();ae();ma();As();ye();Se=I("test-run-handler"),IS=3,_y=20*1e3,Py=r=>JSON.stringify(r).length<_y,fa=class{constructor(e,t,s,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new $t;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.clearTestResultFinished=Promise.resolve(void 0);var c,u;this._testStatus=s.testStatus,this._testId=s.testId,this._testName=s.name,this._testResultId=s.resultId,this._code=s.code,this._baseUrl=n.baseUrl||s.baseUrl||s.testConfig.baseUrl,this._nativeApp=s.nativeApp,this._overrideTestConfigId=(c=s.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((u=s.runConfig)!=null&&u.isMobileWeb)&&n.browser;this._runConfig=a?tn(n.browser,n.saucelabs,n.browserstack):s.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get automationMode(){return this._code?"codeful":"codeless"}get code(){return this._code}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}get androidActivityWait(){var n;let e=this._nativeApp&&"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if((n=e==null?void 0:e.activity)!=null&&n.includes(e.id))return`${e.id}.*`;let{activity:t}=e;if(!t)return null;let s=t.split(".").pop();return t.replace(s,"*")}get isFFAllowAppFromDeviceEnabled(){return M.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return Ys(this._nativeApp)}get isAppForIosVirtualDevice(){return es(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?uo.FROM_DEVICE:uo.FROM_LIBRARY}get nativeAppLink(){let e=null;return this._nativeApp&&"filePath"in this._nativeApp&&(e=`${ge}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`),e}async getNativeAppData(){let{appId:e,baseUrl:t}=this._options;if(t&&!this._nativeApp&&!e){let s=t||this.baseUrl;if(!s)return null;let[n,o]=s.split(":");return{packageName:n,activity:o}}return this._nativeApp&&!e?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var s,n;let t={tokenV3:await Kt(),refreshToken:Oo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Jd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this.code&&{isCodeMode:!0,testName:this.testName},...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&&ht("user-disable-mock"),t.lightweightMode&&((s=this._options.lightweightMode)!=null&&s.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Py(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),Se.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${_y} 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 wn(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 Se.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.runMode===J.EXTENSION&&{code:this.code},...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Py(e))return;let s=async()=>{try{return await ol(this._options.project,this._testId,this._testResultId,e)}catch(i){return Se.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await s();return await this._testRunStatus.waitForExecutionStartedFinished(),sl(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}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){_("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},{targetId:s}=t.find(o=>o.type==="background_page"&&o.title==="Testim Editor")||{},{targetId:n}=t.find(o=>o.type==="page")||{};if(!s)throw new Error("testim extension not found");if(!n)throw new Error("AUT target not found");try{_("before Target.attachToTarget");let[o,i]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:s,flatten:!0}),this.getRunRequestParams()]),{sessionId:a}=o||{};_("before Runtime.evaluate"),await(0,Cy.default)(async()=>{let{result:u}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},a);if(!u.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),_("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(i)})`,awaitPromise:!0,returnByValue:!0},a);if(c.subtype==="error")throw new Error(c.description);return _("after Runtime.evaluate"),c.value}catch(o){throw Se.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let s;try{s=new ky.URL(e)}catch{return}let{username:n,password:o}=s;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let s=!1,n=o=>{if(!s){if(this.isRetryKeyMismatch(o)){Se.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"&&(Se.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),s=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:u,_options:{project:d}}=this;try{let p=await Cr(a,c,d,u);n(p),s||setTimeout(i,3e3)}catch(p){Se.error("failed to check if done",{err:p}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Qe.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:s},branch:n}=this;try{let o=await Cr(e,t,s,n),i=["running","completed"];if(i.includes(o.status))return Se.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw Se.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error($e.TEST_START_TIMEOUT_MSG)}catch(o){throw Se.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error($e.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Qe.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(s=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),s(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Qe.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){Se.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,s(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Ay.debounce(async()=>{try{let i=await Cr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(Se.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"?(Se.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,s(i),!0):!1}catch(i){return Se.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Qe.on("socket-connected",e);else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await zc(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){Se.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Qe.off("socket-connected",e)}}listenToRemoteStep(e){Ns.listenToRemoteStep(this.testResultId,t=>{Ey(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:IS;return this._timeoutRetryCount<e}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,s;return Boolean((s=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:s.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||(this._originalTestResultId=this._previousTestResultId),this._testResultId=z(),!((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 ha,Ly=T(()=>{"use strict";Oy();ha=class{constructor(e,t,s,n,o,i){this._waitingTests=s.map(a=>new fa(e,t,a,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var xS,PS,Wn,ud=T(()=>{"use strict";hs();j();xS=I("worker-utils"),PS=async(r,e,t)=>{e&&await Gl(r,t)},Wn=async(r,e,t,s)=>{xS.info("releasing player",{hasPlayer:Boolean(s)});try{await(s==null?void 0:s.onDone())}finally{await PS(r,e,t)}}});function LS(r,e,t,s){return{testId:r,reason:s,name:e,resultId:t,success:!1}}var md,Fy,pd,At,Ny,Dy,My,Gn,AS,dd,CS,Gt,kS,ga,_S,OS,Ct,ya=T(()=>{"use strict";md=E(require("ms")),Fy=E(require("moment")),pd=E(require("p-retry"));U();Oe();hs();Te();j();ud();Bt();ti();ye();ma();As();Rt();ae();q();At=I("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Ny,TEST_START_TIMEOUT_MSG:Dy,TEST_COMPLETE_TIMEOUT_MSG:My}=$e,{SETUP_TIMEOUT:Gn,NETWORK_ERROR:AS,GRID_ERROR:dd,BROWSER_CLOSED:CS,SELENIUM_ERROR:Gt,UNKNOWN_ERROR:kS,MOBILE_SESSION_ERROR:ga}=Ks,_S=(0,md.default)("1s"),OS=1;Ct=class{constructor(e,t,s,n,o,i,a,c,u=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=s;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=u;this.id=Ct.getWorkerId();this.lambdatestService=new ee;this.isCodeMode=t.files&&t.files.length>0,this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return OS++}async getGridSlot(e,t){let s=await Sf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,s),s}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Yr(!0)}async getBrowserOnce(e,t,s,n){throw new Yr(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),At.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){let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice,s=e.isAppForIosVirtualDevice;if(t||s){let n={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:s}};return this.onTestIgnored(this.id,n),n}}setSessionTimeout(){return this.options.mode===J.APPIUM?Math.max((0,md.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let s=(o=this.userData)==null?void 0:o.projectId,n;try{_("before getSlotOnce retries");let i=0,a=await(0,pd.default)(async()=>{let d=Date.now();try{return await te(this.getSlotOnce(e),this.options.getBrowserTimeout,$e.GET_BROWSER_TIMEOUT_MSG)}catch(p){let m={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw p instanceof hr?At.info("could not get grid slot due to concurrency issue",m):At.error("error getting grid slot",{error:p,...m}),i++,await se(this.options.getBrowserTimeout-(Date.now()-d)),p}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});_("after getSlotOnce retries"),_("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let u=0;n=await(0,pd.default)(async()=>{let d=Date.now(),p=this.initPlayer(e);try{a=await Rf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:u+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=u;let m=this.setSessionTimeout();_("before getBrowserOnce");let h=await te(this.getBrowserOnce(e,t,p,a),m,$e.GET_BROWSER_TIMEOUT_MSG);return _("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,s),p||h}catch(m){let h={provider:a.provider,host:a.host,failedGetBrowserAttempts:u,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===J.APPIUM?"device":"browser";throw At.error(`error getting ${f} from grid`,{error:m,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:h}),Q.onGetBrowserFailure(this.id,s,++u),p.onDone(),!(m instanceof lt)&&this.options.mode!==J.APPIUM&&await se(this.options.getBrowserTimeout-(Date.now()-d)),m}},{retries:c-1,minTimeout:0,factor:1}),_("after getBrowserOnce retries")}catch(i){throw await Wn(this.id,this.releaseSlotOnTestFinished,s,n),i instanceof lt?i:i instanceof ut?new Vt(i,dd):new Vt(i,Gt)}return n}async runTest(e,t,s){var d;_("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Qs(this.options)&&this.handleMobileTest(e);if(i)return i;_("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey,a);e.baseUrl=c.config.baseUrl;let u=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,u)}finally{await Wn(this.id,this.releaseSlotOnTestFinished,n,u)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var m,h;let e=()=>process.nextTick(()=>this.run()),t=async(f,g,y)=>{var k;if(Je(f,this.options)||!g.isFFAllowAppFromDeviceEnabled&&g.isAppFromDevice||g.isAppForIosVirtualDevice)return e();let b=g.sessionId,x=L=>y==null?void 0:y.message.includes(L),w=y&&y instanceof Vt,v=y&&(x(Dy)||x(My)),R=!f.success&&(g.hasMoreRetries()&&!w&&!v||v&&g.hasMoreTimeoutRetries());try{let L=g.retryKey;f.testRetryKey=L;let S=g.getAppSource;return await this.onTestCompleted(this.id,this.testId,f,b,R,S),this.executionQueue.hasMoreTests()&&!((k=this.options.lightweightMode)!=null&&k.general)&&await se(_S),await this.runTestCleanup(),R?(v?await g.startNewTimeoutRetry():await g.startNewRetry(),At.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:L,totalRetries:g._totalRetryCount}),this.testResultId=g.testResultId,await d(g,R)):await e()}catch(L){if(L instanceof _t)return;At.error("failed to process test result",{error:L}),e();return}},s=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
563
|
-
Please make sure the CLI has stable access to the internet. ${ic()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:g,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:b}=mc,x=f instanceof Error?f.message:f;return x.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),x.includes(Ny)?{errorType:Gn,reason:"Test couldn't get device, time"}:x.includes(y)?{errorType:ga,reason:"app doesn't exist on device"}:x.includes(b)?{ErrorType:ga,reason:"app never started, check app permission or app activity"}:x.includes(g)?{ErrorType:ga,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:ga,reason:x}},o=(f,g)=>{let y=this.options.mode===J.APPIUM?"device":"browser";if(!g&&M.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:AS,reason:s()};let b=f instanceof Error?f.message:f;if(b.includes(Ny))return{errorType:Gn,reason:`Test couldn't get ${y}`};if(b.includes(Dy))return{errorType:Gn,reason:"Test couldn't be started"};if(b.includes(My)){if(!this.testRunTimeout)return{errorType:Gn,reason:"Test timeout reached: test is too long"};let x=Fy.default.duration(this.testRunTimeout,"milliseconds"),w=Math.floor(x.asMinutes()),v=x.seconds(),R=w>0?` ${w} min`:"",k=v>0?` ${v} sec`:"";return{errorType:Gn,reason:`Test timeout reached (timeout:${R}${k}): test is too long`}}if(f instanceof Vt&&f.type){if(f.type===dd)return{errorType:dd,reason:`Test couldn't get ${y} from grid - ${f.message}`};if(f.type===Gt)return{errorType:Gt,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===CS?{errorType:Gt,reason:"Session terminated, it is possible that the cli could not connect to the grid to send keep-alive requests for a prolonged period"}:"failure"in f&&f.failure instanceof fr?{errorType:Gt,reason:`Test couldn't get ${y} from grid - ${f.failure.message}`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:Gt,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(f.message)?{errorType:Gt,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(f.message)?{errorType:Gt,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(f.message)?{errorType:Gt,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:kS,reason:b}},i=async(f,g)=>{var v;let y=await oc();!y&&M.flags.warnOnBadNetwork.isEnabled()&&console.warn(s()),At.warn("error on run",{err:f});let b=(v=this.userData)==null?void 0:v.projectId,{errorType:x,reason:w}=this.options.mode===J.APPIUM?n(f):o(f,y);rl(b,this.testResultId,this.testId,{status:zs.COMPLETED,success:!1,reason:w,errorType:x,testRetryKey:g.retryKey,setupStepResult:{status:zs.COMPLETED,success:!1,reason:w,errorType:x}},g.remoteRunId),await t(LS(this.testId,this.testName,this.testResultId,w),g,f)},a=async(f,g)=>{var v;let y=this.testId,b=this.testResultId,x=(v=this.userData)==null?void 0:v.projectId,w=this.branch;if(!y||!b||!x||!w)return At.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,g);try{let R=await Cr(y,b,x,w);if(At.warn("Test failed. Got results via API",{err:f,testResult:R}),R&&R.status===zs.COMPLETED)return await t(R,g);throw f}catch(R){return R!==f&&At.error("Failed to fetch test results from server",{testId:y,resultId:b,projectId:x,branch:w,err:R}),i(f,g)}},c=this.options.disableSockets||((m=this.options.lightweightMode)==null?void 0:m.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),u=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),d=async(f,g)=>{try{await Promise.all([!u&&Ns.joinToRemoteStep(this.testResultId),!c&&Qe.joinToTestResult(this.testResultId,this.testId)]),f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,g),b=await t(y,f);return _("After onRunComplete"),b}catch(y){return a(y,f)}finally{u||Ns.unlistenToRemoteStep(this.testResultId)}},p=this.executionQueue.getNext();return p?(this.testId=p.testId,this.testName=p.testName,this.testResultId=p.testResultId,this.overrideTestConfigId=p.overrideTestConfigId,this.testRunConfig=p.runConfig,this.branch=p.branch,d(p)):this.onQueueCompleted()}}});var Uy={};W(Uy,{WorkerSelenium:()=>fd});function DS(r){let{playback:e}=re().commonConstants;function t(s){r.playbackManager.on(s,()=>{_(`Got event ${s}`)})}Object.values(e).forEach(t)}var ba,NS,fd,jy=T(()=>{"use strict";U();Oe();ya();j();Bt();q();Jo();ae();Cu();la();Ee();ba=I("worker-selenium"),NS=1e9,fd=class extends Ct{initPlayer(t){return new Un(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){_("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new Is(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let u=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,s,this.executionId,this.testResultId,t.seleniumPerfStats,u,this.lambdatestService),_("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:u}),_("in WorkerSelenium after addTab"),u||await this.windowUtils.navigate(c,NS),await this.windowUtils.validatePageIsAvailable(),_("in WorkerSelenium after navigate")}catch(u){let d=u.message&&(u.message.startsWith("Malformed URL")||u.message.includes("Reached error page: about:neterror"))&&a==="firefox",p=u.message&&u.message==="invalid argument";throw u instanceof lt||d||p?new lt(`Page '${c}' is not available`):(ba.error("failed to navigate to page",{baseUrl:c,err:u}),u)}}async runTestOnce(t,s){var d;let n=re(),{driver:o,sessionPlayer:i}=s,a=n.manifestVersion||"runner";Q.onWaitToTestComplete(this.id,this.isCodeMode),DS(i),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&i.setSfdcCredential(t.sfdcCredential),n.localAssetService&&n.localAssetService.initialize({serverUrl:this.options.localRCASaver});let c=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(c=(await wn(this.options))[this.testId]);let u=async()=>{if(t.automationMode==="codeful"){i.callOrderScheduler?i.callOrderScheduler.schedule(()=>t.waitForExecutionStartedFinished(),{key:`test-result:${this.userData.projectId}:${this.testResultId}`}):await t.waitForExecutionStartedFinished(),_("right before playTestByCode");let m=new Promise((h,f)=>{i.playTestByCode(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,h,!1,this.overrideTestConfigId,this.branch,t.code,t.testName).catch(f)});return te(m.then(h=>(_("right after playTestByCode"),h)),this.testRunTimeout,$e.TEST_COMPLETE_TIMEOUT_MSG).catch(h=>{var f;throw h instanceof X&&((f=i.stopPlayingOnTestTimeout)==null||f.call(i)),h}).then(h=>(h.resultId=this.testResultId,h))}let p=!1;return te(new Promise((m,h)=>{i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,m,!1,this.overrideTestConfigId,this.branch,p,t.remoteRunId,void 0,void 0,c).catch(h)}),this.testRunTimeout,$e.TEST_COMPLETE_TIMEOUT_MSG).catch(m=>{var h;throw m instanceof X&&((h=i.stopPlayingOnTestTimeout)==null||h.call(i)),m}).then(async m=>{n.localAssetService&&await n.localAssetService.drain(),m.stepsResults=null,m.resultId=this.testResultId,o.isAlive()||(ba.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.gridIssues="could not validate grid is alive");let h=o.maxKeepAliveGap();h>=3e4&&(ba.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.keepAliveIssue=h);let g={...m,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g})};o.start(),_("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,s),_("right after super.runTestOnce in workerSelenium");let p=await u();return _("right after runSeleniumTest"),p}catch(p){throw ba.error("failed to run test once",{err:p}),p}}}});var wa,By=T(()=>{"use strict";wa=class{constructor(e){this.driver=e,this._utils={},this.sessionTabs={},this.pendingTabs={},this.addedTabs={}}on(){}tabCount(e){}getAllOpenTabIds(e){}getActiveTabInfo(e){}getAllTabIds(e){}isSessionTab(e,t){}createSesion(e){}setAddFrameHandlerCallBack(e){}getAllTabInfoStrings(e){}getAllTabInfos(e){}addNewTab(e,t,s,n={}){}addOpenerStepId(e,t,s){}addOpenerStep(e,t,s){}fixMissingMainTab(e){}buildTabInfo(e,t,s,n,o={}){}addTab(e,t,s,n,o={}){}getTabUtilsByTabIdAndSessionId(e,t){}getTabUtilsByTabId(e){}getTabInfo(e,t){}getTabUtils(e,t){}exactUrlMatch(e,t,s){}singleExactMatchForParts(e,t,s,n){}isSameTab(e,t,s){}getMainTabInfo(e){}getMainTabUtils(e){return{}}removeTabInfo(e,t){}getMainTabId(e){}isMainTabExists(e){}clearAllTabs(e){}clearNonMainTabs(e){}switchTab(e,t,{forceSwitch:s}={forceSwitch:!1}){}getTabDetails(e,t,s={}){}getUnregisteredTabId(e){}waitForTabToOpen(e){}tryToAddTab(e,t){}addNewPopup(e,t){}waitToPendingTabs(e,t){}isMainTabIncognito(){}isInvalidStepVersion(e){}getTabIdByTabInfo(e,t){}}});function $y(r){class e{constructor(s,n){this.frameManager=s,this.locateElementPlayer=n}foundFrameCallback(s,n,o){return hd.info("foundFrameCallback-mock invoked"),{}}locate(s,n,o,i,a,c){return hd.info("locate-mock invoked"),{}}findFrame(s,n,o,i){return hd.info("findFrame-mock invoked"),{}}}return e}var hd,Wy=T(()=>{"use strict";j();hd=I("mobile-frame-locator-mock")});var MS,FS,Ta,Gy=T(()=>{"use strict";MS=E(require("webdriverio"));By();Ou();j();Lu();Nu();Ee();As();Vu();Wy();Hu();zu();FS=I("appium-test-player"),Ta=class{constructor(e,t,s,n="code",o=MS,i,a){let{sessionPlayer:c,commonConstants:u,stepActionFactory:d,MobileLocateElementPlayer:p}=re();this.driver=o,this.id=e;let m=new Ps(this.driver);this.stepActionFactory=new d(m),ca(this.driver,this.stepActionFactory),this.tabService=new wa(this.driver),this.windowCreationListener=Fn,this.playbackTimeoutCalculator=new Ls(Ni()),this.tabService.createSesion(e);let h=$y(this.driver);this.sessionPlayer=new c(e,this.tabService,null,null,h,Li,p,null,m,this.stepActionFactory,this.playbackTimeoutCalculator,Qe.getSocket(),n),this.sessionPlayer.setShouldMonitorPerformance&&this.sessionPlayer.setShouldMonitorPerformance(s),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(u.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){}async onDone(){try{await this.driver.activeSession.deleteSession()}catch(e){FS.error("error while deleting appium session",{error:e})}finally{let{commonConstants:e}=re();this.sessionPlayer.playbackManager.off(e.playback.RESULT),this.sessionPlayer=null,this.tabService=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){return this.driver.activeSession.sessionId}}});var qy={};W(qy,{WorkerAppium:()=>gd});var Vy,Vn,gd,Hy=T(()=>{"use strict";Vy=E(require("jsdom"));le();Te();Ei();ya();j();Bt();Gy();Ee();Vn=I("worker-appium"),gd=class extends Ct{initPlayer(e){return new Ta(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){Q.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=s,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,u=e.nativeAppLink;if(this.options.appId){let{project:d,appId:p}=this.options,m=await qc({appId:p,projectId:d});if(!m)throw Vn.error("mobile app not found",{appId:p,projectId:d}),new Error("mobile app not found");u=`${ge}/storage${m.filePath}?access_token=${this.options.authData.token}`}try{let d=[{executionId:this.executionId},{testResultId:this.testResultId}],p=uh({projectType:i,gridInfo:n,testRunConfig:this.testRunConfig,nativeApp:a,options:this.options,appPath:u,androidActivityWait:c,sessionTags:d}),m=await o.remote(p);Object.assign(o,{activeSession:m}),await this.updateDeviceInfo(e,m),Vn.info(`init new appium session testName: ${this.testName}`,{sessionId:m.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(d){throw Vn.error("failed to start application",{err:d}),d}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:s}=this.options.gridData;return`https://${e}:${t}/v0/${s}/wd/hub`}async updateDeviceInfo(e,t){var h;let{executionId:s,testId:n,testResultId:o}=e,{project:i,projectData:{type:a}={},company:{companyId:c=""}={},gridData:{gridId:u=""}={}}=this.options,d=await pl({projectId:i,projectType:a,companyId:c,gridId:u,selectors:`device_id:${t.capabilities.udid}`}),m={name:(h=d==null?void 0:d[0])==null?void 0:h.name,model:t.capabilities.deviceModel,osVersion:t.capabilities.platformVersion,udid:t.capabilities.udid,osType:t.capabilities.platformName,scaleFactor:t.capabilities.pixelRatio,virtual:!1};await cs(i,s,n,o,"RUNNING",{device:m})}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:s,directConnectPort:n,directConnectPath:o}=e;if(t&&s&&n&&o)return`${t}://${s}:${n}${o}`}async runTestOnce(e,t){let s=re(),{sessionPlayer:n}=t,o=t.driver,i=s.manifestVersion||"runner";Q.onWaitToTestComplete(this.id,this.isCodeMode),n.playbackManager.executionId=e.executionId,n.playbackManager.executionName=e.executionName;let a=this.getDirectAddressConnection(o.activeSession.capabilities)||this.getServerAddressFromGrid(),c=new Vy.JSDOM("").window.DOMParser;n.playbackManager.appiumApi=new s.AppiumApi(a,o.activeSession.sessionId,c),s.localAssetService&&s.localAssetService.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let p=await new Promise((h,f)=>n.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,i,h,!1,this.overrideTestConfigId,this.branch,!1,e.remoteRunId,void 0,void 0,void 0).catch(f));return s.localAssetService&&await s.localAssetService.drain(),p.stepsResults=null,p.resultId=this.testResultId,{...p,...e.seleniumPerfStats.getStats()}}catch(d){throw Vn.error("error while running appium tests",{err:d}),d}};try{return await super.runTestOnce(e,t),await u.call(this)}catch(d){throw Vn.error("failed to run test once",{err:d}),d}}}});var va,zy=T(()=>{"use strict";U();Cn();q();va=class{constructor(e){this.driver=new Dr,this.id=e}async onDone(){try{await te(this.driver.end(),12e4)}catch(t){t instanceof X&&await this.driver.forceEnd().catch(()=>{})}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Ky,Ea,Jy=T(()=>{"use strict";Ky=E(require("ws"));U();Ea=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 Ky.default(this._cdpUrl,{timeout:e}),s=pt(o=>{t.once("open",o)}),n=pt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([s,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),s=this._cdpCallbacks.get(t.id);s&&(this._cdpCallbacks.delete(t.id),t.error?s.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?s.reject(new Error(t.result.exceptionDetails.exception.description)):s.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,s){let n=await this.initCDPWebsocket();this._lastWsId||(this._lastWsId=0);let o=this._lastWsId++,i=new Promise((c,u)=>{this._cdpCallbacks.set(o,{resolve:c,reject:u})}),a={method:e,params:t,id:o};return s&&Object.assign(a,{sessionId:s}),n.send(JSON.stringify(a)),i}}});var Ra,yd,Sa,Xy=T(()=>{"use strict";U();Ra=E(require("chrome-launcher"));Ei();Jy();gn();yd=class{constructor(e){this.sessionId=e,this.cdpTestRunner=new Ea}async init(e,t,s,n,o,i,a){var p,m;let c=vi(e,t,s,n,o,i,a),u=[...((p=c.desiredCapabilities)==null?void 0:p.chromeOptions.args)??[],...((m=c.capabilities)==null?void 0:m.alwaysMatch["goog:chromeOptions"].args)??[],...Ra.Launcher.defaultFlags().filter(h=>h!=="--disable-extensions")];this.chrome=await Ra.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let d=await Ir(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(d),ls(()=>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}},Sa=class{constructor(e){this.sessionId=z(),this.driver=new yd(this.sessionId),this.id=e}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Yy={};W(Yy,{WorkerExtension:()=>qn});var wt,qn,bd=T(()=>{"use strict";Oe();q();ya();U();j();Bt();ae();zy();Xy();wt=I("worker-ext"),qn=class extends Ct{initPlayer(){return this.options.useChromeLauncher?new Sa(this.id):new va(this.id)}async _getBrowserOnce(e,t,s,n){var i;let{driver:o}=s;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw wt.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,s,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,s,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async runTestOnce(e,t){let{testResultId:s,executionId:n,testId:o}=this;_("WorkerExtension runTestOnce");let i=async d=>{let p=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await te(e.runTestUsingCDP(d.cdpTestRunner),p,$e.TEST_START_TIMEOUT_MSG)}catch(m){if(!(m instanceof X))throw m;return wt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:s}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,p,m)=>{try{let h=await d.url(p);return m.driverUrlFinished=!0,h}catch(h){throw wt.error("error from driver.url",{err:h,testResultId:s,executionId:n,testId:o,url:p,urlLength:p.length}),h}},c=async d=>{let p=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,p},u=async()=>{var h;if(_("WorkerExtension runExtTest"),((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw wt.warn("failed to run test via CDP",{err:f}),f}}let{driver:p}=t,m={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await te(Promise.all([a(t.driver,f,m),c(m)]),this.options.testStartTimeout,$e.TEST_START_TIMEOUT_MSG)}catch(y){if(!(y instanceof X))throw y;wt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:s,executionId:n,testId:o,...m}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id,this.isCodeMode);let g=y=>{throw e.onCompletedCleanup(),wt.warn("on browser closed error detected",{err:y,testResultId:s,executionId:n,testId:o}),p.unregisterToClosedBrowser(g),y.type=Ks.BROWSER_CLOSED,y};p.registerToClosedBrowser(g);try{let y=await te(e.onCompleted(),this.testRunTimeout,$e.TEST_COMPLETE_TIMEOUT_MSG);p.unregisterToClosedBrowser(g),this.lambdatestService.isLambdatestRun()&&await p.executeJS(`lambda-status=${y.success?"passed":"failed"}`).catch(()=>{}),p.isAlive()||(wt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),y.gridIssues="could not validate grid is alive");let b=p.maxKeepAliveGap();return b>=3e4&&(wt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),y.keepAliveIssue=b),{...y,...e.seleniumPerfStats.getStats()}}catch(y){throw wt.warn("timeout wait until test completed",{err:y,testResultId:s,executionId:n,testId:o}),new Error(y)}finally{p.unregisterToClosedBrowser(g)}}catch(f){throw wt.warn("failed to start url",{err:f}),new Error(f)}};t.driver.start();try{return await super.runTestOnce(e,t),_("WorkerExtension super.runTestOnce"),await u()}catch(d){throw wt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Qy={};W(Qy,{WorkerExtensionSingleBrowser:()=>wd});var US,jS,wd,Zy=T(()=>{"use strict";Oe();U();j();ud();Bt();bd();US=I("base-worker"),jS=500,wd=class extends qn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Wn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,s,n,o){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,s,n,o)}async getTestPlayer(t,s){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(US.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,s)),this.testPlayer}async runTest(t,s,n){let o=this.handleQuarantine(t);if(o)return o;_("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,s);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await se(jS)}}});function BS(r,e){e===0?r():setTimeout(r,e*zd)}var Td,Ia,eb=T(()=>{"use strict";Cn();U();le();Oe();au();It();Su();q();j();ae();Ly();Td=I("parallel-worker-manager"),Ia=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e){case J.SELENIUM:return(jy(),ie(Uy)).WorkerSelenium;case J.APPIUM:return(Hy(),ie(qy)).WorkerAppium;default:return Pi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Zy(),ie(Qy)).WorkerExtensionSingleBrowser:(bd(),ie(Yy)).WorkerExtension}}createWorkers(e,t,s,...n){let o=this.getWorkerType(s),i=()=>{try{return _("before new Worker",s),new o(t,...n)}finally{_("after new Worker",s)}};return Array.from(new Array(e),i)}async runTests(e,t,s,n,o,i,a,c,u){if(e&&e.length===0)return;let d=!1,p=0,m=h=>new Promise(f=>{var kt,qr,C,N,F,G;let g=o.project,y=new ha(s,n,e,o,i,t),b={},x=e.length,w=(kt=o.company)==null?void 0:kt.companyId,v=(qr=o.company)==null?void 0:qr.name,R=o.source||"cli",k=o.user,L=(C=o.company)==null?void 0:C.planType,S=(N=o.company)==null?void 0:N.isStartUp,O=(F=o.projectData)==null?void 0:F.name,A=(G=o.projectData)==null?void 0:G.type,D=o.lightweightMode,B=Er(o),V=(me,et,we,Na,Hn,Da)=>(p++,jf({executionId:s,projectId:g,testId:et,resultId:we,companyId:w,companyName:v,projectName:O,companyPlan:L,sessionType:B,source:R,user:k,lightweightMode:D,isStartUp:S,projectType:A,appSource:Da}),t.testStartAndReport(me,s,we,Na,Hn)),Y=async(me,et,we,Na,Hn,Da)=>{var kd,_d,Od;p--;let Tt={...(D==null?void 0:D.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...o.host&&{gridHost:o.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),o.grid||o.gridId?(Tt.gridName=o.grid||((kd=o.gridData)==null?void 0:kd.name),Tt.gridType=(_d=o.gridData)==null?void 0:_d.type,Tt.gridProvider=(Od=o.gridData)==null?void 0:Od.provider):o.useLocalChromeDriver?(Tt.gridName="local-chrome-driver-from-options",Tt.gridType="local-chrome"):o.useChromeLauncher?(Tt.gridName="chrome-launcher-from-options",Tt.gridType="local-chrome"):o.browserstack?Tt.gridName="browserstack-from-options":o.saucelabs&&(Tt.gridName="saucelabs-from-options"),await t.testEndAndReport(me,we,s,Na,Hn,Tt).catch(nw=>Td.error("testEndAndReport threw an error",{err:nw})),Hn)return;b[we.resultId]=we,Bf({executionId:s,projectId:g,testId:et,resultId:we.resultId,result:we,companyId:w,companyName:v,projectName:O,companyPlan:L,sessionType:B,source:R,user:k,lightweightMode:D,logger:Td,isStartUp:S,projectType:A,appSource:Da}),u&&!we.success&&(y.stop(),d=!0),(Object.keys(b).length===x||d&&p===0)&&f(b)},Z=(me,et)=>{b[et.resultId]=et,t.onTestIgnored(me,et.resultId),p--,(Object.keys(b).length===x||d&&p===0)&&f(b)},fe=(me,et)=>t.onGridSlot(me,et);o.userData={loginData:Object.assign({},Ft(),{refreshToken:Oo(),authData:Ft(),token:h}),projectId:o.project,company:o.company,servicesUrl:ge},_("in localStrategy before createWorker"),this.createWorkers(c,y,o.mode,o,this.customExtensionLocalLocation,s,V,Y,fe,Z).forEach((me,et)=>{_("before schedule worker.run after createWorkers"),BS(()=>{_("right before worker.run"),me.run()},et)})});try{let h=await Kt(),f=await m(h);if(d)throw new _t;return f}catch(h){throw Td.error("failed running parallel workers",{executionId:s,err:h}),h}}}});var xa,tb=T(()=>{"use strict";Mi();xa=class extends or{init(e){return super.initNewSocket(e,"real-data")}emitJoinRoom(e,t){this._socket.emit("testResult:listen",{query:`projectId=${t}&runId=${e}`})}joinToTestResultsByRunId(e,t){this.joinRoom(e,t),this.emitJoinRoom(e,t)}stopListenToTestResultsByRunId(e){this.leaveRoom(e),this._socket.emit("testResult:listen:stop",{})}listenToTestResultsByRunId(e){function t(s){e(s.data)}this._socket.on("testResult:changes",t.bind(this))}}});var vd,Ed,Pa,rb=T(()=>{"use strict";_n();ae();ye();tb();({TEST_RESULT_CREATED:vd,TEST_RESULT_UPDATED:Ed}=rt),Pa=class{constructor(){M.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new xa)}init(e){return M.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled())return We.addFilter(e,{runId:e},[Ed,vd],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(M.flags.useNewWSCLI.isEnabled()){We.removeFilter(e,[Ed,vd]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled()){We.listenTo(e,[Ed,vd],s=>s.runId===e,s=>t(s));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function ob(r,e){var t;if((t=r.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&r.testId)return{tests:[r.testId.map(n=>({testId:n,testConfig:{},resultId:z()}))]};if(r.files.length>0){let{buildCodeTests:s}=await Promise.resolve().then(()=>(Xu(),ry)),n={};if(r.webpackConfig){let o=nb.join(process.cwd(),r.webpackConfig);n=require(o)}return s(r.files,n,{baseUrl:r.baseUrl})}return await Vc({projectId:r.project,labels:r.label,testIds:r.testId,testNames:r.name,testConfigNames:r.testConfigNames,suiteNames:r.suites,suiteIds:r.suiteIds,branch:e,rerunFailedByRunId:r.rerunFailedByRunId,testConfigIds:r.testConfigIds,intersections:r.intersections})}function Sd(r){let e=Object.keys(r).length,t=Object.keys(r).reduce((s,n)=>s+(r[n].success===!0?1:0),0);return e===t}async function Rd(r,e){let t=r.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],s=sb.difference(Js(r,e),t);if(s.length>0)throw ht("invalid-config-run",{browser:s.join(", "),mode:"runner"}),new P(`browser type <${s}> is not supported in ${r.mode} mode.`);return e}var sb,nb,ib=T(()=>{"use strict";sb=E(require("lodash")),nb=E(require("path"));U();ds();Te();q()});var Wr,ab,$S,Aa,WS,Ca,cb=T(()=>{"use strict";Wr=E(require("lodash"));U();j();le();ae();Oe();hs();Vl();au();Te();It();Bt();rh();q();eb();rb();ib();({testRunStatus:ab,CLI_MODE:$S}=Dt),Aa=I("test-plan-runner"),WS=1e3*60*5,Ca=class{constructor(e){this.startTime=Date.now();this.workerManager=new Ia(e)}async runTestAllPhases(e,t,s,n,o,i,a,c){let u={},d=Ft(),p=async()=>{let y=o.beforeParallel||1,b=!0,x=await this.workerManager.runTests(e,c,i,a,o,n,d,y,b);Object.assign(u,x)},m=async()=>{let y=oo||o.parallel,b=!1;_("right before this.workerManager.runTests");let x=await this.workerManager.runTests(t,c,i,a,o,n,d,y,b);_("right after this.workerManager.runTests"),Object.assign(u,x)},h=async()=>{let y=o.afterParallel||1,b=!1,x=await this.workerManager.runTests(s,c,i,a,o,n,d,y,b);Object.assign(u,x)},f=Er(o);$f({executionId:i,projectId:o.project,sessionType:f}),_("right before runBeforeTests");try{return await p(),_("right before runTestPlanTests"),await m(),_("right after runTestPlanTests"),await h(),u}catch(y){if(Aa.error("error running test plan",{err:y}),y instanceof _t)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw y}finally{await g()}async function g(){var b,x,w,v;if((b=o.lightweightMode)!=null&&b.disablePixelValidation)return;if(o.mode===$S.SELENIUM){let{EyeSdkBuilder:R}=(await Promise.resolve().then(()=>(Ee(),kr))).getSessionPlayer();await R.closeBatch(i);return}let y;try{if(!((v=(w=(x=o.company)==null?void 0:x.activePlan)==null?void 0:w.premiumFeatures)!=null&&v.applitools)||(y=await al(o.project),Wr.default.isEmpty(y)||!i))return;let{runKey:R,url:k}=y;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:k,apiKey:R}})}catch{}}}async initRealDataService(e){let t=new Pa;return await t.init(e),t}async listenToTestCreatedInFile(e,t,s,n){let o={};e.joinToTestResultsByRunId(s,t);let i=!0;return await new Promise(c=>{let u=d=>{i=!1,c(d)};e.listenToTestResultsByRunId(s,d=>{let p=d.id;if(!n.getTestResult(p)){let f=o[p],g=Wr.default.merge({},f,d,{resultId:p});if(o[p]=g,!f||f.status!==d.status){let b=(n.getTestResult(g.parentResultId)||{workerId:1}).workerId;[ab.RUNNING].includes(d.status)&&Q.onTestStarted(g,b),[ab.COMPLETED].includes(d.status)&&(g.duration=g.endTime-g.startTime||0,Q.onTestFinished(g,b))}}let m=!Object.values(o).some(f=>["QUEUED","RUNNING"].includes(f.runnerStatus)),h=!Object.values(n.getAllTestResults()).some(f=>["QUEUED","RUNNING"].includes(f.status));if(m&&h)return u(Object.values(o));if(h&&!m)return se(1e4).then(()=>{i&&u(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,s){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,s)}async runTestPlan(e,t,s,n,o,i,a,c){var k,L,S;let u=z(),d=n.project;Ka(u),e.forEach(O=>Object.assign(O,{isBeforeTestPlan:!0})),s.forEach(O=>Object.assign(O,{isAfterTestPlan:!0}));let p=[...e,...t,...s],m=new Ti(p,n,i,a),h=Wr.default.chain(p).map(O=>{var A;return((A=O.overrideTestConfig)==null?void 0:A.name)||""}).uniq().compact().value(),f=(h==null?void 0:h.length)===1?h[0]:null,g=n.files.length>0,y=(k=n.lightweightMode)!=null&&k.onlyTestIdsNoSuite?[]:p.map(O=>O.name),b=(L=n.lightweightMode)!=null&&L.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:s}:m.executionStart(u,d,this.startTime,o,y),x;g&&(x=this.initRealDataServiceAndListenToTestsCreatedInFile(d,u,m)),_("before testListInfoPromise");let w=await b;(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Q.onTestPlanStarted(w.beforeTests,w.tests,w.afterTests,o,u,c,f,g),_("before runTestAllPhases");let v=await this.runTestAllPhases(w.beforeTests,w.tests,w.afterTests,a,n,u,o||"All Tests",m),R=await te(x,WS).catch(async()=>{var A;Aa.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:d,executionId:u});let O=await mn(d,"testResult",`runId=${u}&sort=runOrder`);return Wr.default.chain(((A=O==null?void 0:O.data)==null?void 0:A.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return _("before executionEnd"),await m.executionEnd(u),_("after executionEnd"),{results:v,executionId:u,testPlanName:o,configName:f,childTestResults:R}}async runTestPlans(e,t){Aa.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function s(d){return Wr.default.flattenDeep(Object.values(d)).reduce((p,m)=>p.concat(m.beforeTests,m.tests,m.afterTests),[])}let n={},o={},i=e.project,a=await Gc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,u=a.testPlansData;if(!c||c.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!u||Object.keys(u).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return await Rd(e,s(u)),await de(c,async d=>{let p=d.testPlanId;n[p]={};let m=Object.assign({},e);m.baseUrl=e.baseUrl||d.startUrl,m.host=e.host,m.port=e.port,m.gridId=e.gridId||d.gridId,e.grid&&delete m.gridId,m.gridData=await vf(e,d);let h=m.overrideExecutionName||d.name;return await de(u[p],async f=>{let g=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,m,h,p,t),y=e.files.length>0;Q.onTestPlanFinished(g.results,d.name,this.startTime,g.executionId,!1,y,g.childTestResults),n[p][g.executionId]=g.results;let b=Object.keys(n[p]).map(R=>({executionId:R,status:Sd(n[p][R])})),x=Object.keys(n[p]).map(R=>n[p][R]).reduce((R,k)=>Object.assign(R,k),{}),w=Sd(x);Object.assign(o,x);let v=w?b[0].executionId:b.find(R=>!R.status).executionId;return await Bc(i,p,{success:w,executions:b,executionId:v}),g})})}async runAnonymousTestPlan(e,t){var a;Aa.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),_("before getSuite");let s=await ob(e,t);if(_("after getSuite"),!((a=s==null?void 0:s.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in s&&s.branch||t;let n=s;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return _("Right before validateConfig + runAnonymousTestPlan tests map"),await de(s.tests,async c=>{if(e.resultId){let p=c[0];p.resultId=e.resultId,c=[p]}await Rd(e,c),_("right before runTestPlan");let u=await this.runTestPlan([],c,[],e,o,null,t,i);_("right after runTestPlan");let d=e.files.length>0;return await Q.onTestPlanFinished(u.results,o,this.startTime,u.executionId,i,d,u.childTestResults),u})}async run(e){let t=Sn(),s=[];Xs(e)?s=await this.runTestPlans(e,t):s=await this.runAnonymousTestPlan(e,t);let n=Wr.default.flattenDeep(s);return _("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),_("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var ub={};W(ub,{init:()=>cR,run:()=>iR});function VS(r){if(!Id.get(r,"company.activePlan.premiumFeatures.allowCLI")){let t=r.project;us(r.authData.uid,"cli-not-supported",{projectId:t}),console.warn("Testim CLI is not supported in this plan")}}async function qS(r){let e=r.project,t=await Hc(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"),us(r.authData.uid,"execution-quota-surpassed",{projectId:e}),new Xr}function HS(r,e){var o,i,a,c;if(fo(e.activePlan)==="free"){let u=r.parallel||1,d=((i=(o=e.activePlan)==null?void 0:o.premiumFeatures)==null?void 0:i.concurrency)||1;if(u>d)throw new P(`Cannot run with parallel ${r.parallel}. Max parallel value is ${d}`)}let s=r.retentionDays;if(!s)return;let n=(c=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:c.resultRetention;if(s>n)throw new P(`Retention days (${s}) cannot be greater than the company's retention days (${n}). Run aborted`)}async function zS(r){var e;if(!((e=r.lightweightMode)!=null&&e.disableQuotaBlocking))try{await Promise.all([qS(r),VS(r)])}catch(t){if([P,Xr].some(s=>t instanceof s))throw t;GS.error("could not validate cli account",{err:t})}}function KS(r){let e=Ft();return Rm({userId:e.uid,name:e.uid,traits:{projectId:r,company:{id:r,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function JS(r,{disableResults:e=!1,disableRemoteStep:t=!1}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return We.connect(r);if(!t){let{remoteStepService:s}=await Promise.resolve().then(()=>(ma(),xy));await s.init(r)}if(!e){let{testResultService:s}=await Promise.resolve().then(()=>(As(),qh));s.init(r)}}function XS(r,e){let{branch:t,autoDetect:s}=r;if(If(e,s),!e&&!s)throw new P(`branch ${t} does not exist, run aborted.`)}async function YS(r){let{project:e}=r,t=Sn();Id.get(r,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(r.sfdcCredential=await Uc({projectId:e,branch:t}))}function QS(r,e){let{onprem:t,id:s,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:p,extensionPath:m,ext:h,playerPath:f}=r;if([J.SELENIUM].includes(p)&&!f)throw new P("in selenium on prem mode --player-path must be provided");if(p==="extension"&&!m&&!h)throw new P("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),u=Boolean(a.isStartUp),d=fo(a);d==="free"&&(r.newBrowserWaitTimeout=r.newBrowserWaitTimeout<lb?lb:r.newBrowserWaitTimeout),M.setCompanyId(s),M.setIsPOC(c),M.setIsStartUp(u),M.setPlanType(d),Pt.setPlanType(d),r.company={companyId:s,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:d,isPOC:c,isStartUp:u,activePlan:a}}function ZS(r,e){if(zr){r.editorUrl=zr;return}r.editorUrl=e.editorUrl}function eR(r,e){r.allGrids=e}function tR(r,e){r.authData=e}function rR(r,e){let{id:t,name:s,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),r.projectData={projectId:t,type:n,name:s,defaults:o}}async function sR(r){r.gridData=await Ef(r)}async function nR(r){let{project:e}=r,t={projectId:e};r.overrideMappingFile&&(ht("user-override-file",t),r.mockNetworkRules=await pm(r.overrideMappingFile))}async function oR(r,e){_("in runner.js runRunner");let{project:t,remoteRunId:s,useLocalChromeDriver:n,useChromeLauncher:o}=r;s||(r.source=n||o?"cli-local":"cli"),await Xm(),_("in runner.js after checkNpmVersion"),await zS(r),_("in runRunner before tunnel.connect"),await si(r),_("in runRunner after tunnel.connect");let a=await new Ca(e).run(r);return _("before tunnel.disconnect"),await ni(r),await vn.end(t),_("after tunnel.disconnect and gridService.keepAlive.end"),a}function aR(r){var e;Pt.shouldShowFreeGridRunWarning((e=r.gridData)==null?void 0:e.type)&&console.log(`
|
|
562
|
+
`;t+="};",await it.promises.writeFile(r,t)}async function ed(r,{mergeIntoExisting:e}={mergeIntoExisting:!1}){let t=await Br(process.cwd()),s=Ze.join(t,"locators","locators.js");await it.promises.mkdir(Ze.join(t,"locators")).catch(()=>{});for(let{name:o,id:i,elementLocator:a}of r)await it.promises.writeFile(Ze.join(t,"locators",`locator.${i}.json`),JSON.stringify({name:o,id:i,elementLocator:a}));let n=Object.fromEntries(r.map(({name:o,id:i})=>[o,i]));if(e){let o=await jn();Object.assign(n,o)}await ny(s,n)}async function td({fileSystem:r,bypassWebpack:e}={},t=void 0){let s=await Br(process.cwd());if(t!=null&&t.aborted)throw new Be;let n=Ze.join(s,"functions.js");if(e!=null&&e.testim){let i=require("module"),a=i.prototype.require;i.prototype.require=function(u){return u==="testim"?e.testim:a.apply(this,arguments)};try{return delete require.cache[require.resolve(n)],require(n)}finally{i.prototype.require=a}}return(await Ju([n],{output:{libraryTarget:"umd",library:"tdk",globalObject:"globalThis"},cache:{type:"memory"},mode:"development"},{},r,t)).tests[0][0].code}var sy,Ze,it,Br,rd=T(()=>{"use strict";sy=E(require("lodash")),Ze=E(require("path")),it=require("fs");q();Yu();Br=sy.memoize(async r=>(await it.promises.readdir(r)).includes("tests")&&(await it.promises.stat(Ze.join(r,"tests"))).isDirectory()?Ze.join(r,"tests"):r)});var iy={};W(iy,{getArgumentsFromContext:()=>$r});async function $r(r,e,t){let s=nS(r.parameterNames.map(n=>n.displayName),e.incomingParams.as);return await Promise.all(s.map(n=>typeof n=="object"&&n.locatedElement?t(n):n))}function nS(r,e){let t=[];for(let s of r){let n=e.functionParameters.indexOf(s);t.push(e.functionArguments[n])}return t}var Bn=T(()=>{"use strict"});var cy={};W(cy,{execute:()=>aS});async function cS(r,e,t,s,n,o){var a;let i;try{let{WebDriver:c}=await oS("selenium-webdriver");if(o.aborted)throw new ay;let{Executor:u,HttpClient:d}=require("selenium-webdriver/http"),p=r.driver.client.options,m=p.path,f=`${p.protocol}://${p.hostname}:${p.port}`+m,h=new d(f),y=new c(r.getSessionId(),new u(h));await lS(y,r.driver);let I=await iS(t,s,v=>y.findElement({css:v.selector})),w=e.bind(null,y,...I);return i=function(){h.send=async function(){throw new ay}},o.addEventListener("abort",i),await w(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}async function lS(r,e){if(e.cdpUrl){let t=await r.getAllWindowHandles();for(let s of t)if(await r.switchTo().window(s),await r.executeScript("return window.__isMainTestimTab"))break}}var ay,oS,iS,aS,ly=T(()=>{"use strict";({AbortError:ay}=(q(),ie(np))),{lazyRequire:oS}=(yt(),ie(_l)),{getArgumentsFromContext:iS}=(Bn(),ie(iy)),aS=cS});var uy={};W(uy,{execute:()=>uS});async function dS(r,e,t,s,n,o){var a;let i;try{let c=await ge("puppeteer");if(o.aborted)throw new Be;let u=await c.connect({browserWSEndpoint:r.driver.cdpUrl,defaultViewport:null,product:"chrome"});if(o.aborted)throw u.disconnect(),new Be;i=function(){u.disconnect()},o.addEventListener("abort",i);let d=await u.pages(),p;for(let y of d)if(await y.evaluate(()=>window.__isMainTestimTab)){p=y;break}let m=p||d.at(-1),f=await $r(t,s,y=>m.$(y.selector));return await e.bind(null,m,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{o.removeEventListener("abort",i)}}var uS,dy=T(()=>{"use strict";q();yt();Bn();uS=dS});var py={};W(py,{execute:()=>pS});async function mS(r,e,t,s,n,o){var a;let i;try{let c=await ge("playwright");if(o.aborted)throw new Be;let u=await c.chromium.connect({wsEndpoint:r.driver.cdpUrl});if(o.aborted)throw u.disconnect(),new Be;i=function(){u.disconnect()},o.addEventListener("abort",i);let m=(await(await u.newContext({viewport:null})).pages()).at(-1),f=await $r(t,s,y=>m.$(y.selector));return await e.bind(null,m,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}var pS,my=T(()=>{"use strict";q();yt();Bn();pS=mS});var gy={};W(gy,{execute:()=>fS});async function gS(r,e,t,s,n,o,i,a){function c(){r.sessionPlayer.stopPlaying()}a.addEventListener("abort",c);function u(A){if(o.parameterValues){let N=o.parameterValues.find(B=>B.type==="locate"&&B.id===A.locatorId);return{elementLocator:N.elementLocator,id:N.id,name:"Hybrid Step Locator"}}return A.locatedElement.shadowPath?A.locatedElement.shadowPath[0]:A}let d=await $r(o,t,u),p=e.bind(null,...d),m=z(),g=z(),f=t.testResultId,h=t.config.baseUrl,y=fy.cloneDeep(t);y.loginData=s;let I=re().manifestVersion||"runner",w=!1,v=null,R="master",k=`Execute TDK Function '${o.functionName}'`,L=!0,S={fn:p,bypassSetup:!0,isBeforeOrAfterTest:!0,name:k,sourceCode:p.toString(),sourceName:p.name,testId:m,resultId:z()},O=typeof e.results=="boolean"&&!e.results;try{_("tdkHybridStepPlayback before addAllTabs"),n?(r.sessionPlayer.playbackAutUtils.frameManager=n,r.sessionPlayer.frameManager=n):await r.addAllTabs(null,{loadInfo:!0,checkForMainTab:!0,takeScreenshots:!O},[r.driver.initialUrl]),r.sessionPlayer.playbackManager.dontAssociateChildResult=!0,r.sessionPlayer.playbackManager.onlyLocalReporting=O,_("tdkHybridStepPlayback before playTestByCode");let A=await new Promise((N,B)=>{i==="agent"&&hS(r,N);function V(){B(new Be),a.removeEventListener("abort",V)}a.addEventListener("abort",V),r.sessionPlayer.playTestByCode(m,g,f,h,y,I,N,w,v,R,[S],k,L).catch(B)});return _("tdkHybridStepPlayback after playTestByCode"),{success:A.success,shouldRetry:!1,resultInfo:{testId:m,executionId:g,resultId:S.resultId}}}catch(A){return{success:!1,error:A,shouldRetry:!1}}finally{a.removeEventListener("abort",c)}}function hS(r,e){let{commonConstants:t}=re();r.sessionPlayer.playbackManager.on(t.playback.START,({testResult:s})=>{let n=s.runnerStatus;Object.defineProperty(s,"runnerStatus",{get(){return n},set(o){n=o,o==="FINISHED"&&e(s)}})})}var fy,fS,hy=T(()=>{"use strict";fy=E(require("lodash"));Oe();U();q();Bn();Ee();fS=gS});var da={};W(da,{abort:()=>od,execute:()=>ks,run:()=>wS});async function ks(r,e,t,s,n,o="cli"){let i=new by.AbortController,{signal:a}=i;nd.set(e.stepResultId,i);try{_("before seleniumTestPlayer require");let{SeleniumTestPlayer:c}=(la(),ie(Ku)),{compileFunctionsLibrary:u}=(rd(),ie(oy)),{functionName:d}=r,p={},m=!1,g=new c(e.id,p,m,Dt.CODEFUL,t);sd=g.sessionPlayer.codeSessionPlayer.proxy;let f=r.bypassWebpack?{testim:sd.wrappedSteps()}:!1;_("before compileFunctionsLibrary",{bypassWebpack:Boolean(r.bypassWebpack)});let h;try{h=await u({fileSystem:yS,bypassWebpack:f},a)}catch(b){return{success:!1,shouldRetry:!1,reason:`Unable to compile functions library. ${b.message}`,extraInfo:b.stack}}typeof globalThis>"u"&&(global.globalThis=process);let y;if(f?y=h[d]:(global.globalThis.__testim=sd.wrappedSteps(),(0,eval)(h),y=globalThis.tdk[d]),_("after hybridFunction obtain and eval"),!y)return{success:!1,shouldRetry:!1,reason:`Could not find function '${d}' locally. Please make sure you have a functions.js file with a '${d}' function defined`,extraInfo:Object.keys(globalThis.tdk)};if(y.type==="selenium"){let b=(ly(),ie(cy)).execute;return await b(g,y,r,e,o,a)}if(y.type==="puppeteer"){if(!g.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running puppeteer code requires the remote debugging protocol to be open. Please contact Testim support."};_("before puppeteerPlayback");let b=(dy(),ie(uy)).execute;try{return await b(g,y,r,e,o,a)}finally{_("after puppeteerPlayback")}}if(y.type==="playwright"){if(!g.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running playwright code requires the remote debugging protocol to be open. Please contact Testim support."};let b=(my(),ie(py)).execute;return await b(g,y,r,e,o,a)}if(y.type==="tdk"||!y.type){let b=(hy(),ie(gy)).execute;_("before tdkPlayback");try{return await b(g,y,e,s,n,r,o,a)}finally{_("after tdkPlayback")}}return{success:!1,shouldRetry:!1,reason:`unknown hybrid format ${y.type}`}}catch(c){bS.info("error running hybrid step",{err:c});return}finally{nd.delete(e.stepResultId)}}function od(r){let e=nd.get(r);if(e)e.abort();else throw new Error("No such stepResultId")}var yy,by,yS,bS,nd,sd,wS,na=T(()=>{"use strict";yy=E(require("memory-fs"));Oe();by=require("abort-controller");j();ae();yS=new yy.default,bS=x("hybrid-step-playback"),nd=new Map,wS=(r,e,t,s)=>{let{step:n,context:o}=e.data;return ks(n,o,r,s.loginData)}});var id={};W(id,{run:()=>TS});var TS,wy=T(()=>{"use strict";U();Fr();q();TS=async(r,e)=>{let{stepId:t,testResultId:s,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await vs(t,s,n,i,o,a),success:!0}}catch(c){if(c instanceof dt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof Y)return{success:!1,code:"timeout"};throw c}}});async function vy(r,e,t,s){try{return await nl(r,e,t,s)}catch{pa.error("failed to report remote step state",{projectId:r,resultId:e,stepId:t});return}}async function ES(r,e,t,s,n){return pa.info("finished to run remote step",{stepId:t,sessionId:n}),await vy(r,e,t,{status:"completed",success:!0,failureReason:null,data:s})}async function Ty(r,e,t,s,n){return pa.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:s}),await vy(r,e,t,{status:"completed",success:!1,failureReason:s})}async function Ey(r,e,t,s){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o,userData:i}=r,a=t.type,c=e.getSessionId(),u=t.id;pa.info("start play remote step",{stepType:a,stepId:u,sessionId:c});let d=vS[a];if(!d)return await Ty(n,s,u,`Failed to find step type ${a}`,c);try{let p=await d.run(e,t,o,i);return await ES(n,s,u,p,c)}catch(p){return await Ty(n,s,u,p.message,c)}}var pa,vS,Sy=T(()=>{"use strict";Ag();na();Te();wy();j();pa=x("step-playback"),vS={"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":id,"tdk-hybrid":da}});var Ry={};W(Ry,{remoteStepServiceSocketIO:()=>RS});var ad,RS,Iy=T(()=>{"use strict";Mi();ad=class extends or{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,s){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&s(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},RS=new ad});var xy={};W(xy,{remoteStepService:()=>Ds});var cd,$n,ld,Ds,ma=T(()=>{"use strict";_n();ae();ye();({REMOTE_STEP_SAVED:cd}=rt),ld=class{async init(e){M.flags.useNewWSCLI.isEnabled()||($n=(await Promise.resolve().then(()=>(Iy(),Ry))).remoteStepServiceSocketIO,$n.init(e))}joinToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?We.addFilter(`${e}:remoteStep`,{resultId:e},[cd]):$n.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(M.flags.useNewWSCLI.isEnabled()){We.listenTo(`${e}:remoteStep`,[cd],s=>s.resultId===e&&s.remoteStep&&s.remoteStep.status==="pending",s=>t(s.remoteStep));return}$n.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?(We.removeFilter(`${e}:remoteStep`,[cd]),Promise.resolve()):$n.unlistenToRemoteStep(e)}},Ds=new ld});var Ay,Cy,ky,Se,IS,_y,Py,fa,Oy=T(()=>{"use strict";Ay=E(require("lodash"));U();le();Oe();ds();It();Te();Sy();Cy=E(require("p-retry")),ky=require("url");j();Jo();ys();ae();ma();As();ye();Se=x("test-run-handler"),IS=3,_y=20*1e3,Py=r=>JSON.stringify(r).length<_y,fa=class{constructor(e,t,s,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new $t;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.clearTestResultFinished=Promise.resolve(void 0);var c,u;this._testStatus=s.testStatus,this._testId=s.testId,this._testName=s.name,this._testResultId=s.resultId,this._code=s.code,this._baseUrl=n.baseUrl||s.baseUrl||s.testConfig.baseUrl,this._nativeApp=s.nativeApp,this._overrideTestConfigId=(c=s.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((u=s.runConfig)!=null&&u.isMobileWeb)&&n.browser;this._runConfig=a?tn(n.browser,n.saucelabs,n.browserstack):s.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get automationMode(){return this._code?"codeful":"codeless"}get code(){return this._code}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}get androidActivityWait(){var n;let e=this._nativeApp&&"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if((n=e==null?void 0:e.activity)!=null&&n.includes(e.id))return`${e.id}.*`;let{activity:t}=e;if(!t)return null;let s=t.split(".").pop();return t.replace(s,"*")}get isFFAllowAppFromDeviceEnabled(){return M.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return Xs(this._nativeApp)}get isAppForIosVirtualDevice(){return es(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?uo.FROM_DEVICE:uo.FROM_LIBRARY}get nativeAppLink(){let e=null;return this._nativeApp&&"filePath"in this._nativeApp&&(e=`${he}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`),e}async getNativeAppData(){let{appId:e,baseUrl:t}=this._options;if(t&&!this._nativeApp&&!e){let s=t||this.baseUrl;if(!s)return null;let[n,o]=s.split(":");return{packageName:n,activity:o}}return this._nativeApp&&!e?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var s,n;let t={tokenV3:await Kt(),refreshToken:Oo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Jd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this.code&&{isCodeMode:!0,testName:this.testName},...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,onprem:this._options.company.onprem,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential}};if(this._options.disableMockNetwork&>("user-disable-mock"),t.lightweightMode&&((s=this._options.lightweightMode)!=null&&s.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Py(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),Se.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${_y} 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 wn(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 Se.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.runMode===J.EXTENSION&&{code:this.code},...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Py(e))return;let s=async()=>{try{return await ol(this._options.project,this._testId,this._testResultId,e)}catch(i){return Se.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await s();return await this._testRunStatus.waitForExecutionStartedFinished(),sl(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}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){_("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},{targetId:s}=t.find(o=>o.type==="background_page"&&o.title==="Testim Editor")||{},{targetId:n}=t.find(o=>o.type==="page")||{};if(!s)throw new Error("testim extension not found");if(!n)throw new Error("AUT target not found");try{_("before Target.attachToTarget");let[o,i]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:s,flatten:!0}),this.getRunRequestParams()]),{sessionId:a}=o||{};_("before Runtime.evaluate"),await(0,Cy.default)(async()=>{let{result:u}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},a);if(!u.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),_("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(i)})`,awaitPromise:!0,returnByValue:!0},a);if(c.subtype==="error")throw new Error(c.description);return _("after Runtime.evaluate"),c.value}catch(o){throw Se.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let s;try{s=new ky.URL(e)}catch{return}let{username:n,password:o}=s;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let s=!1,n=o=>{if(!s){if(this.isRetryKeyMismatch(o)){Se.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"&&(Se.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),s=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:u,_options:{project:d}}=this;try{let p=await Cr(a,c,d,u);n(p),s||setTimeout(i,3e3)}catch(p){Se.error("failed to check if done",{err:p}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Qe.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:s},branch:n}=this;try{let o=await Cr(e,t,s,n),i=["running","completed"];if(i.includes(o.status))return Se.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw Se.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error($e.TEST_START_TIMEOUT_MSG)}catch(o){throw Se.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error($e.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Qe.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(s=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),s(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Qe.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){Se.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,s(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Ay.debounce(async()=>{try{let i=await Cr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(Se.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"?(Se.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,s(i),!0):!1}catch(i){return Se.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Qe.on("socket-connected",e);else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await zc(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){Se.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Qe.off("socket-connected",e)}}listenToRemoteStep(e){Ds.listenToRemoteStep(this.testResultId,t=>{Ey(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:IS;return this._timeoutRetryCount<e}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,s;return Boolean((s=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:s.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||(this._originalTestResultId=this._previousTestResultId),this._testResultId=z(),!((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 ga,Ly=T(()=>{"use strict";Oy();ga=class{constructor(e,t,s,n,o,i){this._waitingTests=s.map(a=>new fa(e,t,a,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var xS,PS,Wn,ud=T(()=>{"use strict";gs();j();xS=x("worker-utils"),PS=async(r,e,t)=>{e&&await Gl(r,t)},Wn=async(r,e,t,s)=>{xS.info("releasing player",{hasPlayer:Boolean(s)});try{await(s==null?void 0:s.onDone())}finally{await PS(r,e,t)}}});function LS(r,e,t,s){return{testId:r,reason:s,name:e,resultId:t,success:!1}}var md,Fy,pd,At,Dy,Ny,My,Gn,AS,dd,CS,Gt,kS,ha,_S,OS,Ct,ya=T(()=>{"use strict";md=E(require("ms")),Fy=E(require("moment")),pd=E(require("p-retry"));U();Oe();gs();Te();j();ud();Bt();ti();ye();ma();As();Rt();ae();q();At=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Dy,TEST_START_TIMEOUT_MSG:Ny,TEST_COMPLETE_TIMEOUT_MSG:My}=$e,{SETUP_TIMEOUT:Gn,NETWORK_ERROR:AS,GRID_ERROR:dd,BROWSER_CLOSED:CS,SELENIUM_ERROR:Gt,UNKNOWN_ERROR:kS,MOBILE_SESSION_ERROR:ha}=Ks,_S=(0,md.default)("1s"),OS=1;Ct=class{constructor(e,t,s,n,o,i,a,c,u=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=s;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=u;this.id=Ct.getWorkerId();this.lambdatestService=new ee;this.isCodeMode=t.files&&t.files.length>0,this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return OS++}async getGridSlot(e,t){let s=await Sf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,s),s}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Xr(!0)}async getBrowserOnce(e,t,s,n){throw new Xr(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),At.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){let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice,s=e.isAppForIosVirtualDevice;if(t||s){let n={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:s}};return this.onTestIgnored(this.id,n),n}}setSessionTimeout(){return this.options.mode===J.APPIUM?Math.max((0,md.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let s=(o=this.userData)==null?void 0:o.projectId,n;try{_("before getSlotOnce retries");let i=0,a=await(0,pd.default)(async()=>{let d=Date.now();try{return await te(this.getSlotOnce(e),this.options.getBrowserTimeout,$e.GET_BROWSER_TIMEOUT_MSG)}catch(p){let m={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw p instanceof gr?At.info("could not get grid slot due to concurrency issue",m):At.error("error getting grid slot",{error:p,...m}),i++,await se(this.options.getBrowserTimeout-(Date.now()-d)),p}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});_("after getSlotOnce retries"),_("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let u=0;n=await(0,pd.default)(async()=>{let d=Date.now(),p=this.initPlayer(e);try{a=await Rf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:u+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=u;let m=this.setSessionTimeout();_("before getBrowserOnce");let g=await te(this.getBrowserOnce(e,t,p,a),m,$e.GET_BROWSER_TIMEOUT_MSG);return _("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,s),p||g}catch(m){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:u,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===J.APPIUM?"device":"browser";throw At.error(`error getting ${f} from grid`,{error:m,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),Q.onGetBrowserFailure(this.id,s,++u),p.onDone(),!(m instanceof lt)&&this.options.mode!==J.APPIUM&&await se(this.options.getBrowserTimeout-(Date.now()-d)),m}},{retries:c-1,minTimeout:0,factor:1}),_("after getBrowserOnce retries")}catch(i){throw await Wn(this.id,this.releaseSlotOnTestFinished,s,n),i instanceof lt?i:i instanceof ut?new Vt(i,dd):new Vt(i,Gt)}return n}async runTest(e,t,s){var d;_("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Qs(this.options)&&this.handleMobileTest(e);if(i)return i;_("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey,a);e.baseUrl=c.config.baseUrl;let u=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,u)}finally{await Wn(this.id,this.releaseSlotOnTestFinished,n,u)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var m,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var k;if(Je(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice)return e();let b=h.sessionId,I=L=>y==null?void 0:y.message.includes(L),w=y&&y instanceof Vt,v=y&&(I(Ny)||I(My)),R=!f.success&&(h.hasMoreRetries()&&!w&&!v||v&&h.hasMoreTimeoutRetries());try{let L=h.retryKey;f.testRetryKey=L;let S=h.getAppSource;return await this.onTestCompleted(this.id,this.testId,f,b,R,S),this.executionQueue.hasMoreTests()&&!((k=this.options.lightweightMode)!=null&&k.general)&&await se(_S),await this.runTestCleanup(),R?(v?await h.startNewTimeoutRetry():await h.startNewRetry(),At.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:L,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await d(h,R)):await e()}catch(L){if(L instanceof _t)return;At.error("failed to process test result",{error:L}),e();return}},s=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
563
|
+
Please make sure the CLI has stable access to the internet. ${ic()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:b}=mc,I=f instanceof Error?f.message:f;return I.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),I.includes(Dy)?{errorType:Gn,reason:"Test couldn't get device, time"}:I.includes(y)?{errorType:ha,reason:"app doesn't exist on device"}:I.includes(b)?{ErrorType:ha,reason:"app never started, check app permission or app activity"}:I.includes(h)?{ErrorType:ha,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:ha,reason:I}},o=(f,h)=>{let y=this.options.mode===J.APPIUM?"device":"browser";if(!h&&M.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:AS,reason:s()};let b=f instanceof Error?f.message:f;if(b.includes(Dy))return{errorType:Gn,reason:`Test couldn't get ${y}`};if(b.includes(Ny))return{errorType:Gn,reason:"Test couldn't be started"};if(b.includes(My)){if(!this.testRunTimeout)return{errorType:Gn,reason:"Test timeout reached: test is too long"};let I=Fy.default.duration(this.testRunTimeout,"milliseconds"),w=Math.floor(I.asMinutes()),v=I.seconds(),R=w>0?` ${w} min`:"",k=v>0?` ${v} sec`:"";return{errorType:Gn,reason:`Test timeout reached (timeout:${R}${k}): test is too long`}}if(f instanceof Vt&&f.type){if(f.type===dd)return{errorType:dd,reason:`Test couldn't get ${y} from grid - ${f.message}`};if(f.type===Gt)return{errorType:Gt,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===CS?{errorType:Gt,reason:"Session terminated, it is possible that the cli could not connect to the grid to send keep-alive requests for a prolonged period"}:"failure"in f&&f.failure instanceof fr?{errorType:Gt,reason:`Test couldn't get ${y} from grid - ${f.failure.message}`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:Gt,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(f.message)?{errorType:Gt,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(f.message)?{errorType:Gt,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(f.message)?{errorType:Gt,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:kS,reason:b}},i=async(f,h)=>{var v;let y=await oc();!y&&M.flags.warnOnBadNetwork.isEnabled()&&console.warn(s()),At.warn("error on run",{err:f});let b=(v=this.userData)==null?void 0:v.projectId,{errorType:I,reason:w}=this.options.mode===J.APPIUM?n(f):o(f,y);rl(b,this.testResultId,this.testId,{status:zs.COMPLETED,success:!1,reason:w,errorType:I,testRetryKey:h.retryKey,setupStepResult:{status:zs.COMPLETED,success:!1,reason:w,errorType:I}},h.remoteRunId),await t(LS(this.testId,this.testName,this.testResultId,w),h,f)},a=async(f,h)=>{var v;let y=this.testId,b=this.testResultId,I=(v=this.userData)==null?void 0:v.projectId,w=this.branch;if(!y||!b||!I||!w)return At.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let R=await Cr(y,b,I,w);if(At.warn("Test failed. Got results via API",{err:f,testResult:R}),R&&R.status===zs.COMPLETED)return await t(R,h);throw f}catch(R){return R!==f&&At.error("Failed to fetch test results from server",{testId:y,resultId:b,projectId:I,branch:w,err:R}),i(f,h)}},c=this.options.disableSockets||((m=this.options.lightweightMode)==null?void 0:m.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),u=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),d=async(f,h)=>{try{await Promise.all([!u&&Ds.joinToRemoteStep(this.testResultId),!c&&Qe.joinToTestResult(this.testResultId,this.testId)]),f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),b=await t(y,f);return _("After onRunComplete"),b}catch(y){return a(y,f)}finally{u||Ds.unlistenToRemoteStep(this.testResultId)}},p=this.executionQueue.getNext();return p?(this.testId=p.testId,this.testName=p.testName,this.testResultId=p.testResultId,this.overrideTestConfigId=p.overrideTestConfigId,this.testRunConfig=p.runConfig,this.branch=p.branch,d(p)):this.onQueueCompleted()}}});var Uy={};W(Uy,{WorkerSelenium:()=>fd});function NS(r){let{playback:e}=re().commonConstants;function t(s){r.playbackManager.on(s,()=>{_(`Got event ${s}`)})}Object.values(e).forEach(t)}var ba,DS,fd,jy=T(()=>{"use strict";U();Oe();ya();j();Bt();q();Jo();ae();Cu();la();Ee();ba=x("worker-selenium"),DS=1e9,fd=class extends Ct{initPlayer(t){return new Un(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){_("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new Is(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let u=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,s,this.executionId,this.testResultId,t.seleniumPerfStats,u,this.lambdatestService),_("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:u}),_("in WorkerSelenium after addTab"),u||await this.windowUtils.navigate(c,DS),await this.windowUtils.validatePageIsAvailable(),_("in WorkerSelenium after navigate")}catch(u){let d=u.message&&(u.message.startsWith("Malformed URL")||u.message.includes("Reached error page: about:neterror"))&&a==="firefox",p=u.message&&u.message==="invalid argument";throw u instanceof lt||d||p?new lt(`Page '${c}' is not available`):(ba.error("failed to navigate to page",{baseUrl:c,err:u}),u)}}async runTestOnce(t,s){var d;let n=re(),{driver:o,sessionPlayer:i}=s,a=n.manifestVersion||"runner";Q.onWaitToTestComplete(this.id,this.isCodeMode),NS(i),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&i.setSfdcCredential(t.sfdcCredential),n.localAssetService&&n.localAssetService.initialize({serverUrl:this.options.localRCASaver});let c=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(c=(await wn(this.options))[this.testId]);let u=async()=>{if(t.automationMode==="codeful"){i.callOrderScheduler?i.callOrderScheduler.schedule(()=>t.waitForExecutionStartedFinished(),{key:`test-result:${this.userData.projectId}:${this.testResultId}`}):await t.waitForExecutionStartedFinished(),_("right before playTestByCode");let m=new Promise((g,f)=>{i.playTestByCode(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,g,!1,this.overrideTestConfigId,this.branch,t.code,t.testName).catch(f)});return te(m.then(g=>(_("right after playTestByCode"),g)),this.testRunTimeout,$e.TEST_COMPLETE_TIMEOUT_MSG).catch(g=>{var f;throw g instanceof Y&&((f=i.stopPlayingOnTestTimeout)==null||f.call(i)),g}).then(g=>(g.resultId=this.testResultId,g))}let p=!1;return te(new Promise((m,g)=>{i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,m,!1,this.overrideTestConfigId,this.branch,p,t.remoteRunId,void 0,void 0,c).catch(g)}),this.testRunTimeout,$e.TEST_COMPLETE_TIMEOUT_MSG).catch(m=>{var g;throw m instanceof Y&&((g=i.stopPlayingOnTestTimeout)==null||g.call(i)),m}).then(async m=>{n.localAssetService&&await n.localAssetService.drain(),m.stepsResults=null,m.resultId=this.testResultId,o.isAlive()||(ba.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.gridIssues="could not validate grid is alive");let g=o.maxKeepAliveGap();g>=3e4&&(ba.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),m.keepAliveIssue=g);let h={...m,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h})};o.start(),_("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,s),_("right after super.runTestOnce in workerSelenium");let p=await u();return _("right after runSeleniumTest"),p}catch(p){throw ba.error("failed to run test once",{err:p}),p}}}});var wa,By=T(()=>{"use strict";wa=class{constructor(e){this.driver=e,this._utils={},this.sessionTabs={},this.pendingTabs={},this.addedTabs={}}on(){}tabCount(e){}getAllOpenTabIds(e){}getActiveTabInfo(e){}getAllTabIds(e){}isSessionTab(e,t){}createSesion(e){}setAddFrameHandlerCallBack(e){}getAllTabInfoStrings(e){}getAllTabInfos(e){}addNewTab(e,t,s,n={}){}addOpenerStepId(e,t,s){}addOpenerStep(e,t,s){}fixMissingMainTab(e){}buildTabInfo(e,t,s,n,o={}){}addTab(e,t,s,n,o={}){}getTabUtilsByTabIdAndSessionId(e,t){}getTabUtilsByTabId(e){}getTabInfo(e,t){}getTabUtils(e,t){}exactUrlMatch(e,t,s){}singleExactMatchForParts(e,t,s,n){}isSameTab(e,t,s){}getMainTabInfo(e){}getMainTabUtils(e){return{}}removeTabInfo(e,t){}getMainTabId(e){}isMainTabExists(e){}clearAllTabs(e){}clearNonMainTabs(e){}switchTab(e,t,{forceSwitch:s}={forceSwitch:!1}){}getTabDetails(e,t,s={}){}getUnregisteredTabId(e){}waitForTabToOpen(e){}tryToAddTab(e,t){}addNewPopup(e,t){}waitToPendingTabs(e,t){}isMainTabIncognito(){}isInvalidStepVersion(e){}getTabIdByTabInfo(e,t){}}});function $y(r){class e{constructor(s,n){this.frameManager=s;this.locateElementPlayer=n;this.frameManager=s,this.locateElementPlayer=n}foundFrameCallback(){return gd.info("foundFrameCallback-mock invoked"),{}}locate(){return gd.info("locate-mock invoked"),{}}findFrame(){return gd.info("findFrame-mock invoked"),{}}}return e}var gd,Wy=T(()=>{"use strict";j();gd=x("mobile-frame-locator-mock")});var MS,FS,Ta,Gy=T(()=>{"use strict";MS=E(require("webdriverio"));By();Ou();j();Lu();Du();Ee();As();Vu();Wy();Hu();zu();FS=x("appium-test-player"),Ta=class{constructor(e,t,s,n,o=MS,i=void 0,a=void 0){this.id=e;this.driver=o;let{sessionPlayer:c,commonConstants:u,stepActionFactory:d,MobileLocateElementPlayer:p}=re(),m=new Ps(this.driver);this.stepActionFactory=new d(m),ca(this.driver,this.stepActionFactory),this.tabService=new wa(this.driver),this.windowCreationListener=Fn,this.playbackTimeoutCalculator=new Ls(Di()),this.tabService.createSesion(e);let g=$y(this.driver);this.sessionPlayer=new c(e,this.tabService,null,null,g,Li,p,null,m,this.stepActionFactory,this.playbackTimeoutCalculator,Qe.getSocket(),n),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(u.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){}async onDone(){var e,t;try{await((t=(e=this.driver)==null?void 0:e.activeSession)==null?void 0:t.deleteSession())}catch(s){FS.error("error while deleting appium session",{error:s})}finally{let{commonConstants:s}=re();this.sessionPlayer.playbackManager.off(s.playback.RESULT),this.sessionPlayer=null,this.tabService=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e,t;return(t=(e=this.driver)==null?void 0:e.activeSession)==null?void 0:t.sessionId}}});var qy={};W(qy,{WorkerAppium:()=>hd});var Vy,Vn,hd,Hy=T(()=>{"use strict";Vy=E(require("jsdom"));le();Te();Ei();ya();j();Bt();Gy();Ee();Vn=x("worker-appium"),hd=class extends Ct{initPlayer(e){return new Ta(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){Q.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=s,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,u=e.nativeAppLink;if(this.options.appId){let{project:d,appId:p}=this.options,m=await qc({appId:p,projectId:d});if(!m)throw Vn.error("mobile app not found",{appId:p,projectId:d}),new Error("mobile app not found");u=`${he}/storage${m.filePath}?access_token=${this.options.authData.token}`}try{let d=[{executionId:this.executionId},{testResultId:this.testResultId}],p=ug({projectType:i,gridInfo:n,testRunConfig:this.testRunConfig,nativeApp:a,options:this.options,appPath:u,androidActivityWait:c,sessionTags:d}),m=await o.remote(p);Object.assign(o,{activeSession:m}),await this.updateDeviceInfo(e,m),Vn.info(`init new appium session testName: ${this.testName}`,{sessionId:m.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(d){throw Vn.error("failed to start application",{err:d}),d}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:s}=this.options.gridData;return`https://${e}:${t}/v0/${s}/wd/hub`}async updateDeviceInfo(e,t){var g;let{executionId:s,testId:n,testResultId:o}=e,{project:i,projectData:{type:a}={},company:{companyId:c=""}={},gridData:{gridId:u=""}={}}=this.options,d=await pl({projectId:i,projectType:a,companyId:c,gridId:u,selectors:`device_id:${t.capabilities.udid}`}),m={name:(g=d==null?void 0:d[0])==null?void 0:g.name,model:t.capabilities.deviceModel,osVersion:t.capabilities.platformVersion,udid:t.capabilities.udid,osType:t.capabilities.platformName,scaleFactor:t.capabilities.pixelRatio,virtual:!1};await cs(i,s,n,o,"RUNNING",{device:m})}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:s,directConnectPort:n,directConnectPath:o}=e;if(t&&s&&n&&o)return`${t}://${s}:${n}${o}`}async runTestOnce(e,t){let s=re(),{sessionPlayer:n}=t,o=t.driver,i=s.manifestVersion||"runner";Q.onWaitToTestComplete(this.id,this.isCodeMode),n.playbackManager.executionId=e.executionId,n.playbackManager.executionName=e.executionName;let a=this.getDirectAddressConnection(o.activeSession.capabilities)||this.getServerAddressFromGrid(),c=new Vy.JSDOM("").window.DOMParser;n.playbackManager.appiumSessionData={env:"remote",capabilities:o.activeSession.capabilities,sessionId:o.activeSession.sessionId},n.playbackManager.appiumApi=new s.AppiumApi(a,o.activeSession.sessionId,c),s.localAssetService&&s.localAssetService.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let p=await new Promise((g,f)=>n.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,i,g,!1,this.overrideTestConfigId,this.branch,!1,e.remoteRunId,void 0,void 0,void 0).catch(f));return s.localAssetService&&await s.localAssetService.drain(),p.stepsResults=null,p.resultId=this.testResultId,{...p,...e.seleniumPerfStats.getStats()}}catch(d){throw Vn.error("error while running appium tests",{err:d}),d}};try{return await super.runTestOnce(e,t),await u.call(this)}catch(d){throw Vn.error("failed to run test once",{err:d}),d}}}});var va,zy=T(()=>{"use strict";U();Cn();q();va=class{constructor(e){this.id=e;this.driver=new Nr}async onDone(){try{await te(this.driver.end(),12e4)}catch(t){t instanceof Y&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Ky,Ea,Jy=T(()=>{"use strict";Ky=E(require("ws"));U();Ea=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 Ky.default(this._cdpUrl,{timeout:e}),s=pt(o=>{t.once("open",o)}),n=pt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([s,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),s=this._cdpCallbacks.get(t.id);s&&(this._cdpCallbacks.delete(t.id),t.error?s.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?s.reject(new Error(t.result.exceptionDetails.exception.description)):s.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,s){let n=await this.initCDPWebsocket();this._lastWsId||(this._lastWsId=0);let o=this._lastWsId++,i=new Promise((c,u)=>{this._cdpCallbacks.set(o,{resolve:c,reject:u})}),a={method:e,params:t,id:o};return s&&Object.assign(a,{sessionId:s}),n.send(JSON.stringify(a)),i}}});var Ra,yd,Sa,Yy=T(()=>{"use strict";U();Ra=E(require("chrome-launcher"));Ei();Jy();hn();yd=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ea}async init(e,t,s,n,o,i,a,c,u,d){var f,h,y,b;let p=vi(e,t,s,n,o,i,a),m=[...((f=p.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((b=(y=(h=p.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:b.args)??[],...Ra.Launcher.defaultFlags().filter(I=>I!=="--disable-extensions")];this.chrome=await Ra.launch({chromeFlags:m,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await Ir(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),ls(()=>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}},Sa=class{constructor(e){this.id=e;this.sessionId=z();this.driver=new yd(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Xy={};W(Xy,{WorkerExtension:()=>qn});var wt,qn,bd=T(()=>{"use strict";Oe();q();ya();U();j();Bt();ae();zy();Yy();wt=x("worker-ext"),qn=class extends Ct{initPlayer(){return this.options.useChromeLauncher?new Sa(this.id):new va(this.id)}async _getBrowserOnce(e,t,s,n){var i;let{driver:o}=s;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw wt.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,s,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,s,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async runTestOnce(e,t){let{testResultId:s,executionId:n,testId:o}=this;_("WorkerExtension runTestOnce");let i=async d=>{let p=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await te(e.runTestUsingCDP(d.cdpTestRunner),p,$e.TEST_START_TIMEOUT_MSG)}catch(m){if(!(m instanceof Y))throw m;return wt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:s}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,p,m)=>{try{let g=await d.url(p);return m.driverUrlFinished=!0,g}catch(g){throw wt.error("error from driver.url",{err:g,testResultId:s,executionId:n,testId:o,url:p,urlLength:p.length}),g}},c=async d=>{let p=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,p},u=async()=>{var g;if(_("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw wt.warn("failed to run test via CDP",{err:f}),f}}let{driver:p}=t,m={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await te(Promise.all([a(t.driver,f,m),c(m)]),this.options.testStartTimeout,$e.TEST_START_TIMEOUT_MSG)}catch(y){if(!(y instanceof Y))throw y;wt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:s,executionId:n,testId:o,...m}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id,this.isCodeMode);let h=y=>{throw e.onCompletedCleanup(),wt.warn("on browser closed error detected",{err:y,testResultId:s,executionId:n,testId:o}),p.unregisterToClosedBrowser(h),y.type=Ks.BROWSER_CLOSED,y};p.registerToClosedBrowser(h);try{let y=await te(e.onCompleted(),this.testRunTimeout,$e.TEST_COMPLETE_TIMEOUT_MSG);p.unregisterToClosedBrowser(h),this.lambdatestService.isLambdatestRun()&&await p.executeJS(`lambda-status=${y.success?"passed":"failed"}`).catch(()=>{}),p.isAlive()||(wt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),y.gridIssues="could not validate grid is alive");let b=p.maxKeepAliveGap();return b>=3e4&&(wt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),y.keepAliveIssue=b),{...y,...e.seleniumPerfStats.getStats()}}catch(y){throw wt.warn("timeout wait until test completed",{err:y,testResultId:s,executionId:n,testId:o}),new Error(y)}finally{p.unregisterToClosedBrowser(h)}}catch(f){throw wt.warn("failed to start url",{err:f}),new Error(f)}};t.driver.start();try{return await super.runTestOnce(e,t),_("WorkerExtension super.runTestOnce"),await u()}catch(d){throw wt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Qy={};W(Qy,{WorkerExtensionSingleBrowser:()=>wd});var US,jS,wd,Zy=T(()=>{"use strict";Oe();U();j();ud();Bt();bd();US=x("base-worker"),jS=500,wd=class extends qn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Wn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,s,n,o){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,s,n,o)}async getTestPlayer(t,s){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(US.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,s)),this.testPlayer}async runTest(t,s,n){let o=this.handleQuarantine(t);if(o)return o;_("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,s);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await se(jS)}}});function BS(r,e){e===0?r():setTimeout(r,e*zd)}var Td,Ia,eb=T(()=>{"use strict";Cn();U();le();Oe();au();It();Su();q();j();ae();Ly();Td=x("parallel-worker-manager"),Ia=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e){case J.SELENIUM:return(jy(),ie(Uy)).WorkerSelenium;case J.APPIUM:return(Hy(),ie(qy)).WorkerAppium;default:return Pi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Zy(),ie(Qy)).WorkerExtensionSingleBrowser:(bd(),ie(Xy)).WorkerExtension}}createWorkers(e,t,s,...n){let o=this.getWorkerType(s),i=()=>{try{return _("before new Worker",s),new o(t,...n)}finally{_("after new Worker",s)}};return Array.from(new Array(e),i)}async runTests(e,t,s,n,o,i,a,c,u){if(e&&e.length===0)return;let d=!1,p=0,m=g=>new Promise(f=>{var kt,qr,C,D,F,G;let h=o.project,y=new ga(s,n,e,o,i,t),b={},I=e.length,w=(kt=o.company)==null?void 0:kt.companyId,v=(qr=o.company)==null?void 0:qr.name,R=o.source||"cli",k=o.user,L=(C=o.company)==null?void 0:C.planType,S=(D=o.company)==null?void 0:D.isStartUp,O=(F=o.projectData)==null?void 0:F.name,A=(G=o.projectData)==null?void 0:G.type,N=o.lightweightMode,B=Er(o),V=(me,et,we,Da,Hn,Na)=>(p++,jf({executionId:s,projectId:h,testId:et,resultId:we,companyId:w,companyName:v,projectName:O,companyPlan:L,sessionType:B,source:R,user:k,lightweightMode:N,isStartUp:S,projectType:A,appSource:Na}),t.testStartAndReport(me,s,we,Da,Hn)),X=async(me,et,we,Da,Hn,Na)=>{var kd,_d,Od;p--;let Tt={...(N==null?void 0:N.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...o.host&&{gridHost:o.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),o.grid||o.gridId?(Tt.gridName=o.grid||((kd=o.gridData)==null?void 0:kd.name),Tt.gridType=(_d=o.gridData)==null?void 0:_d.type,Tt.gridProvider=(Od=o.gridData)==null?void 0:Od.provider):o.useLocalChromeDriver?(Tt.gridName="local-chrome-driver-from-options",Tt.gridType="local-chrome"):o.useChromeLauncher?(Tt.gridName="chrome-launcher-from-options",Tt.gridType="local-chrome"):o.browserstack?Tt.gridName="browserstack-from-options":o.saucelabs&&(Tt.gridName="saucelabs-from-options"),await t.testEndAndReport(me,we,s,Da,Hn,Tt).catch(nw=>Td.error("testEndAndReport threw an error",{err:nw})),Hn)return;b[we.resultId]=we,Bf({executionId:s,projectId:h,testId:et,resultId:we.resultId,result:we,companyId:w,companyName:v,projectName:O,companyPlan:L,sessionType:B,source:R,user:k,lightweightMode:N,logger:Td,isStartUp:S,projectType:A,appSource:Na}),u&&!we.success&&(y.stop(),d=!0),(Object.keys(b).length===I||d&&p===0)&&f(b)},Z=(me,et)=>{b[et.resultId]=et,t.onTestIgnored(me,et.resultId),p--,(Object.keys(b).length===I||d&&p===0)&&f(b)},fe=(me,et)=>t.onGridSlot(me,et);o.userData={loginData:Object.assign({},Ft(),{refreshToken:Oo(),authData:Ft(),token:g}),projectId:o.project,company:o.company,servicesUrl:he},_("in localStrategy before createWorker"),this.createWorkers(c,y,o.mode,o,this.customExtensionLocalLocation,s,V,X,fe,Z).forEach((me,et)=>{_("before schedule worker.run after createWorkers"),BS(()=>{_("right before worker.run"),me.run()},et)})});try{let g=await Kt(),f=await m(g);if(d)throw new _t;return f}catch(g){throw Td.error("failed running parallel workers",{executionId:s,err:g}),g}}}});var xa,tb=T(()=>{"use strict";Mi();xa=class extends or{init(e){return super.initNewSocket(e,"real-data")}emitJoinRoom(e,t){this._socket.emit("testResult:listen",{query:`projectId=${t}&runId=${e}`})}joinToTestResultsByRunId(e,t){this.joinRoom(e,t),this.emitJoinRoom(e,t)}stopListenToTestResultsByRunId(e){this.leaveRoom(e),this._socket.emit("testResult:listen:stop",{})}listenToTestResultsByRunId(e){function t(s){e(s.data)}this._socket.on("testResult:changes",t.bind(this))}}});var vd,Ed,Pa,rb=T(()=>{"use strict";_n();ae();ye();tb();({TEST_RESULT_CREATED:vd,TEST_RESULT_UPDATED:Ed}=rt),Pa=class{constructor(){M.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new xa)}init(e){return M.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled())return We.addFilter(e,{runId:e},[Ed,vd],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(M.flags.useNewWSCLI.isEnabled()){We.removeFilter(e,[Ed,vd]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(M.flags.useNewWSCLI.isEnabled()){We.listenTo(e,[Ed,vd],s=>s.runId===e,s=>t(s));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function ob(r,e){var t;if((t=r.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&r.testId)return{tests:[r.testId.map(n=>({testId:n,testConfig:{},resultId:z()}))]};if(r.files.length>0){let{buildCodeTests:s}=await Promise.resolve().then(()=>(Yu(),ry)),n={};if(r.webpackConfig){let o=nb.join(process.cwd(),r.webpackConfig);n=require(o)}return s(r.files,n,{baseUrl:r.baseUrl})}return await Vc({projectId:r.project,labels:r.label,testIds:r.testId,testNames:r.name,testConfigNames:r.testConfigNames,suiteNames:r.suites,suiteIds:r.suiteIds,branch:e,rerunFailedByRunId:r.rerunFailedByRunId,testConfigIds:r.testConfigIds,intersections:r.intersections})}function Sd(r){let e=Object.keys(r).length,t=Object.keys(r).reduce((s,n)=>s+(r[n].success===!0?1:0),0);return e===t}async function Rd(r,e){let t=r.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],s=sb.difference(Js(r,e),t);if(s.length>0)throw gt("invalid-config-run",{browser:s.join(", "),mode:"runner"}),new P(`browser type <${s}> is not supported in ${r.mode} mode.`);return e}var sb,nb,ib=T(()=>{"use strict";sb=E(require("lodash")),nb=E(require("path"));U();ds();Te();q()});var Wr,ab,$S,Aa,WS,Ca,cb=T(()=>{"use strict";Wr=E(require("lodash"));U();j();le();ae();Oe();gs();Vl();au();Te();It();Bt();rg();q();eb();rb();ib();({testRunStatus:ab,CLI_MODE:$S}=Nt),Aa=x("test-plan-runner"),WS=1e3*60*5,Ca=class{constructor(e){this.startTime=Date.now();this.workerManager=new Ia(e)}async runTestAllPhases(e,t,s,n,o,i,a,c){let u={},d=Ft(),p=async()=>{let y=o.beforeParallel||1,b=!0,I=await this.workerManager.runTests(e,c,i,a,o,n,d,y,b);Object.assign(u,I)},m=async()=>{let y=oo||o.parallel,b=!1;_("right before this.workerManager.runTests");let I=await this.workerManager.runTests(t,c,i,a,o,n,d,y,b);_("right after this.workerManager.runTests"),Object.assign(u,I)},g=async()=>{let y=o.afterParallel||1,b=!1,I=await this.workerManager.runTests(s,c,i,a,o,n,d,y,b);Object.assign(u,I)},f=Er(o);$f({executionId:i,projectId:o.project,sessionType:f}),_("right before runBeforeTests");try{return await p(),_("right before runTestPlanTests"),await m(),_("right after runTestPlanTests"),await g(),u}catch(y){if(Aa.error("error running test plan",{err:y}),y instanceof _t)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw y}finally{await h()}async function h(){var b,I,w,v;if((b=o.lightweightMode)!=null&&b.disablePixelValidation)return;if(o.mode===$S.SELENIUM){let{EyeSdkBuilder:R}=(await Promise.resolve().then(()=>(Ee(),kr))).getSessionPlayer();await R.closeBatch(i);return}let y;try{if(!((v=(w=(I=o.company)==null?void 0:I.activePlan)==null?void 0:w.premiumFeatures)!=null&&v.applitools)||(y=await al(o.project),Wr.default.isEmpty(y)||!i))return;let{runKey:R,url:k}=y;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:k,apiKey:R}})}catch{}}}async initRealDataService(e){let t=new Pa;return await t.init(e),t}async listenToTestCreatedInFile(e,t,s,n){let o={};e.joinToTestResultsByRunId(s,t);let i=!0;return await new Promise(c=>{let u=d=>{i=!1,c(d)};e.listenToTestResultsByRunId(s,d=>{let p=d.id;if(!n.getTestResult(p)){let f=o[p],h=Wr.default.merge({},f,d,{resultId:p});if(o[p]=h,!f||f.status!==d.status){let b=(n.getTestResult(h.parentResultId)||{workerId:1}).workerId;[ab.RUNNING].includes(d.status)&&Q.onTestStarted(h,b),[ab.COMPLETED].includes(d.status)&&(h.duration=h.endTime-h.startTime||0,Q.onTestFinished(h,b))}}let m=!Object.values(o).some(f=>["QUEUED","RUNNING"].includes(f.runnerStatus)),g=!Object.values(n.getAllTestResults()).some(f=>["QUEUED","RUNNING"].includes(f.status));if(m&&g)return u(Object.values(o));if(g&&!m)return se(1e4).then(()=>{i&&u(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,s){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,s)}async runTestPlan(e,t,s,n,o,i,a,c){var k,L,S;let u=z(),d=n.project;Ka(u),e.forEach(O=>Object.assign(O,{isBeforeTestPlan:!0})),s.forEach(O=>Object.assign(O,{isAfterTestPlan:!0}));let p=[...e,...t,...s],m=new Ti(p,n,i,a),g=Wr.default.chain(p).map(O=>{var A;return((A=O.overrideTestConfig)==null?void 0:A.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=n.files.length>0,y=(k=n.lightweightMode)!=null&&k.onlyTestIdsNoSuite?[]:p.map(O=>O.name),b=(L=n.lightweightMode)!=null&&L.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:s}:m.executionStart(u,d,this.startTime,o,y),I;h&&(I=this.initRealDataServiceAndListenToTestsCreatedInFile(d,u,m)),_("before testListInfoPromise");let w=await b;(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Q.onTestPlanStarted(w.beforeTests,w.tests,w.afterTests,o,u,c,f,h),_("before runTestAllPhases");let v=await this.runTestAllPhases(w.beforeTests,w.tests,w.afterTests,a,n,u,o||"All Tests",m),R=await te(I,WS).catch(async()=>{var A;Aa.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:d,executionId:u});let O=await mn(d,"testResult",`runId=${u}&sort=runOrder`);return Wr.default.chain(((A=O==null?void 0:O.data)==null?void 0:A.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return _("before executionEnd"),await m.executionEnd(u),_("after executionEnd"),{results:v,executionId:u,testPlanName:o,configName:f,childTestResults:R}}async runTestPlans(e,t){Aa.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function s(d){return Wr.default.flattenDeep(Object.values(d)).reduce((p,m)=>p.concat(m.beforeTests,m.tests,m.afterTests),[])}let n={},o={},i=e.project,a=await Gc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,u=a.testPlansData;if(!c||c.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!u||Object.keys(u).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return await Rd(e,s(u)),await de(c,async d=>{let p=d.testPlanId;n[p]={};let m=Object.assign({},e);m.baseUrl=e.baseUrl||d.startUrl,m.host=e.host,m.port=e.port,m.gridId=e.gridId||d.gridId,e.grid&&delete m.gridId,m.gridData=await vf(e,d);let g=m.overrideExecutionName||d.name;return await de(u[p],async f=>{let h=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,m,g,p,t),y=e.files.length>0;Q.onTestPlanFinished(h.results,d.name,this.startTime,h.executionId,!1,y,h.childTestResults),n[p][h.executionId]=h.results;let b=Object.keys(n[p]).map(R=>({executionId:R,status:Sd(n[p][R])})),I=Object.keys(n[p]).map(R=>n[p][R]).reduce((R,k)=>Object.assign(R,k),{}),w=Sd(I);Object.assign(o,I);let v=w?b[0].executionId:b.find(R=>!R.status).executionId;return await Bc(i,p,{success:w,executions:b,executionId:v}),h})})}async runAnonymousTestPlan(e,t){var a;Aa.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),_("before getSuite");let s=await ob(e,t);if(_("after getSuite"),!((a=s==null?void 0:s.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in s&&s.branch||t;let n=s;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return _("Right before validateConfig + runAnonymousTestPlan tests map"),await de(s.tests,async c=>{if(e.resultId){let p=c[0];p.resultId=e.resultId,c=[p]}await Rd(e,c),_("right before runTestPlan");let u=await this.runTestPlan([],c,[],e,o,null,t,i);_("right after runTestPlan");let d=e.files.length>0;return await Q.onTestPlanFinished(u.results,o,this.startTime,u.executionId,i,d,u.childTestResults),u})}async run(e){let t=Sn(),s=[];Ys(e)?s=await this.runTestPlans(e,t):s=await this.runAnonymousTestPlan(e,t);let n=Wr.default.flattenDeep(s);return _("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),_("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var ub={};W(ub,{init:()=>cR,run:()=>iR});function VS(r){if(!Id.get(r,"company.activePlan.premiumFeatures.allowCLI")){let t=r.project;us(r.authData.uid,"cli-not-supported",{projectId:t}),console.warn("Testim CLI is not supported in this plan")}}async function qS(r){let e=r.project,t=await Hc(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"),us(r.authData.uid,"execution-quota-surpassed",{projectId:e}),new Yr}function HS(r,e){var o,i,a,c;if(fo(e.activePlan)==="free"){let u=r.parallel||1,d=((i=(o=e.activePlan)==null?void 0:o.premiumFeatures)==null?void 0:i.concurrency)||1;if(u>d)throw new P(`Cannot run with parallel ${r.parallel}. Max parallel value is ${d}`)}let s=r.retentionDays;if(!s)return;let n=(c=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:c.resultRetention;if(s>n)throw new P(`Retention days (${s}) cannot be greater than the company's retention days (${n}). Run aborted`)}async function zS(r){var e;if(!((e=r.lightweightMode)!=null&&e.disableQuotaBlocking))try{await Promise.all([qS(r),VS(r)])}catch(t){if([P,Yr].some(s=>t instanceof s))throw t;GS.error("could not validate cli account",{err:t})}}function KS(r){let e=Ft();return Rm({userId:e.uid,name:e.uid,traits:{projectId:r,company:{id:r,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function JS(r,{disableResults:e=!1,disableRemoteStep:t=!1}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return We.connect(r);if(!t){let{remoteStepService:s}=await Promise.resolve().then(()=>(ma(),xy));await s.init(r)}if(!e){let{testResultService:s}=await Promise.resolve().then(()=>(As(),qg));s.init(r)}}function YS(r,e){let{branch:t,autoDetect:s}=r;if(If(e,s),!e&&!s)throw new P(`branch ${t} does not exist, run aborted.`)}async function XS(r){let{project:e}=r,t=Sn();Id.get(r,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(r.sfdcCredential=await Uc({projectId:e,branch:t}))}function QS(r,e){let{onprem:t,id:s,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:p,extensionPath:m,ext:g,playerPath:f}=r;if([J.SELENIUM].includes(p)&&!f)throw new P("in selenium on prem mode --player-path must be provided");if(p==="extension"&&!m&&!g)throw new P("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),u=Boolean(a.isStartUp),d=fo(a);d==="free"&&(r.newBrowserWaitTimeout=r.newBrowserWaitTimeout<lb?lb:r.newBrowserWaitTimeout),M.setCompanyId(s),M.setIsPOC(c),M.setIsStartUp(u),M.setPlanType(d),Pt.setPlanType(d),r.company={companyId:s,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:d,isPOC:c,isStartUp:u,activePlan:a}}function ZS(r,e){if(zr){r.editorUrl=zr;return}r.editorUrl=e.editorUrl}function eR(r,e){r.allGrids=e}function tR(r,e){r.authData=e}function rR(r,e){let{id:t,name:s,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),r.projectData={projectId:t,type:n,name:s,defaults:o}}async function sR(r){r.gridData=await Ef(r)}async function nR(r){let{project:e}=r,t={projectId:e};r.overrideMappingFile&&(gt("user-override-file",t),r.mockNetworkRules=await pm(r.overrideMappingFile))}async function oR(r,e){_("in runner.js runRunner");let{project:t,remoteRunId:s,useLocalChromeDriver:n,useChromeLauncher:o}=r;s||(r.source=n||o?"cli-local":"cli"),await Ym(),_("in runner.js after checkNpmVersion"),await zS(r),_("in runRunner before tunnel.connect"),await si(r),_("in runRunner after tunnel.connect");let a=await new Ca(e).run(r);return _("before tunnel.disconnect"),await ni(r),await vn.end(t),_("after tunnel.disconnect and gridService.keepAlive.end"),a}function aR(r){var e;Pt.shouldShowFreeGridRunWarning((e=r.gridData)==null?void 0:e.type)&&console.log(`
|
|
564
564
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
565
565
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
566
|
-
`)}async function cR(r){var
|
|
567
|
-
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`),vn.start(e),KS(e),await nR(r),await sR(r),aR(r);let f=Sn();await Q.setOptions(r,f)}var Id,lb,GS,iR,db=T(()=>{"use strict";Id=E(require("lodash"));U();
|
|
566
|
+
`)}async function cR(r){var h,y,b;_("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:s,mode:n,disableSockets:o}=r,i=M.fetch(),a=JS(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(s||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{}),a.catch(()=>{});let{authData:c,editorConfig:u,companyByProjectId:d,projectById:p,branchName:m,allGrids:g}=await fn(r);if(HS(r,d),await Promise.all([i,a]),r.browser&&M.flags.dec2022eolBrowsers.isEnabled()){let I=en(r.browser);if(I.eol)throw new P(`Unsupported browser: ${I.browserName}`)}_("after featureFlagsReady and socketConnected"),ZS(r,u),QS(r,d),rR(r,p),YS(r,m),eR(r,g),tR(r,c),await XS(r),(h=r.lightweightMode)!=null&&h.disableLabs||await Pi.loadLabFeatures(p.id,d.activePlan),((y=r.lightweightMode)==null?void 0:y.type)==="turboMode"&&(M.flags.highSpeedMode.getValue()==="disabled"||r.company.planType==="free")&&delete r.lightweightMode,((b=r.lightweightMode)==null?void 0:b.type)==="turboMode"&&console.log(`
|
|
567
|
+
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`),vn.start(e),KS(e),await nR(r),await sR(r),aR(r);let f=Sn();await Q.setOptions(r,f)}var Id,lb,GS,iR,db=T(()=>{"use strict";Id=E(require("lodash"));U();Nl();Wl();Oe();gs();ds();Vl();Te();It();j();Bt();le();ae();q();cb();_n();Su();ye();In();hl();lb=30*60*1e3,GS=x("runner");iR=oR});function pb(r){r.get("/",(e,t)=>{let s=xd();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:s})}),r.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Dl()})}),r.get("/loginInfo",(e,t)=>{try{let s=JSON.parse(Buffer.from(e.query.info,"base64").toString());Il({overwriteExisting:!1,projects:s}),t.status(200).end()}catch{t.status(400).end()}})}var mb=T(()=>{"use strict";ps();Pd();Nl()});function hb(r){let e=(0,gb.Router)();return e.post("/run",(t,s)=>{var a;if(!((a=t.body)!=null&&a.step)){s.status(400).send({error:"Missing step"});return}let{step:n,context:o,loginData:i}=t.body;if(!(r!=null&&r.webdriverApi)){s.status(503).send({success:!1,reason:"Testim Agent was not started with Testim Start."});return}t.setTimeout(0),ks(n,o,r.webdriverApi,i,void 0,"agent").then(c=>{s.status(200).send(c)}).catch(c=>{fb.error("failed to run hybrid code",{e:c}),s.status(500).send(Object.assign({success:!1,error:c}))})}),e.post("/abort",(t,s)=>{var n;if(!((n=t.body)!=null&&n.stepResultId)){s.status(400).send({error:"missing stepResultId"});return}try{od(t.body.stepResultId),s.status(204).end()}catch(o){if(o&&o.message==="No such stepResultId"){s.status(400).send({error:"No such stepResultId"});return}fb.error("hybrid code abort unexpected error",{e:o}),s.status(500).send({error:"unexpected error",info:`${o?o.message:"N/A"}`})}}),e}var gb,fb,yb=T(()=>{"use strict";na();gb=require("express");j();fb=x("hybrid-router")});var bb,Gr,wb,Tb=T(()=>{"use strict";bb=require("express");j();rd();Gr=(0,bb.Router)(),wb=x("codim-router");Gr.get("/tests",async(r,e)=>{let t=await Xu();e.json({tests:t,success:!0})});Gr.get("/locators",async(r,e)=>{let t=await jn(),s=await Qu(t,Boolean(r.query.full));e.json({locators:t,contents:s,success:!0})});Gr.post("/locators",async(r,e)=>{if(!r.body){e.status(400).send({success:!1,reason:"missing body"});return}if(!r.body.locators){e.status(400).send({success:!1,reason:"missing locators"});return}let{locators:t,mergeIntoExisting:s}=r.body;await ed(t,{mergeIntoExisting:s||!1}),e.status(200).send({success:!0})});Gr.get("/compile",async(r,e)=>{try{let t=await td(r.body.name);e.send({success:!0,code:t})}catch(t){wb.error(t),e.json({success:!1,reason:t.message})}});Gr.post("/saveTest",async(r,e)=>{if(!r.body){e.status(400).send({success:!1,reason:"missing body"});return}try{await Zu(r.body),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),wb.error(t)}})});var Ad,vb,Ns,ka,Eb=T(()=>{"use strict";Ad=E(require("chalk"));Fr();vb=require("express");j();q();Ns=x("cli-router"),ka=(0,vb.Router)();ka.post("/run",async(r,e)=>{let{code:t,stepId:s,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:c,timeout:u,fileDataUrl:d}=r.body;if(typeof t!="string"||!s||!n||!o||!i||typeof a!="number"||!c||typeof u!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let p=await Es(t,s,n,o,i,a,c,u,d);p.success||(console.log(Ad.default.red(p.result.resultValue)),Ns.error("CLI Action Failure",{message:p.result.resultValue})),e.status(200).json({success:!0,data:p})}catch(p){Ns.error("failed to run cli code",{err:p}),console.log(Ad.default.red("failed to run cli code",p)),e.status(500).json({success:!1,code:"internal-error"})}});ka.post("/install",async(r,e)=>{let{stepId:t,testResultId:s,retryIndex:n,packageData:o,stepResultId:i,timeout:a}=r.body;if(!t||typeof o!="object"||!s||typeof n!="number"||!i||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let c=await vs(t,s,n,o,i,a);Ns.info("installed packages successfully"),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof dt){Ns.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 Y){Ns.error("timeout installing node package"),e.status(200).json({success:!1,code:"timeout"});return}Ns.error("failed to install node packages",{err:c}),e.status(500).json({success:!1,code:"internal-error"})}})});var lR,Sb=T(()=>{"use strict";Fr();j();Eb();lR=x("cli-service");Pg().catch(r=>lR.warn("failed to clean local package folder",{err:r}))});async function uR(r,e,t="utf8"){let s=xb.join(Ib.tmpdir(),r);return await Rb.promises.writeFile(s,e,t),s}async function pR({code:r}){let e=Date.now();try{let t=`
|
|
568
568
|
module.paths = ${JSON.stringify(module.paths)};
|
|
569
569
|
process.on('unhandledRejection', (error) => {
|
|
570
570
|
process.send({type: 'unhandledRejection', error: {message: error.message, stack: error.stack}});
|
|
@@ -575,12 +575,12 @@ Turbo mode will ignore step delays. Test artifacts like screenshots and logs wil
|
|
|
575
575
|
process.exit(1);
|
|
576
576
|
});
|
|
577
577
|
${r};
|
|
578
|
-
`,s=await uR(`tst-playground-${Date.now()}.js`,t),n=dR(s);Vr[e]=n.child;let{error:o,exitCode:i}=await n;if(o)throw o;if(i!==0)throw new Error(`Process exited with exit code: ${i}`);return}finally{Vr[e]&&(Vr[e].kill(),delete Vr[e])}}async function Cb({code:r,type:e}){if(["playwright","puppeteer","selenium"].includes(e))return pR({code:r});throw new
|
|
578
|
+
`,s=await uR(`tst-playground-${Date.now()}.js`,t),n=dR(s);Vr[e]=n.child;let{error:o,exitCode:i}=await n;if(o)throw o;if(i!==0)throw new Error(`Process exited with exit code: ${i}`);return}finally{Vr[e]&&(Vr[e].kill(),delete Vr[e])}}async function Cb({code:r,type:e}){if(["playwright","puppeteer","selenium"].includes(e))return pR({code:r});throw new hr}async function kb(){Object.keys(Vr).forEach(r=>{Vr[r].kill(),delete Vr[r]})}var Rb,Ib,xb,Pb,Ab,Vr,dR,_b=T(()=>{"use strict";Rb=E(require("fs")),Ib=E(require("os")),xb=E(require("path")),Pb=require("child_process");q();Ab=["playwright","selenium","puppeteer"],Vr={};dR=r=>{let e,t=new Promise(n=>{e=n}),s=(0,Pb.fork)(r,{stdio:["inherit","inherit","inherit","ipc"]});return t.child=s,s.on("message",n=>{if(!n)return;let{type:o,error:i}=n;i&&["uncaughtException","unhandledRejection"].includes(o)&&e({error:Object.assign(new yr,{innerStack:n.error.stack})})}),s.on("error",n=>{e({error:n})}),s.on("exit",n=>{e({exitCode:n})}),t}});var Db,_a,Nb,Ob,Lb,mR,Mb=T(()=>{"use strict";Db=require("express");j();q();le();_b();_a=(0,Db.Router)(),Nb=x("playground-router"),Ob=["localhost","app.testim.io","playground.testim.io","staging.testim.io","app.staging.testim.cc","tta-crm.tricentis.com"],Lb=r=>{if(!r)return{};try{return new URL(r)}catch{return{}}},mR=(r,e,t)=>{if(ro)return t();let s=r.headers.referer,n=r.headers.origin;if(!s&&!n)return e.status(400).send();let o=Lb(s),i=Lb(n);return!Ob.includes(o.hostname)&&!Ob.includes(i.hostname)?e.status(400).send():t()};_a.post("/run",[mR],async(r,e)=>{let t=r.body||{},{code:s,type:n}=t;if(!s||!Ab.includes(n)){e.status(400).send({success:!1,reason:"missing arguments"});return}try{await Cb(t),e.send({success:!0})}catch(o){if(o instanceof hr){e.status(404).send({success:!1});return}if(o instanceof yr){e.json({success:!1,type:"playground-error",stack:o.innerStack});return}e.json({success:!1,reason:o.message}),Nb.error(o)}});_a.post("/stop",(r,e)=>{try{kb(),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),Nb.error(t)}})});function Ub(r){let e=(0,Fb.Router)();return e.get("/cdp-url",(t,s)=>{if(!r){s.status(503).send({error:"Testim standalone browser is not running"});return}s.status(200).send({url:r.webdriverApi.cdpUrl})}),e.get("/status",(t,s)=>{if(!r){s.status(503).send({ok:!1});return}s.status(200).send({ok:!0})}),e}var Fb,jb=T(()=>{"use strict";Fb=require("express")});var Gb={};W(Gb,{orchestrateRoutes:()=>fR});function fR(r,e){let t=(0,$b.default)();r(t),t.use(Cd.default.urlencoded({extended:!1,limit:"50mb"})),t.use((0,Wb.default)()),t.use(Cd.default.json({limit:"50mb"}));let n={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Le||ro?"*":["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,Bb.default)(n)),pb(t),t.use("/files",Gr),t.use("/playground",_a),t.use("/cliJs",ka),t.use("/standalone-browser",Ub(e)),t.use("/hybrid",hb(e)),t.use((o,i)=>{i.status(404).send("Endpoint Not Found")}),t}var Bb,$b,Cd,Wb,Vb=T(()=>{"use strict";Bb=E(require("cors")),$b=E(require("express")),Cd=E(require("body-parser")),Wb=E(require("compression"));mb();yb();Tb();Sb();Mb();jb();le()});var Hb={};W(Hb,{init:()=>gR});async function gR({agentPort:r,agentBind:e,project:t,token:s,installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i},a){await yR({installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i,project:t}),await hR({agentPort:r,agentBind:e,project:t,token:s},a)}async function hR({agentPort:r,agentBind:e,project:t,token:s},n){let{orchestrateRoutes:o}=await Promise.resolve().then(()=>(Vb(),Gb));return new Promise((i,a)=>{let c=()=>{};t&&(sm(t,s),c=g=>{g.use((f,h,y)=>{Object.assign(f,{project:t}),y()})});let u=o(c,n),d=qb.createServer(u);d.listen(r,e),d.on("error",p),d.on("listening",m);function p(g){if(g.syscall!=="listen")return a(g);switch(g.code){case"EACCES":case"EPERM":return a(new P(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return a(new P(`Port ${r} is already in use, is another Testim instance running?`));default:return a(g)}}function m(){let{port:g}=d.address();console.log(`Running on port: ${g}`),bR()}})}function yR({installPlaygroundPlaywrightDeps:r,installPlaygroundPuppeteerDeps:e,installPlaygroundSeleniumDeps:t,project:s}){let n=[];return r&&n.push(ge("playwright")),e&&n.push(ge("puppeteer")),t&&n.push(ge("selenium-webdriver"),Pr({projectId:s})),Promise.all(n)}async function bR(){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 qb,zb=T(()=>{"use strict";qb=E(require("http"));It();q();yt();is()});var ew={};W(ew,{getStartedWithStart:()=>xd,runAgentMode:()=>ER});async function ER(r){var s;let e;if(await Ar(r.playerLocation,r.canary),r.startTestimBrowser){await IR();try{e=await RR(r)}catch(n){throw(s=n==null?void 0:n.message)!=null&&s.includes("user data directory is already in use")?new P('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(zb(),Hb));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(la(),ie(Ku)));let o=["webpack"];for(let i of o)await ge(i,{silent:!0}).catch(()=>null)},6e3),t.init(r,e)}function xd(){return Qb}function Kb(r){try{return process.kill(r,0)}catch{return!1}}async function SR(r,e,t){let s=dr.join(Mt,`chrome-${cn}-process`),n=3e3,o=()=>{Ce.rmSync(s,{recursive:!0}),console.log(`
|
|
579
579
|
|
|
580
|
-
Browser session ended`),process.exit(0)};if(await be(s)){let
|
|
581
|
-
`).map(o=>o.trim()),s=Number.parseInt(e,10);if(!Number.isInteger(s)||s<1||s>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await Ir(`localhost:${s}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:s,webSocketDebuggerUrl:n}}async function PR(r,e=100){let t=await AR(r,e);return pt(s=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),s)})}async function AR(r,e=100){let t=new
|
|
582
|
-
`):""}overrideMimeType(t){if([Re.LOADING,Re.DONE].includes(this.readyState))throw new pr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let s=new Fs("readystatechange");this.dispatchEvent(s)}_sendFile(){throw this._url.method!=="GET"?new Qn("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||(t=""),this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let s=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,o=(this._url.protocol==="http:"?js:Ma).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:s});typeof t=="object"&&t instanceof Kn.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 Kn.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,s){if(this._request!==t)return;if([301,302,303,307,308].includes(s.statusCode)){this._url=this._parseUrl(s.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=s,this._response.on("data",o=>this._onHttpResponseData(s,o)),this._response.on("end",()=>this._onHttpResponseEnd(s)),this._response.on("close",()=>this._onHttpResponseClose(s)),this.status=this._response.statusCode,this.statusText=js.STATUS_CODES[this.status],this._parseResponseHeaders(s);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Re.HEADERS_RECEIVED)}_onHttpResponseData(t,s){if(this._response===t)return this._responseParts.push(s),this._loadedBytes+=s.length,this.readyState!==Re.LOADING&&this._setReadyState(Re.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Re.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let s=this._request;return this._setError(),s.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let s=new Fs(t);s.lengthComputable=this._lengthComputable,s.loaded=this._loadedBytes,s.total=this._totalBytes,this.dispatchEvent(s)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let s,n,o,i=this.nodejsBaseUrl===null?t:Us.resolve(this.nodejsBaseUrl,t),a=Us.parse(i,!1,!0);return a.hash=null,a.auth&&(typeof o<"u"&&o!==null||typeof n<"u"&&n!==null)&&(s=a.auth.indexOf(":"),s===-1?o||(o=a.auth):(o||(o=a.substring(0,s)),n||(n=a.substring(s+1)))),(o||n)&&(a.auth=`${o}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([s,n])=>{let o=s.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 s=new ArrayBuffer(t.length),n=new Uint8Array(s);for(let o=0;o<t.length;o++)n[o]=t[o];this.response=s;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"],s=/;\s*charset=(.*)$/.exec(t);return t&&s?s[1]:"utf-8"}},ke=Re;ke.SyntaxError=
|
|
580
|
+
Browser session ended`),process.exit(0)};if(await be(s)){let g=JSON.parse(Ce.readFileSync(s));if(Kb(g.pid)){let f=()=>Kb(g.pid)?setTimeout(f,n):o();return f(),{webdriverApi:g}}}let i=await Co();await be(Ms)||await Ce.promises.mkdir(Ms,{recursive:!0});let c=[...Zb(Ms,e,t,i).desiredCapabilities.chromeOptions.args,...La.Launcher.defaultFlags().filter(g=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(g))],u={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${r.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,p=await La.launch({chromeFlags:c,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:Ms,chromePath:i,envVars:u}),m={port:p.port,pid:p.pid,cdpUrl:await Ir(`localhost:${p.port}`)};return Ce.writeFileSync(s,JSON.stringify(m)),p.process.once("exit",o),p.process.once("close",o),{webdriverApi:m}}async function RR(r){let e=`${Yd}/extension/testim-full-master.zip`,t=dr.basename(e),s=dr.join(Mt,t),n=dr.join(Mt,`${t}__unzipped__`),o=!(r.ext||r.extensionPath);if(o&&await be(s)){let g=await Ce.promises.stat(s);o=Date.now()-TR>g.mtimeMs}if(await Ce.promises.mkdir(Mt,{recursive:!0}),o){let g=(0,Yb.default)("Downloading Testim Editor").start();await ze(e,s);try{await tt(s,n)}catch{await Ce.promises.rm(s,{recursive:!0,force:!0}),await ze(e,s);try{await tt(s,n)}catch{throw await Ce.promises.rm(s,{recursive:!0,force:!0}),g.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{r.downloadBrowser||await Ce.promises.rm(n,{recursive:!0,force:!0})}g.succeed()}let i=r.extensionPath?null:(await Ce.promises.readFile(r.ext||s)).toString("base64");if(r.downloadBrowser)return await SR(r,i,n);await Pr({projectId:r.project},{chromeBinaryLocation:r.chromeBinaryLocations});let a=Zb(Ms,i,r.extensionPath,r.chromeBinaryLocations),{WebDriver:c}=(Cn(),ie(Eg)),{SeleniumPerfStats:u}=(ys(),ie(Yf)),d=new c;d.seleniumPerfStats=new u;let p=await d.initClient(a);Qb=!0;let m=`${r.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(m),Object.assign(d,{initialUrl:m});try{d.cdpUrl=await Ir(p.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function Zb(r,e,t,s){let n=e?[e]:[],o=[`--user-data-dir=${r}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&o.push(`--load-extension=${t}`),{logLevel:wR,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:s},browserName:"chrome"},host:"localhost",port:9515}}async function IR(){if(await be(Oa))try{let{webSocketDebuggerUrl:r}=await xR();await PR(r),await Ce.promises.unlink(Oa)}catch(r){r&&r.message==="unable to connect to devtools http server"&&await Ce.promises.unlink(Oa)}}async function xR(){let r=await Ce.promises.readFile(Oa,{encoding:"utf8"}),[e,t]=r.split(`
|
|
581
|
+
`).map(o=>o.trim()),s=Number.parseInt(e,10);if(!Number.isInteger(s)||s<1||s>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await Ir(`localhost:${s}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:s,webSocketDebuggerUrl:n}}async function PR(r,e=100){let t=await AR(r,e);return pt(s=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),s)})}async function AR(r,e=100){let t=new Xb.default(r,{timeout:e}),s=pt(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=pt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([s,n]).then(()=>t)}var Jb,Yb,Xb,Ce,dr,La,wR,TR,Ms,vR,Oa,Qb,Pd=T(()=>{"use strict";Jb=E(require("ms")),Yb=E(require("ora")),Xb=E(require("ws")),Ce=E(require("fs")),dr=E(require("path")),La=E(require("chrome-launcher"));le();is();q();yt();_c();U();wR=no?"verbose":"silent",TR=(0,Jb.default)("1h"),Ms=dr.join(Mt,"profile"),vR="DevToolsActivePort",Oa=dr.join(Ms,vR);Qb=!1});var ED=require("source-map-support/register");var Dd;(Dd=Array.prototype).at||(Dd.at=function(r){let e=Number.isInteger(r)?r:0,t=e>=0?e:this.length+e;if(!(t<0||t>=this.length))return this[t]});var Nd=require("perf_hooks");var eo=E(require("os")),Us=E(require("url")),js=E(require("http")),Ma=E(require("https")),Kn=E(require("form-data")),Jn=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){var s;e=e.toLowerCase(),(s=this._listeners)[e]||(s[e]=[]),this._listeners[e].push(t)}removeEventListener(e,t){let s;e=e.toLowerCase(),this._listeners[e]&&(s=this._listeners[e].indexOf(t),s!==-1&&this._listeners[e].splice(s,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,s=this._listeners[t]||[];for(let o of s)o==null||o.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},Yn=class extends Jn{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(!(typeof t>"u"||t===null))if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let s=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let o=0;o<t.byteLength;o++)s[o]=n[o];this._body=s}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let s=Buffer.alloc(t.byteLength),n=t.byteOffset,o=new Uint8Array(t.buffer);for(let i=0;i<t.byteLength;i++)s[i]=o[i+n];this._body=s}else if(typeof t=="object"&&t instanceof Kn.default)this._body=null;else throw new Error(`Unsupported send() data ${t}`)}_finalizeHeaders(t,s){this._contentType&&!("content-type"in s)&&(t["Content-Type"]=this._contentType),this._body&&(t["Content-Length"]=this._body.length.toString())}_startUpload(t){this._body&&t.write(this._body),t.end()}},Fs=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}},Xn=class extends Error{},Qn=class extends Error{},Zn=class extends Error{},pr=class extends Error{},Re=class extends Jn{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=js.globalAgent;this.nodejsHttpsAgent=Ma.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 (${eo.type()} ${eo.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=Re.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new Yn(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){Re.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let s=t.baseUrl;if(s!==null&&!Us.parse(s,!1,!0).protocol)throw new Xn("baseUrl must be an absolute URL");this.nodejsBaseUrl=s}}open(t,s,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new Zn(`HTTP method ${t} is not allowed in XHR`);let o=this._parseUrl(s);n===void 0&&(n=!0),this._method=t,this._url=o,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(Re.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,s){if(this.readyState!==Re.OPENED)throw new pr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||/^sec-/.test(n)||/^proxy-/.test(n)||(s=s.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${s}`):(this._loweredHeaders[n]=t,this._headers[t]=s))}send(t){if(this.readyState!==Re.OPENED)throw new pr("XHR readyState must be OPENED");if(this._request)throw new pr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new Qn(`Unsupported protocol ${this._url.protocol}`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let s=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[s])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,s])=>`${t}: ${s}`).join(`\r
|
|
582
|
+
`):""}overrideMimeType(t){if([Re.LOADING,Re.DONE].includes(this.readyState))throw new pr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let s=new Fs("readystatechange");this.dispatchEvent(s)}_sendFile(){throw this._url.method!=="GET"?new Qn("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||(t=""),this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let s=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,o=(this._url.protocol==="http:"?js:Ma).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:s});typeof t=="object"&&t instanceof Kn.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 Kn.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,s){if(this._request!==t)return;if([301,302,303,307,308].includes(s.statusCode)){this._url=this._parseUrl(s.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=s,this._response.on("data",o=>this._onHttpResponseData(s,o)),this._response.on("end",()=>this._onHttpResponseEnd(s)),this._response.on("close",()=>this._onHttpResponseClose(s)),this.status=this._response.statusCode,this.statusText=js.STATUS_CODES[this.status],this._parseResponseHeaders(s);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Re.HEADERS_RECEIVED)}_onHttpResponseData(t,s){if(this._response===t)return this._responseParts.push(s),this._loadedBytes+=s.length,this.readyState!==Re.LOADING&&this._setReadyState(Re.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Re.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let s=this._request;return this._setError(),s.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Re.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let s=new Fs(t);s.lengthComputable=this._lengthComputable,s.loaded=this._loadedBytes,s.total=this._totalBytes,this.dispatchEvent(s)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let s,n,o,i=this.nodejsBaseUrl===null?t:Us.resolve(this.nodejsBaseUrl,t),a=Us.parse(i,!1,!0);return a.hash=null,a.auth&&(typeof o<"u"&&o!==null||typeof n<"u"&&n!==null)&&(s=a.auth.indexOf(":"),s===-1?o||(o=a.auth):(o||(o=a.substring(0,s)),n||(n=a.substring(s+1)))),(o||n)&&(a.auth=`${o}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([s,n])=>{let o=s.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 s=new ArrayBuffer(t.length),n=new Uint8Array(s);for(let o=0;o<t.length;o++)n[o]=t[o];this.response=s;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"],s=/;\s*charset=(.*)$/.exec(t);return t&&s?s[1]:"utf-8"}},ke=Re;ke.SyntaxError=Xn,ke.ProgressEvent=Fs,ke.SecurityError=Zn,ke.XMLHttpRequest=Re,ke.InvalidStateError=pr,ke.XMLHttpRequestUpload=Yn,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke,performance:Nd.performance,...typeof Blob>"u"&&{Blob:require("buffer").Blob}});var tw=E(require("semver"));Oe();hl();Ht();is();var rw=E(require("chalk")),sw=require("events");ae();hn();q();ae();Lo();j();var gm=E(require("os")),yl=E(require("path")),bl=E(require("chalk")),Bo=require("fs");function hm(r){var e,t,s;if(!((e=r==null?void 0:r.message)!=null&&e.includes("SIGINT")))try{let n=gm.homedir();(0,Bo.mkdirSync)(yl.resolve(n,".testim_logs"),{recursive:!0});let o=yl.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}`),(t=r==null?void 0:r.message)!=null&&t.includes("Unable to compile TypeScript")&&((s=r.stack)!=null&&s.includes("runner/src"))&&process.argv.some(i=>i.includes("player-require-path"))&&(console.log(bl.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(bl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Bo.writeFileSync)(o,`${r}
|
|
583
583
|
${r==null?void 0:r.stack}
|
|
584
584
|
|
|
585
|
-
${JSON.stringify(r,Object.getOwnPropertyNames(r),2)}`)}catch{}}sn();var _T=
|
|
585
|
+
${JSON.stringify(r,Object.getOwnPropertyNames(r),2)}`)}catch{}}sn();var _T=x("process-handler"),ym=!1;function OT(r){return r instanceof Error?1:ym?0:(r||(r={}),Object.values(r).some(({runnerStatus:t,success:s,testStatus:n,status:o})=>[t,o].includes(pe.SKIPPED)||[t,o].includes(pe.FAILED)&&n===Ke.EVALUATING?!1:s!==!0)?1:0)}function LT(){try{zt("chromedriver").stop()}catch{}}function bm(){ym=!0}async function wl(r){r!=null&&r.stack&&(as?console.error(r,r.stack):hm(r)),LT(),await _T.waitForFlush(),process.exit(OT(r))}Te();j();var CR=x("cli-entry");function kR(r){if(!tw.satisfies(process.version,r))throw new P(`Required node version ${r} not satisfied with current version ${process.version}`);let e=14,t=16,s=Number(process.versions.node.split(".")[0]),n=new Date("2023-04-30T00:00:00.000Z")<=new Date;if(s<e)throw new P(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(s<t&&n)throw new P(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);s<t&&console.log("\x1B[33m%s\x1B[0m",`Testim.io CLI will stop supporting Node.js < ${t} on April 30 2023, please upgrade to a newer Node.js version`)}async function _R(){console.log("Starting Testim.io CLI");let[r,e]=await Promise.all([Promise.resolve().then(()=>(U(),H)),Promise.resolve().then(()=>(Fm(),Mm))]);_("Starting Testim.io CLI"),fm(wl);try{kR(r.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{let t=await e.process();if(_("in main, after options.process"),Ya(global.proxyUri),"parallel"in t&&t.parallel>5&&(sw.EventEmitter.defaultMaxListeners=t.parallel*2),Ja(t.project),Dp("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),r.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(yt(),_l));return await o()}if(r.isInitCodimMode(t)){let{init:o}=await Promise.resolve().then(()=>(qm(),Vm));return o(t.initTestProject)}if(r.isLoginMode(t))return;if(r.isCreatePrefetchedDataMode(t)){await kp(),await fn(t);let{preloadTests:o}=await Promise.resolve().then(()=>(Jo(),zm));await o(t),!t.playerRequirePath&&t.mode!==J.EXTENSION&&await Ar(t.playerLocation,t.canary);let i=await Op();i.success?console.log(`created prefetched data at ${To()}`):console.error("failed to create prefetch data",i.error);return}let s=await Promise.resolve().then(()=>(db(),ub));if(r.isTunnelOnlyMode(t)){await s.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(Wl(),$l));await o(t);return}if(r.isAgentMode(t)){let{runAgentMode:o}=await Promise.resolve().then(()=>(Pd(),ew));return o(t)}if(t.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(du(),eg)),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&bm(),_("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([dm(t),s.init(t)]);return _("right after testRunner.init/prepareRunner.prepare"),await s.run(t,n)}catch(t){if(t instanceof mr)return;let s=r.getArgsOnRemoteRunFailure();return s&&await dl({...s,error:t.message}).catch(()=>{}),t instanceof P?(console.log(rw.default.red("Argument Error:",t.message)),t):t instanceof fr?(console.log("Selenium Error:",t.message),t):(console.log("Error:",t.message),CR.error("runner ended with unexpected error",{err:t}),t)}}_R().then(r=>{Array.isArray(r)&&r.length===0&&console.log("No tests ran"),wl(r)});
|
|
586
586
|
//# sourceMappingURL=cli.js.map
|