@testim/testim-cli 3.293.0 → 3.295.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -1,37 +1,37 @@
1
1
  #! /usr/bin/env node
2
- "use strict";var _T=Object.create;var ir=Object.defineProperty;var OT=Object.getOwnPropertyDescriptor;var LT=Object.getOwnPropertyNames;var NT=Object.getPrototypeOf,DT=Object.prototype.hasOwnProperty;var MT=(s,e,t)=>e in s?ir(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var F=(s,e)=>()=>(s&&(e=s(s=0)),e);var C=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),W=(s,e)=>{for(var t in e)ir(s,t,{get:e[t],enumerable:!0})},dd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of LT(e))!DT.call(s,n)&&n!==t&&ir(s,n,{get:()=>e[n],enumerable:!(r=OT(e,n))||r.enumerable});return s};var S=(s,e,t)=>(t=s!=null?_T(NT(s)):{},dd(e||!s||!s.__esModule?ir(t,"default",{value:s,enumerable:!0}):t,s)),w=s=>dd(ir({},"__esModule",{value:!0}),s);var Ue=(s,e,t)=>(MT(s,typeof e!="symbol"?e+"":e,t),t);var Ie=C((SL,In)=>{"use strict";var Sn=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,FT=Date.now(),fd=Date.now();In.exports={log(...s){if(!Sn)return;let e=Date.now();console.log(`${e-FT} ${e-fd} `,...s),fd=e},measure(s){if(!Sn)return;let e=Date.now();try{s()}finally{console.log(s.name,"took",Date.now()-e)}},patchPromisePrototype(){Promise.prototype.log=function(e){return Sn?this.then(t=>(In.exports.log(e),t)):this}},measureRequireTimes(){if(!Sn)return;let{performance:s,PerformanceObserver:e}=require("perf_hooks"),t=require("module");t.Module.prototype.require=s.timerify(t.Module.prototype.require),require=s.timerify(require);let r=new e(n=>{n.getEntries().sort((i,a)=>a.duration-i.duration).filter(i=>i.duration>1).forEach(i=>{console.log(`require('${i[0]}')`,i.duration)}),r.disconnect()});r.observe({entryTypes:["function"],buffered:!0})}};In.exports.patchPromisePrototype()});var Rn={};W(Rn,{EDGE_CHROMIUM_MIN_VERSION:()=>xn,SELENIUM_STATUS_CODES:()=>iE,UNICODE_CHARACTERS:()=>UT,W3C_ELEMENT_ID:()=>yi});var UT,yi,qT,jT,$T,hd,gd,yd,wd,BT,bd,Td,Ed,vd,WT,Sd,Id,xd,Rd,Cd,Pd,kd,Ad,GT,VT,_d,Od,HT,KT,zT,JT,XT,YT,QT,ZT,eE,tE,sE,rE,nE,oE,iE,xn,Es=F(()=>{"use strict";UT={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"},yi="element-6066-11e4-a52e-4f735466cecf",qT={id:"Unknown",status:-1,message:"Remote end send an unknown status code."},jT={id:"Success",status:0,message:"The command executed successfully."},$T={id:"NoSuchDriver",status:6,message:"A session is either terminated or not started"},hd={id:"NoSuchElement",status:404,message:"An element could not be located on the page using the given search parameters."},gd={id:"NoSuchFrame",status:400,message:"A request to switch to a frame could not be satisfied because the frame could not be found."},yd={id:"UnknownCommand",status:404,message:"The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource."},wd={id:"StaleElementReference",status:400,message:"An element command failed because the referenced element is no longer attached to the DOM."},BT={id:"ElementNotVisible",status:11,message:"An element command could not be completed because the element is not visible on the page."},bd={id:"InvalidElementState",status:400,message:"An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element)."},Td={id:"UnknownError",status:500,message:"An unknown server-side error occurred while processing the command."},Ed={id:"ElementIsNotSelectable",status:400,message:"An attempt was made to select an element that cannot be selected."},vd={id:"JavaScriptError",status:500,message:"An error occurred while executing user supplied JavaScript."},WT={id:"XPathLookupError",status:19,message:"An error occurred while searching for an element by XPath."},Sd={id:"Timeout",status:408,message:"An operation did not complete before its timeout expired."},Id={id:"NoSuchWindow",status:400,message:"A request to switch to a different window could not be satisfied because the window could not be found."},xd={id:"InvalidCookieDomain",status:400,message:"An illegal attempt was made to set a cookie under a different domain than the current page."},Rd={id:"UnableToSetCookie",status:500,message:"A request to set a cookie's value could not be satisfied."},Cd={id:"UnexpectedAlertOpen",status:500,message:"A modal dialog was open, blocking this operation"},Pd={id:"NoAlertOpenError",status:400,message:"An attempt was made to operate on a modal dialog when one was not open."},kd={id:"ScriptTimeout",status:408,message:"A script did not complete before its timeout expired."},Ad={id:"InvalidElementCoordinates",status:400,message:"The coordinates provided to an interactions operation are invalid."},GT={id:"IMENotAvailable",status:30,message:"IME was not available."},VT={id:"IMEEngineActivationFailed",status:31,message:"An IME engine could not be started."},_d={id:"InvalidSelector",status:400,message:"Argument was an invalid selector (e.g. XPath/CSS)."},Od={id:"SessionNotCreatedException",status:500,message:"A new session could not be created."},HT={id:"ElementNotScrollable",status:34,message:"Element cannot be scrolled into view."},KT={id:"SelectorTimeoutError",status:100,message:"Request timed out after the element was still found on the page."},zT={id:"NoSessionIdError",status:101,message:"A session id is required for this command but wasn't found in the response payload"},JT={id:"GridApiError",status:102,message:"A call to the Selenium Grid API failed"},XT={id:"ElementClickIntercepted",status:400,message:"The Element Click command could not be completed because the element receiving the events is obscuring the element that was requested clicked."},YT={id:"ElementNotInteractable",status:400,message:"A command could not be completed because the element is not pointer- or keyboard interactable."},QT={id:"InsecureCertificate",status:400,message:"Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate."},ZT={id:"InvalidArgument",status:400,message:"The arguments passed to a command are either invalid or malformed."},eE={id:"InvalidSessionId",status:404,message:"Occurs if the given session id is not in the list of active sessions, meaning the session either does not exist or that it\u2019s not active."},tE={id:"MoveTargetOutOfBounds",status:500,message:"The target for mouse interaction is not in the browser\u2019s viewport and cannot be brought into that viewport."},sE={id:"NoSuchCookie",status:404,message:"No cookie matching the given path name was found amongst the associated cookies of the current browsing context\u2019s active document."},rE={id:"UnableToCaptureScreen",status:500,message:"A screen capture was made impossible."},nE={id:"UnknownMethod",status:405,message:"The requested command matched a known URL but did not match an method for that URL."},oE={id:"UnsupportedOperation",status:500,message:"Indicates that a command that should have executed properly cannot be supported for some reason."},iE={"-1":qT,0:jT,6:$T,7:hd,8:gd,9:yd,10:wd,11:BT,12:bd,13:Td,15:Ed,17:vd,19:WT,21:Sd,23:Id,24:xd,25:Rd,26:Cd,27:Pd,28:kd,29:Ad,30:GT,31:VT,32:_d,33:Od,34:HT,100:KT,101:zT,102:JT,"element click intercepted":XT,"element not selectable":Ed,"element not interactable":YT,"insecure certificate":QT,"invalid argument":ZT,"invalid cookie domain":xd,"invalid coordinates":Ad,"invalid element state":bd,"invalid selector":_d,"invalid session id":eE,"javascript error":vd,"move target out of bounds":tE,"no such alert":Pd,"no such cookie":sE,"no such element":hd,"no such frame":gd,"no such window":Id,"script timeout":kd,"session not created":Od,"stale element reference":wd,timeout:Sd,"unable to set cookie":Rd,"unable to capture screen":rE,"unexpected alert open":Cd,"unknown command":yd,"unknown error":Td,"unknown method":nE,"unsupported operation":oE},xn=79});function Oe(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function It(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function aE(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function ur(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var wi=F(()=>{"use strict"});var Cn=C((IL,lE)=>{lE.exports={name:"@testim/testim-cli",version:"0.10.22",description:"Command line interface for running Testing on your CI",author:"Oren Rubin",contributors:[{name:"Oren Rubin",email:"oren@testim.io"}],bugs:{email:"info@testim.io"},devDependencies:{"@types/decompress":"4.2.4","@types/fs-extra":"9.0.13","@types/memory-fs":"0.3.3","@types/ms":"0.7.31","@types/node":"10.17.24","@types/prompts":"2.4.2","@types/selenium-webdriver":"4.0.9","@types/superagent-proxy":"3.0.0","@types/validate-npm-package-name":"3.0.3","bundle-deps":"1.0.0",esbuild:"0.17.10","merge-stream":"2.0.0",proxyquire:"2.1.3",sinon:"9.0.2","sinon-chai":"3.7.0","ts-node":"9.1.1","tsconfig-paths":"3.12.0"},lazyDependencies:{ngrok:"4.3.3",webpack:"5.74.0",playwright:"0.12.1",puppeteer:"2.1.1","selenium-webdriver":"3.6.0","v8-to-istanbul":"7.0.0","istanbul-lib-coverage":"3.0.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},dependencies:{"@applitools/eyes-sdk-core":"13.11.29","@testim/coralogix-logger":"1.1.27-beta.1","@testim/webdriverio":"0.0.8","abort-controller":"3.0.0",ajv:"6.12.6","analytics-node":"5.0.0","appium-dom-utils":"1.0.6",archiver:"5.3.0","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0","combine-source-map":"0.8.0",commander:"2.9.0",compression:"1.7.4",cors:"2.8.5","crypto-js":"4.1.1","data-uri-to-buffer":"2.0.2",decompress:"4.2.1",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0","fs-extra":"10.0.1",glob:"7.2.0","https-proxy-agent":"5.0.0","istanbul-lib-report":"3.0.0","istanbul-reports":"3.0.2",jimp:"0.16.2",jsdom:"19.0.0",jsonwebtoken:"9.0.0",lodash:"4.17.21","memory-fs":"0.5.0",memorystream:"0.3.1",mkdirp:"1.0.4",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"},license:"Proprietary",bin:{testim:"cli.js"},scripts:{start:"ts-node-transpile-only ./src/cli",test:"yarn test:pattern './src/**/*.test.[jt]s'","test:pattern":"IS_UNIT_TEST=1 ../../node_modules/mocha/bin/_mocha --timeout 2000 --exit --recursive --exclude ./src/codim/template.[jt]s/tests/examples/**/*.test.[jt]s --watch-files 'src' -r ts-node/register/transpile-only -r tsconfig-paths/register --reporter mocha-multi-reporters --reporter-options configFile=mochaReporterConfig.js","test:cov":"nyc --reporter=lcov --reporter=text yarn test","upload-bundle-s3":"ts-node-transpile-only scripts/upload.js","prepare-version":"rm -rf ./deploy && mkdir -p deploy && tsx buildTool prepare-version-on-prem","make-onprem-deps":"cp ../../yarn.lock deploy && cd deploy && yarn install --production && bundle-deps","pack-onprem":"yarn prepare-version && yarn make-onprem-deps && cd deploy && npm pack && zip -r testim-cli.zip testim-cli-*.tgz","pack-serve":"yarn pack-onprem && http-server deploy/","self-test":"cd /tmp && DEBUG=self-test BUILD_MAX_MEMORY=4096 tsx /home/circleci/testimio/apps/runner/scripts/selfTest.ts"},engines:{node:">= 14.0.0"}}});var ce={};W(ce,{APPIUM_VERSION:()=>yE,BLOB_URL:()=>fr,CANONICAL_BLOB_URL:()=>Ri,CANONICAL_EDGE_URL:()=>Ci,DEBUG_MODE:()=>hE,DF_ENABLE_VIDEO:()=>gE,DISABLE_AGENT_ORIGIN_CHECK:()=>uE,DISABLE_DEBUGGER_INFINITE_TIMEOUT:()=>bi,EDGE_URL:()=>bE,EDITOR_URL:()=>dE,EXTENSION_SERVICES_HOST:()=>wE,GATEWAY_URL:()=>xi,IS_ON_PREM:()=>et,LOGGER_CONSOLE:()=>Ti,LOGGER_DEBUG:()=>Ei,OVERRIDE_TIMEOUTS:()=>pr,REQUESTS_QUEUE_SIZE:()=>fE,ROLLOUT_KEY:()=>Si,SERVICES_HOST:()=>mr,START_WORKER_DELAY_MS:()=>Ii,TESTIM_CONCURRENT_WORKER_COUNT:()=>vi,WEBDRIVER_DEBUG:()=>mE,WEBSOCKET_HOST:()=>pE});var dr,Ld,Nd,uE,bi,pr,dE,pE,mr,Ti,Ei,mE,et,fE,hE,vi,Si,gE,Ii,yE,xi,wE,fr,bE,Ri,Ci,ne=F(()=>{"use strict";dr=process.env.SERVICES_HOST||"https://services.testim.io",Ld="https://testimstatic.blob.core.windows.net",Nd="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:dr,dr=process.env.SERVICES_HOST);uE=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),bi=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),pr=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),dE=process.env.EDITOR_URL,pE=process.env.WEBSOCKET_HOST||`${dr}/ws`,mr=dr,Ti=parseInt(process.env.LOGGER_CONSOLE||"0",10),Ei=parseInt(process.env.LOGGER_DEBUG||"0",10),mE=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),et=parseInt(process.env.IS_ON_PREM||"0",10),fE=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,hE=parseInt(process.env.DEBUG_MODE||"0",10),vi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Si=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",gE=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Ii=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),yE=process.env.APPIUM_VERSION||"1.10.1",xi=process.env.GATEWAY_URL,wE=process.env.EXTENSION_SERVICES_HOST||dr,fr=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Ld,bE=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:Nd,Ri=Ld,Ci=Nd});var Pi={};W(Pi,{CoralogixTransport:()=>vs});var we,Dd,TE,EE,vs,ki=F(()=>{"use strict";we=require("@testim/coralogix-logger"),Dd=S(require("winston-transport")),TE={silly:we.Severity.verbose,verbose:we.Severity.verbose,info:we.Severity.info,http:we.Severity.info,warn:we.Severity.warning,warning:we.Severity.warning,error:we.Severity.error,silent:we.Severity.verbose,critical:we.Severity.critical,crit:we.Severity.critical,debug:we.Severity.debug},EE=["err","error","reason","e"],vs=class extends Dd.default{constructor(t){t=Object.assign({},vs.options,t);super(t);this.options=t,this.logger=new we.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:o,message:i,meta:a={},...c}=t,l=Object.assign({},a,this.options.extraFields,c),u=new we.Log;u.severity=TE[o],u.text=i,u.category=n,l.className&&(u.className=l.className),l.methodName&&(u.methodName=l.methodName),l.threadId&&(u.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let p=!1;a instanceof Error&&(p=!0,l.msg=a.message+a.stack,i&&(l.msg=`${i}
3
- ${l.msg}`));for(let f of EE)a[f]instanceof Error&&(l[f]={message:a[f].message,stack:a[f].stack,name:a[f].name,type:a[f].type,cause:a[f].cause,...a[f]});Object.keys(l).length>0&&(i&&!p&&(l.msg=i),u.text=l),this.logger.addLog(u),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){we.CoralogixLogger.configure(t),vs.options=t}}});var H={};W(H,{getLogger:()=>G,setExecutionId:()=>Oi,setProjectId:()=>Li,setProxyUri:()=>Ni});function IE(){let s=[],e=()=>Promise.resolve();if(!et){let{CoralogixTransport:t}=(ki(),w(Pi));t.configure(Ud);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return Ti&&s.push(new tt.transports.Console({format:tt.format.combine(tt.format.colorize(),tt.format.simple())})),[s,e]}function Oi(s){Ai=s}function Li(s){qd=s}function Ni(s){if(et||!s)return;let{CoralogixTransport:e}=(ki(),w(Pi));e.configure({...Ud,proxyUri:s})}function Md(s){return{projectId:qd,time:new Date().toISOString(),...Ai&&!s&&{executionId:Ai}}}function G(s){return new _i(kE.child({category:s}))}var Fd,tt,vE,SE,Ud,xE,RE,CE,PE,kE,Ai,qd,_i,U=F(()=>{"use strict";Fd=S(require("os")),tt=S(require("winston"));ne();M();vE=Fd.hostname(),SE=Gt(),Ud={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[xE,RE]=IE(),CE=Ei?"debug":"info",PE={release:Boolean(!0),branch:"production"},kE=tt.createLogger({levels:tt.config.syslog.levels,level:CE,transports:xE,defaultMeta:{name:"runner",hostname:vE,nodeVersion:process.version,runnerVersion:SE,...PE}}),Ai=null,qd=null;_i=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,Object.assign({meta:r,message:t},Md(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},Md(n)))}catch{}}}waitForFlush(){return RE()}}});var Z={};W(Z,{AbortError:()=>hr,ArgError:()=>L,ClientError:()=>Ui,GetBrowserError:()=>xt,GridConcurrencyError:()=>gr,GridError:()=>Ss,NoArgsError:()=>Vt,NotImplementedError:()=>Is,NpmPackageError:()=>Mi,NpmPermissionsError:()=>ji,PageNotAvailableError:()=>ft,PlaygroundCodeError:()=>qi,QuotaDepletedError:()=>Di,SeleniumCrashError:()=>Fi,SeleniumError:()=>Ht,StopRunOnError:()=>mt,TimeoutError:()=>ke});var jd,hr,Vt,L,Ht,mt,xt,ft,ke,Di,Ss,gr,Mi,Fi,Ui,qi,ji,Is,K=F(()=>{"use strict";jd=require("p-retry"),hr=class extends Error{constructor(t="aborted"){super(t);this.name="AbortError"}},Vt=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},L=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Ht=class extends Error{constructor(t){super(t.orgStatusMessage||t.message);this.name="SeleniumError",this.errorType=t.type}},mt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},xt=class extends Error{constructor(t,r){super(t);this.type=r}},ft=class extends jd.AbortError{},ke=class extends Error{},Di=class extends Error{},Ss=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},gr=class extends Ss{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Mi=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Fi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Ui=class extends Error{},qi=class extends Error{},ji=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Is=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function AE(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function qe(s){return new Promise(e=>{setTimeout(e,s)})}function de(s,e,t="Timeout Error"){pr&&!$d&&($d=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ke(t);return e=pr?Number(pr)||6e5:e,Promise.race([s,qe(e).then(()=>{throw r})])}async function Ke(s,e,{concurrency:t}={}){if(t){Bd||(Bd=(await import("p-limit")).default);let r=Bd(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var $d,Bd,$i=F(()=>{"use strict";K();ne();$d=!1});var wr,Wd,_E,yr,Gd,OE,LE,Vd,Hd=F(()=>{"use strict";wr=S(require("lodash"));ne();Wd=require("dns");U();$i();_E=G("http-request-counters"),yr=!1,Gd=async()=>{if(et)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await Ke(s,t=>Wd.promises.lookup(t)));return e||(yr=!0),e}catch{return _E.error("network connectivity test failed"),yr=!0,!1}},OE=wr.throttle(Gd,10*1e3),LE=60*1e3*15,Vd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},LE)}function t(n,o=n.name){return async function(...i){e(s.call,o);try{let a=await n.call(null,...i);return e(s.success,o),a}catch(a){throw e(s.fail,o),yr||OE(),a}}}async function r(){if(yr||!await Gd())return!1;let n=wr.sum([...s.fail.values()]),o=wr.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>yr,t}});var ht={};W(ht,{deleteFullRes:()=>UE,deleteReq:()=>Wi,didNetworkConnectivityTestFail:()=>zi,download:()=>VE,get:()=>Hi,getFullRes:()=>BE,getText:()=>$E,head:()=>WE,isNetworkHealthy:()=>Ki,post:()=>Gi,postForm:()=>jE,postFullRes:()=>qE,put:()=>GE});function DE(){return global.caFileContent}function ME(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function FE(){return!st.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(st.default),global.proxyUri}function zt(s,e=!1){let t=DE();t&&s.ca(t);let r=!e&&FE();r&&s.proxy(r)}async function Kd(s,e={},t={},r=xs){let n=st.default.delete(s).send(e).timeout(r).set(t);return zt(n),await n}async function zd(s,e,t={},r=xs,n=0){let o=st.default.post(s).send(e).timeout(r).set(t);zt(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function Vi(s,e,t={},r=xs,{isBinary:n=!1,skipProxy:o=!1}={}){let i=st.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),zt(i,o),await i}var st,Bi,Le,xs,NE,Rt,Wi,UE,Gi,qE,jE,$E,Hi,BE,WE,GE,VE,Ki,zi,rt=F(()=>{"use strict";st=S(require("superagent"));U();Hd();Bi=G("http-request"),Le=Vd(),xs=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,NE=6e4;Rt=(s,e,t)=>{throw Bi.error(s,{...t,error:e}),e};Wi=Le(async(s,e,t,r)=>{try{let n=await Kd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Rt("failed to delete request",n,{url:s})}});UE=Le(Kd),Gi=Le(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await zd(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Rt("failed to post request",o,{url:s})}});qE=Le(zd),jE=Le(async(s,e,t,r={},n=xs)=>{let o=st.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.keys(t).forEach(i=>{o.attach(i,t[i].buffer,t[i].fileName)}),zt(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Rt("failed to post request",i,{url:s})}});$E=Le(async(s,e,t)=>{try{return(await Vi(s,e,t)).text}catch(r){return Rt("failed to getText request",r,{url:s,query:e})}}),Hi=Le(async(s,e,t,r,n)=>{try{return(await Vi(s,e,t,r,n)).body}catch(o){return Rt("failed to get request",o,{url:s,query:e})}}),BE=Le((s,e,t,r)=>Vi(s,e,t,r)),WE=Le(async s=>{let e=st.default.head(s).timeout(xs);zt(e);try{return await e}catch(t){return Rt("failed to head request",t,{url:s})}}),GE=Le(async(s,e,t={},r=xs)=>{let n=st.default.put(s).send(e).timeout(r).set(t);zt(n);try{return(await n).body}catch(o){return Rt("failed to put request",o,{url:s})}}),VE=Le(async s=>{Bi.info("start to download",{url:s});let e=st.default.get(s).timeout(NE).buffer(!0).parse(ME);zt(e);try{let t=await e;return Bi.info("finished to download",{url:s}),t}catch(t){return Rt("failed to download",t,{url:s})}}),Ki=Le.isNetworkHealthy,zi=Le.didNetworkConnectivityTestFail});function Jt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=gt.resolve(__dirname,"../../"):s=gt.resolve(__dirname,""),s):process.cwd()}function Zd(s,e){return ur(s)?e||gt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||gt.basename(s)}function Gt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function JE(){try{return Jd.engines.node}catch{return""}}async function Pn(s,e,t=!0){let r=await Ne.promises.readdir(s,{withFileTypes:!0});await Ne.promises.mkdir(e,{recursive:t});for(let n of r){let o=gt.join(s,n.name),i=gt.join(e,n.name);n.isDirectory()?await Pn(o,i):await Ne.promises.copyFile(o,i)}}async function yt(s){try{return await Ne.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var gt,Jd,Xd,Yd,Ne,HE,Ji,Rs,Qd,KE,Xi,br,zE,Yi=F(()=>{"use strict";gt=S(require("path"));wi();Jd=S(Cn()),Xd=S(require("p-retry")),Yd=S(require("decompress")),Ne=require("fs"),HE=3;Ji=async s=>{let e=await Promise.resolve().then(()=>(rt(),ht));return(0,Xd.default)(()=>e.download(s),{retries:HE})},Rs=async(s,e)=>{let t=await Ji(s);return Ne.promises.writeFile(e,t.body)},Qd=async(s,e)=>new Promise((t,r)=>{try{let n=(0,Ne.createWriteStream)(e);(0,Ne.createReadStream)(s).pipe(n),n.on("finish",()=>{n.close(()=>t())})}catch(n){r(n)}});KE=async(s,e)=>{let t=Zd(s,e);return ur(s)?Rs(s,t):Qd(s,t)},Xi=async s=>ur(s)?Ji(s):Ne.promises.readFile(s),br=async(s,e)=>await(0,Yd.default)(s,e),zE=s=>(0,Ne.statSync)(s).size/1e6});var fe={};W(fe,{CLI_MODE:()=>ae,gridMessages:()=>XE,gridTypes:()=>Qt,mobileWeb:()=>YE,runnerTestStatus:()=>xe,sessionType:()=>Yt,socketEventTypes:()=>ZE,stepResult:()=>Er,test:()=>QE,testRunStatus:()=>Tr,testStatus:()=>Xt,timeoutMessages:()=>je});var je,Tr,xe,Xt,XE,YE,QE,ZE,ae,Yt,Qt,Er,ee=F(()=>{"use strict";je={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Tr={COMPLETED:"completed",RUNNING:"running"},xe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED"},Xt={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},XE={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},YE={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},QE={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},ZE={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},ae={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},Yt={CODELESS:"codeless",CODEFUL:"codeful"},Qt={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin"},Er={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed"}});function vr(s){return s.files.length>0?Yt.CODEFUL:Yt.CODELESS}function Qi(s,e){var t,r,n;return((t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length)&&!s.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function ev(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var Zi,ep,nt,tv,sv,rv,nv,ov,iv,tp=F(()=>{"use strict";ee();Zi=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},ep=s=>Boolean(s.resultId&&s.source==="remote-run"),nt=(s,e)=>s.testStatus===Xt.QUARANTINE&&!ep(e)&&!e.runQuarantinedTests;tv=s=>Boolean(s.initCodimMode),sv=s=>Boolean(s.loginMode),rv=s=>Boolean(s.tunnelOnlyMode),nv=s=>Boolean(s.createPrefechedData),ov=s=>Boolean(s.installLazyDepsMode),iv=s=>Boolean(s.agentMode)});function kn(s){let e=ea.default.duration(s);return`${e.hours()}:${e.minutes()}:${e.seconds()}.${e.milliseconds()}`}function ta(s){return ea.default.duration(s).asSeconds()}var ea,sp=F(()=>{"use strict";ea=S(require("moment"))});var q={};W(q,{TESTIM_BROWSER_DIR:()=>ra,TimeoutError:()=>ke,buildBasicHeader:()=>aE,calcPercentile:()=>pv,copy:()=>Qd,copyDir:()=>Pn,delay:()=>qe,doesPathExist:()=>yt,download:()=>Ji,downloadAndSave:()=>Rs,extractElementId:()=>uv,getArgsOnRemoteRunFailure:()=>ev,getBrowserInfo:()=>cv,getCdpAddressForHost:()=>fv,getCliLocation:()=>Jt,getDuration:()=>kn,getDurationSec:()=>ta,getEnginesVersion:()=>JE,getEnvironmentGitBranch:()=>Ir,getLocalFileSizeInMB:()=>zE,getPlanType:()=>dv,getRunConfigByBrowserName:()=>lv,getRunnerVersion:()=>Gt,getSessionType:()=>vr,getSource:()=>KE,getSourceAsBuffer:()=>Xi,getSourcePath:()=>Zd,getTestUrl:()=>It,getUniqBrowsers:()=>Qi,groupTestsByRetries:()=>mv,guid:()=>Oe,hasTestPlanFlag:()=>Zi,isAgentMode:()=>iv,isCreatePrefetchedDataMode:()=>nv,isInitCodimMode:()=>tv,isInstallLazyDepsMode:()=>ov,isLoginMode:()=>sv,isPromise:()=>AE,isQuarantineAndNotRemoteRun:()=>nt,isRemoteRun:()=>ep,isTunnelOnlyMode:()=>rv,isURL:()=>ur,promiseFromCallback:()=>Kt,promiseMap:()=>Ke,promiseTimeout:()=>de,removePropertyFromObject:()=>op,unzipFile:()=>br});function cv(s){return s=s.toLowerCase(),sa.find(e=>e.browserValue===s)}function lv(s,e,t){s=s.toLowerCase();let r=sa.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||sa[0],n=Sr.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=Sr.find(o=>o.sl.platform===e.platform):e.platformName&&(n=Sr.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=Sr.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=Sr.find(o=>o.bs.platform===t.platform))),Zt.merge(r,n)}function Ir(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function op(s,e,t){for(let r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&op(s[r],e,t))}function uv(s){return s.ELEMENT||s[yi]}function dv(s){s||(s={});let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function mv(s=[]){return Zt.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=Zt.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=Zt.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function fv(s,e){let t=await Promise.resolve().then(()=>(rt(),ht));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var rp,Zt,np,av,ra,Sr,sa,pv,M=F(()=>{"use strict";rp=S(require("os")),Zt=S(require("lodash")),np=S(require("path"));Es();Yi();tp();sp();wi();$i();av=rp.homedir(),ra=np.join(av,".testim-browser-profile"),Sr=[{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"}}],sa=[{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"}];pv=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]}});var na={};W(na,{$schema:()=>hv,default:()=>Tv,definitions:()=>gv,properties:()=>bv,required:()=>wv,type:()=>yv});var hv,gv,yv,wv,bv,Tv,ip=F(()=>{hv="http://json-schema.org/draft-07/schema#",gv={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}}}},yv="object",wv=["entries"],bv={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},Tv={$schema:hv,definitions:gv,type:yv,required:wv,properties:bv}});var oa={};W(oa,{additionalLogDetails:()=>Ev});function Ev(){return{cliLocation:Jt(),userInfo:Ps.userInfo(),platform:Ps.platform(),release:Ps.release()}}var Ps,ia=F(()=>{"use strict";Ps=S(require("os"));M()});var Ct=C((Rr,Ae)=>{"use strict";var aa=require("fs"),ca=require("path"),la=require("crypto"),da=(M(),w(q)),{debounce:vv}=require("lodash"),{getLogger:Sv}=(U(),w(H)),xr=Sv("local cache"),An=ca.resolve(da.getCliLocation(),"testim-cache"),ap,_n,pa=!0,cp=!0,ua=!1,lp=new Promise(s=>{_n=s}),up=new Promise(s=>{ap=s}),Iv=1e3*60*60*3,ma=()=>ca.resolve(ca.resolve(An,"testim.cache"));async function dp(){try{return await da.promiseTimeout(aa.promises.readFile(ma()).then(async s=>{let e=await up;return Rv(e,s)}),3e4)}catch{return{}}}var On=dp(),xv=vv(async s=>{let e;try{let t=await up,r=la.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=la.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await da.doesPathExist(An)||await aa.promises.mkdir(An,{recursive:!0}),await aa.promises.writeFile(ma(),a)}catch(t){xr.error("failed saving cache",{err:t}),e=t}_n(e?{success:!1,error:e}:{success:!0})},200);function Rv(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=la.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(r);return JSON.parse(Buffer.concat([i,o.final()]))}function Cv(s,e,t=Iv,r=void 0){return async()=>{if(!pa)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await pp(e);if(o)return xr.debug("cache hit:",{fnName:e}),o;if(xr.debug("cache miss:",{fnName:e}),!cp)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await s();return i&&await mp(e,i,t),i}}async function pp(s){let t=(await On)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function mp(s,e,t){if(ua)throw xr.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await On;r[s]={value:e,expiry:Date.now()+t},lp=new Promise(n=>{_n=n}),xv(r)}catch{xr.error("failed updating cache")}}async function Pv(){let s=await On;Object.keys(s).forEach(e=>{delete s[e]})}function fp(s){pa=s}function hp(s){cp=s}async function kv(){try{return ua=!0,await lp}finally{ua=!1}}function Av(s){An=s,On=dp()}Ae.exports.setEncryptKey=ap;Ae.exports.memoize=Cv;Ae.exports.get=pp;Ae.exports.set=mp;Ae.exports.clear=Pv;Ae.exports.disable=fp.bind(Rr,!1);Ae.exports.enable=fp.bind(Rr,!0);Ae.exports.disableCacheMiss=hp.bind(Rr,!1);Ae.exports.enableCacheMiss=hp.bind(Rr,!0);Ae.exports.isEnabled=function(){return pa};Ae.exports.setCacheLocation=Av;Ae.exports.waitForSave=kv;Ae.exports.getCacheFileLocation=ma});var gp={};W(gp,{requireWithFallback:()=>es});function _v(s){try{return Ln.resolve(Ln.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function es(s){let e=_v(s);return require(e)}var Ln,Cr=F(()=>{"use strict";Ln=S(require("path"))});var kr=C((VL,vp)=>{"use strict";var yp=require("fs"),Ov=require("util"),Pr=require("path"),Lv=require("fs-extra"),wp=(M(),w(q)),{spawn:Nv,exec:Dv}=require("child_process"),{getLogger:Mv}=(U(),w(H)),{additionalLogDetails:Fv}=(ia(),w(oa)),{requireWithFallback:Uv}=(Cr(),w(gp)),{NpmPackageError:qv,NpmPermissionsError:bp}=(K(),w(Z)),Tp=Ov.promisify(Dv),Ep=Mv("cli-service");async function jv(s){return(await Tp(`npm view ${s} version`)).stdout.trim()}function $v(s){try{return Uv(s)}catch{return!1}}async function Bv(s,e){try{return await Lv.pathExists(Pr.join(s,`./node_modules/${e}/package.json`))}catch{return!1}}function Wv(s,e){return require(Pr.join(s,`./node_modules/${e}/package.json`)).version}async function Gv(s,e,t){function r(c){let u=/EACCES[^']+'(.+)'/.exec(c.stderr);return u===null?!1:u[1]}function n(c){return/The "to" argument must be of type string./.exec(c.stderr)}let o=Pr.join(s,"npm-shrinkwrap.json"),i=Pr.join(s,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await wp.doesPathExist(o)&&(await yp.promises.rename(o,i),a=!0)}catch{}return await Tp(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(c=>{let l=r(c),u=n(c);throw l||u?(Ep.info("Failed to install package due to insufficient write access",{...Fv(),package:e,path:l||s}),console.error(`
2
+ "use strict";var NT=Object.create;var ar=Object.defineProperty;var LT=Object.getOwnPropertyDescriptor;var DT=Object.getOwnPropertyNames;var MT=Object.getPrototypeOf,FT=Object.prototype.hasOwnProperty;var UT=(s,e,t)=>e in s?ar(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var F=(s,e)=>()=>(s&&(e=s(s=0)),e);var C=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),W=(s,e)=>{for(var t in e)ar(s,t,{get:e[t],enumerable:!0})},pd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of DT(e))!FT.call(s,n)&&n!==t&&ar(s,n,{get:()=>e[n],enumerable:!(r=LT(e,n))||r.enumerable});return s};var S=(s,e,t)=>(t=s!=null?NT(MT(s)):{},pd(e||!s||!s.__esModule?ar(t,"default",{value:s,enumerable:!0}):t,s)),y=s=>pd(ar({},"__esModule",{value:!0}),s);var Ue=(s,e,t)=>(UT(s,typeof e!="symbol"?e+"":e,t),t);var Ie=C((IN,Rn)=>{"use strict";var xn=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,qT=Date.now(),hd=Date.now();Rn.exports={log(...s){if(!xn)return;let e=Date.now();console.log(`${e-qT} ${e-hd} `,...s),hd=e},measure(s){if(!xn)return;let e=Date.now();try{s()}finally{console.log(s.name,"took",Date.now()-e)}},patchPromisePrototype(){Promise.prototype.log=function(e){return xn?this.then(t=>(Rn.exports.log(e),t)):this}},measureRequireTimes(){if(!xn)return;let{performance:s,PerformanceObserver:e}=require("perf_hooks"),t=require("module");t.Module.prototype.require=s.timerify(t.Module.prototype.require),require=s.timerify(require);let r=new e(n=>{n.getEntries().sort((i,a)=>a.duration-i.duration).filter(i=>i.duration>1).forEach(i=>{console.log(`require('${i[0]}')`,i.duration)}),r.disconnect()});r.observe({entryTypes:["function"],buffered:!0})}};Rn.exports.patchPromisePrototype()});var Pn={};W(Pn,{EDGE_CHROMIUM_MIN_VERSION:()=>Cn,SELENIUM_STATUS_CODES:()=>cE,UNICODE_CHARACTERS:()=>jT,W3C_ELEMENT_ID:()=>wi});var jT,wi,$T,BT,WT,gd,yd,wd,bd,GT,Td,Ed,vd,Sd,VT,Id,xd,Rd,Cd,Pd,kd,Ad,_d,HT,KT,Od,Nd,zT,JT,XT,YT,QT,ZT,eE,tE,sE,rE,nE,oE,iE,aE,cE,Cn,Es=F(()=>{"use strict";jT={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"},wi="element-6066-11e4-a52e-4f735466cecf",$T={id:"Unknown",status:-1,message:"Remote end send an unknown status code."},BT={id:"Success",status:0,message:"The command executed successfully."},WT={id:"NoSuchDriver",status:6,message:"A session is either terminated or not started"},gd={id:"NoSuchElement",status:404,message:"An element could not be located on the page using the given search parameters."},yd={id:"NoSuchFrame",status:400,message:"A request to switch to a frame could not be satisfied because the frame could not be found."},wd={id:"UnknownCommand",status:404,message:"The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource."},bd={id:"StaleElementReference",status:400,message:"An element command failed because the referenced element is no longer attached to the DOM."},GT={id:"ElementNotVisible",status:11,message:"An element command could not be completed because the element is not visible on the page."},Td={id:"InvalidElementState",status:400,message:"An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element)."},Ed={id:"UnknownError",status:500,message:"An unknown server-side error occurred while processing the command."},vd={id:"ElementIsNotSelectable",status:400,message:"An attempt was made to select an element that cannot be selected."},Sd={id:"JavaScriptError",status:500,message:"An error occurred while executing user supplied JavaScript."},VT={id:"XPathLookupError",status:19,message:"An error occurred while searching for an element by XPath."},Id={id:"Timeout",status:408,message:"An operation did not complete before its timeout expired."},xd={id:"NoSuchWindow",status:400,message:"A request to switch to a different window could not be satisfied because the window could not be found."},Rd={id:"InvalidCookieDomain",status:400,message:"An illegal attempt was made to set a cookie under a different domain than the current page."},Cd={id:"UnableToSetCookie",status:500,message:"A request to set a cookie's value could not be satisfied."},Pd={id:"UnexpectedAlertOpen",status:500,message:"A modal dialog was open, blocking this operation"},kd={id:"NoAlertOpenError",status:400,message:"An attempt was made to operate on a modal dialog when one was not open."},Ad={id:"ScriptTimeout",status:408,message:"A script did not complete before its timeout expired."},_d={id:"InvalidElementCoordinates",status:400,message:"The coordinates provided to an interactions operation are invalid."},HT={id:"IMENotAvailable",status:30,message:"IME was not available."},KT={id:"IMEEngineActivationFailed",status:31,message:"An IME engine could not be started."},Od={id:"InvalidSelector",status:400,message:"Argument was an invalid selector (e.g. XPath/CSS)."},Nd={id:"SessionNotCreatedException",status:500,message:"A new session could not be created."},zT={id:"ElementNotScrollable",status:34,message:"Element cannot be scrolled into view."},JT={id:"SelectorTimeoutError",status:100,message:"Request timed out after the element was still found on the page."},XT={id:"NoSessionIdError",status:101,message:"A session id is required for this command but wasn't found in the response payload"},YT={id:"GridApiError",status:102,message:"A call to the Selenium Grid API failed"},QT={id:"ElementClickIntercepted",status:400,message:"The Element Click command could not be completed because the element receiving the events is obscuring the element that was requested clicked."},ZT={id:"ElementNotInteractable",status:400,message:"A command could not be completed because the element is not pointer- or keyboard interactable."},eE={id:"InsecureCertificate",status:400,message:"Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate."},tE={id:"InvalidArgument",status:400,message:"The arguments passed to a command are either invalid or malformed."},sE={id:"InvalidSessionId",status:404,message:"Occurs if the given session id is not in the list of active sessions, meaning the session either does not exist or that it\u2019s not active."},rE={id:"MoveTargetOutOfBounds",status:500,message:"The target for mouse interaction is not in the browser\u2019s viewport and cannot be brought into that viewport."},nE={id:"NoSuchCookie",status:404,message:"No cookie matching the given path name was found amongst the associated cookies of the current browsing context\u2019s active document."},oE={id:"UnableToCaptureScreen",status:500,message:"A screen capture was made impossible."},iE={id:"UnknownMethod",status:405,message:"The requested command matched a known URL but did not match an method for that URL."},aE={id:"UnsupportedOperation",status:500,message:"Indicates that a command that should have executed properly cannot be supported for some reason."},cE={"-1":$T,0:BT,6:WT,7:gd,8:yd,9:wd,10:bd,11:GT,12:Td,13:Ed,15:vd,17:Sd,19:VT,21:Id,23:xd,24:Rd,25:Cd,26:Pd,27:kd,28:Ad,29:_d,30:HT,31:KT,32:Od,33:Nd,34:zT,100:JT,101:XT,102:YT,"element click intercepted":QT,"element not selectable":vd,"element not interactable":ZT,"insecure certificate":eE,"invalid argument":tE,"invalid cookie domain":Rd,"invalid coordinates":_d,"invalid element state":Td,"invalid selector":Od,"invalid session id":sE,"javascript error":Sd,"move target out of bounds":rE,"no such alert":kd,"no such cookie":nE,"no such element":gd,"no such frame":yd,"no such window":xd,"script timeout":Ad,"session not created":Nd,"stale element reference":bd,timeout:Id,"unable to set cookie":Cd,"unable to capture screen":oE,"unexpected alert open":Pd,"unknown command":wd,"unknown error":Ed,"unknown method":iE,"unsupported operation":aE},Cn=79});function Oe(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function It(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function lE(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function dr(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var bi=F(()=>{"use strict"});var kn=C((xN,dE)=>{dE.exports={name:"@testim/testim-cli",version:"0.10.22",description:"Command line interface for running Testing on your CI",author:"Oren Rubin",contributors:[{name:"Oren Rubin",email:"oren@testim.io"}],bugs:{email:"info@testim.io"},devDependencies:{"@types/decompress":"4.2.4","@types/fs-extra":"9.0.13","@types/memory-fs":"0.3.3","@types/ms":"0.7.31","@types/node":"10.17.24","@types/prompts":"2.4.2","@types/selenium-webdriver":"4.0.9","@types/superagent-proxy":"3.0.0","@types/validate-npm-package-name":"3.0.3","bundle-deps":"1.0.0",esbuild:"0.17.10","merge-stream":"2.0.0",proxyquire:"2.1.3",sinon:"9.0.2","sinon-chai":"3.7.0","ts-node":"9.1.1","tsconfig-paths":"3.12.0"},lazyDependencies:{ngrok:"4.3.3",webpack:"5.74.0",playwright:"0.12.1",puppeteer:"2.1.1","selenium-webdriver":"3.6.0","v8-to-istanbul":"7.0.0","istanbul-lib-coverage":"3.0.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},dependencies:{"@applitools/eyes-sdk-core":"13.11.29","@testim/coralogix-logger":"1.1.27-beta.1","@testim/webdriverio":"0.0.8","abort-controller":"3.0.0",ajv:"6.12.6","analytics-node":"5.0.0","appium-dom-utils":"1.0.6",archiver:"5.3.0","body-parser":"1.20.1",chalk:"4.1.2","chrome-launcher":"0.15.0","combine-source-map":"0.8.0",commander:"2.9.0",compression:"1.7.4",cors:"2.8.5","crypto-js":"4.1.1","data-uri-to-buffer":"2.0.2",decompress:"4.2.1",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0","fs-extra":"10.0.1",glob:"7.2.0","https-proxy-agent":"5.0.0","istanbul-lib-report":"3.0.0","istanbul-reports":"3.0.2",jimp:"0.16.2",jsdom:"19.0.0",jsonwebtoken:"9.0.0",lodash:"4.17.21","memory-fs":"0.5.0",memorystream:"0.3.1",mkdirp:"1.0.4",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"},license:"Proprietary",bin:{testim:"cli.js"},scripts:{start:"ts-node-transpile-only ./src/cli",test:"yarn test:pattern './src/**/*.test.[jt]s'","test:pattern":"IS_UNIT_TEST=1 ../../node_modules/mocha/bin/_mocha --timeout 2000 --exit --recursive --exclude ./src/codim/template.[jt]s/tests/examples/**/*.test.[jt]s --watch-files 'src' -r ts-node/register/transpile-only -r tsconfig-paths/register --reporter mocha-multi-reporters --reporter-options configFile=mochaReporterConfig.js","test:cov":"nyc --reporter=lcov --reporter=text yarn test","upload-bundle-s3":"ts-node-transpile-only scripts/upload.js","prepare-version":"rm -rf ./deploy && mkdir -p deploy && tsx buildTool prepare-version-on-prem","make-onprem-deps":"cp ../../yarn.lock deploy && cd deploy && yarn install --production && bundle-deps","pack-onprem":"yarn prepare-version && yarn make-onprem-deps && cd deploy && npm pack && zip -r testim-cli.zip testim-cli-*.tgz","pack-serve":"yarn pack-onprem && http-server deploy/","self-test":"cd /tmp && DEBUG=self-test BUILD_MAX_MEMORY=4096 tsx /runner/_work/testimio/testimio/apps/runner/scripts/selfTest.ts"},engines:{node:">= 14.0.0"}}});var ce={};W(ce,{APPIUM_VERSION:()=>bE,BLOB_URL:()=>hr,CANONICAL_BLOB_URL:()=>Ci,CANONICAL_EDGE_URL:()=>Pi,DEBUG_MODE:()=>yE,DF_ENABLE_VIDEO:()=>wE,DISABLE_AGENT_ORIGIN_CHECK:()=>pE,DISABLE_DEBUGGER_INFINITE_TIMEOUT:()=>Ti,EDGE_URL:()=>EE,EDITOR_URL:()=>mE,EXTENSION_SERVICES_HOST:()=>TE,GATEWAY_URL:()=>Ri,IS_ON_PREM:()=>et,LOGGER_CONSOLE:()=>Ei,LOGGER_DEBUG:()=>vi,OVERRIDE_TIMEOUTS:()=>mr,REQUESTS_QUEUE_SIZE:()=>gE,ROLLOUT_KEY:()=>Ii,SERVICES_HOST:()=>fr,START_WORKER_DELAY_MS:()=>xi,TESTIM_CONCURRENT_WORKER_COUNT:()=>Si,WEBDRIVER_DEBUG:()=>hE,WEBSOCKET_HOST:()=>fE});var pr,Ld,Dd,pE,Ti,mr,mE,fE,fr,Ei,vi,hE,et,gE,yE,Si,Ii,wE,xi,bE,Ri,TE,hr,EE,Ci,Pi,ne=F(()=>{"use strict";pr=process.env.SERVICES_HOST||"https://services.testim.io",Ld="https://testimstatic.blob.core.windows.net",Dd="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:pr,pr=process.env.SERVICES_HOST);pE=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Ti=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),mr=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),mE=process.env.EDITOR_URL,fE=process.env.WEBSOCKET_HOST||`${pr}/ws`,fr=pr,Ei=parseInt(process.env.LOGGER_CONSOLE||"0",10),vi=parseInt(process.env.LOGGER_DEBUG||"0",10),hE=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),et=parseInt(process.env.IS_ON_PREM||"0",10),gE=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,yE=parseInt(process.env.DEBUG_MODE||"0",10),Si=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Ii=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",wE=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),xi=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),bE=process.env.APPIUM_VERSION||"1.10.1",Ri=process.env.GATEWAY_URL,TE=process.env.EXTENSION_SERVICES_HOST||pr,hr=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Ld,EE=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:Dd,Ci=Ld,Pi=Dd});var ki={};W(ki,{CoralogixTransport:()=>vs});var we,Md,vE,SE,vs,Ai=F(()=>{"use strict";we=require("@testim/coralogix-logger"),Md=S(require("winston-transport")),vE={silly:we.Severity.verbose,verbose:we.Severity.verbose,info:we.Severity.info,http:we.Severity.info,warn:we.Severity.warning,warning:we.Severity.warning,error:we.Severity.error,silent:we.Severity.verbose,critical:we.Severity.critical,crit:we.Severity.critical,debug:we.Severity.debug},SE=["err","error","reason","e"],vs=class extends Md.default{constructor(t){t=Object.assign({},vs.options,t);super(t);this.options=t,this.logger=new we.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:o,message:i,meta:a={},...c}=t,l=Object.assign({},a,this.options.extraFields,c),u=new we.Log;u.severity=vE[o],u.text=i,u.category=n,l.className&&(u.className=l.className),l.methodName&&(u.methodName=l.methodName),l.threadId&&(u.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let p=!1;a instanceof Error&&(p=!0,l.msg=a.message+a.stack,i&&(l.msg=`${i}
3
+ ${l.msg}`));for(let f of SE)a[f]instanceof Error&&(l[f]={message:a[f].message,stack:a[f].stack,name:a[f].name,type:a[f].type,cause:a[f].cause,...a[f]});Object.keys(l).length>0&&(i&&!p&&(l.msg=i),u.text=l),this.logger.addLog(u),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){we.CoralogixLogger.configure(t),vs.options=t}}});var H={};W(H,{getLogger:()=>G,setExecutionId:()=>Ni,setProjectId:()=>Li,setProxyUri:()=>Di});function RE(){let s=[],e=()=>Promise.resolve();if(!et){let{CoralogixTransport:t}=(Ai(),y(ki));t.configure(qd);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return Ei&&s.push(new tt.transports.Console({format:tt.format.combine(tt.format.colorize(),tt.format.simple())})),[s,e]}function Ni(s){_i=s}function Li(s){jd=s}function Di(s){if(et||!s)return;let{CoralogixTransport:e}=(Ai(),y(ki));e.configure({...qd,proxyUri:s})}function Fd(s){return{projectId:jd,time:new Date().toISOString(),..._i&&!s&&{executionId:_i}}}function G(s){return new Oi(_E.child({category:s}))}var Ud,tt,IE,xE,qd,CE,PE,kE,AE,_E,_i,jd,Oi,U=F(()=>{"use strict";Ud=S(require("os")),tt=S(require("winston"));ne();M();IE=Ud.hostname(),xE=Gt(),qd={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[CE,PE]=RE(),kE=vi?"debug":"info",AE={release:Boolean(!0),branch:"production"},_E=tt.createLogger({levels:tt.config.syslog.levels,level:kE,transports:CE,defaultMeta:{name:"runner",hostname:IE,nodeVersion:process.version,runnerVersion:xE,...AE}}),_i=null,jd=null;Oi=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,Object.assign({meta:r,message:t},Fd(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},Fd(n)))}catch{}}}waitForFlush(){return PE()}}});var Z={};W(Z,{AbortError:()=>gr,ArgError:()=>N,ClientError:()=>qi,GetBrowserError:()=>xt,GridConcurrencyError:()=>yr,GridError:()=>Ss,NoArgsError:()=>Vt,NotImplementedError:()=>Is,NpmPackageError:()=>Fi,NpmPermissionsError:()=>$i,PageNotAvailableError:()=>ft,PlaygroundCodeError:()=>ji,QuotaDepletedError:()=>Mi,SeleniumCrashError:()=>Ui,SeleniumError:()=>Ht,StopRunOnError:()=>mt,TimeoutError:()=>ke});var $d,gr,Vt,N,Ht,mt,xt,ft,ke,Mi,Ss,yr,Fi,Ui,qi,ji,$i,Is,K=F(()=>{"use strict";$d=require("p-retry"),gr=class extends Error{constructor(t="aborted"){super(t);this.name="AbortError"}},Vt=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},N=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Ht=class extends Error{constructor(t){super(t.orgStatusMessage||t.message);this.name="SeleniumError",this.errorType=t.type}},mt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},xt=class extends Error{constructor(t,r){super(t);this.type=r}},ft=class extends $d.AbortError{},ke=class extends Error{},Mi=class extends Error{},Ss=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},yr=class extends Ss{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Fi=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Ui=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},qi=class extends Error{},ji=class extends Error{},$i=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Is=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function OE(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function qe(s){return new Promise(e=>{setTimeout(e,s)})}function de(s,e,t="Timeout Error"){mr&&!Bd&&(Bd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ke(t);return e=mr?Number(mr)||6e5:e,Promise.race([s,qe(e).then(()=>{throw r})])}async function ze(s,e,{concurrency:t}={}){if(t){Wd||(Wd=(await import("p-limit")).default);let r=Wd(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var Bd,Wd,Bi=F(()=>{"use strict";K();ne();Bd=!1});var br,Gd,NE,wr,Vd,LE,DE,Hd,Kd=F(()=>{"use strict";br=S(require("lodash"));ne();Gd=require("dns");U();Bi();NE=G("http-request-counters"),wr=!1,Vd=async()=>{if(et)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ze(s,t=>Gd.promises.lookup(t)));return e||(wr=!0),e}catch{return NE.error("network connectivity test failed"),wr=!0,!1}},LE=br.throttle(Vd,10*1e3),DE=60*1e3*15,Hd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},DE)}function t(n,o=n.name){return async function(...i){e(s.call,o);try{let a=await n.call(null,...i);return e(s.success,o),a}catch(a){throw e(s.fail,o),wr||LE(),a}}}async function r(){if(wr||!await Vd())return!1;let n=br.sum([...s.fail.values()]),o=br.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>wr,t}});var ht={};W(ht,{deleteFullRes:()=>jE,deleteReq:()=>Gi,didNetworkConnectivityTestFail:()=>Ji,download:()=>KE,get:()=>Ki,getFullRes:()=>GE,getText:()=>WE,head:()=>VE,isNetworkHealthy:()=>zi,post:()=>Vi,postForm:()=>BE,postFullRes:()=>$E,put:()=>HE});function FE(){return global.caFileContent}function UE(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function qE(){return!st.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(st.default),global.proxyUri}function zt(s,e=!1){let t=FE();t&&s.ca(t);let r=!e&&qE();r&&s.proxy(r)}async function zd(s,e={},t={},r=xs){let n=st.default.delete(s).send(e).timeout(r).set(t);return zt(n),await n}async function Jd(s,e,t={},r=xs,n=0){let o=st.default.post(s).send(e).timeout(r).set(t);zt(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function Hi(s,e,t={},r=xs,{isBinary:n=!1,skipProxy:o=!1}={}){let i=st.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),zt(i,o),await i}var st,Wi,Ne,xs,ME,Rt,Gi,jE,Vi,$E,BE,WE,Ki,GE,VE,HE,KE,zi,Ji,rt=F(()=>{"use strict";st=S(require("superagent"));U();Kd();Wi=G("http-request"),Ne=Hd(),xs=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,ME=6e4;Rt=(s,e,t)=>{throw Wi.error(s,{...t,error:e}),e};Gi=Ne(async(s,e,t,r)=>{try{let n=await zd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Rt("failed to delete request",n,{url:s})}});jE=Ne(zd),Vi=Ne(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await Jd(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Rt("failed to post request",o,{url:s})}});$E=Ne(Jd),BE=Ne(async(s,e,t,r={},n=xs)=>{let o=st.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.keys(t).forEach(i=>{o.attach(i,t[i].buffer,t[i].fileName)}),zt(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Rt("failed to post request",i,{url:s})}});WE=Ne(async(s,e,t)=>{try{return(await Hi(s,e,t)).text}catch(r){return Rt("failed to getText request",r,{url:s,query:e})}}),Ki=Ne(async(s,e,t,r,n)=>{try{return(await Hi(s,e,t,r,n)).body}catch(o){return Rt("failed to get request",o,{url:s,query:e})}}),GE=Ne((s,e,t,r)=>Hi(s,e,t,r)),VE=Ne(async s=>{let e=st.default.head(s).timeout(xs);zt(e);try{return await e}catch(t){return Rt("failed to head request",t,{url:s})}}),HE=Ne(async(s,e,t={},r=xs)=>{let n=st.default.put(s).send(e).timeout(r).set(t);zt(n);try{return(await n).body}catch(o){return Rt("failed to put request",o,{url:s})}}),KE=Ne(async s=>{Wi.info("start to download",{url:s});let e=st.default.get(s).timeout(ME).buffer(!0).parse(UE);zt(e);try{let t=await e;return Wi.info("finished to download",{url:s}),t}catch(t){return Rt("failed to download",t,{url:s})}}),zi=Ne.isNetworkHealthy,Ji=Ne.didNetworkConnectivityTestFail});function Jt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=gt.resolve(__dirname,"../../"):s=gt.resolve(__dirname,""),s):process.cwd()}function ep(s,e){return dr(s)?e||gt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||gt.basename(s)}function Gt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function YE(){try{return Xd.engines.node}catch{return""}}async function An(s,e,t=!0){let r=await Le.promises.readdir(s,{withFileTypes:!0});await Le.promises.mkdir(e,{recursive:t});for(let n of r){let o=gt.join(s,n.name),i=gt.join(e,n.name);n.isDirectory()?await An(o,i):await Le.promises.copyFile(o,i)}}async function yt(s){try{return await Le.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var gt,Xd,Yd,Qd,Le,zE,Xi,Rs,Zd,JE,Yi,Tr,XE,Qi=F(()=>{"use strict";gt=S(require("path"));bi();Xd=S(kn()),Yd=S(require("p-retry")),Qd=S(require("decompress")),Le=require("fs"),zE=3;Xi=async s=>{let e=await Promise.resolve().then(()=>(rt(),ht));return(0,Yd.default)(()=>e.download(s),{retries:zE})},Rs=async(s,e)=>{let t=await Xi(s);return Le.promises.writeFile(e,t.body)},Zd=async(s,e)=>new Promise((t,r)=>{try{let n=(0,Le.createWriteStream)(e);(0,Le.createReadStream)(s).pipe(n),n.on("finish",()=>{n.close(()=>t())})}catch(n){r(n)}});JE=async(s,e)=>{let t=ep(s,e);return dr(s)?Rs(s,t):Zd(s,t)},Yi=async s=>dr(s)?Xi(s):Le.promises.readFile(s),Tr=async(s,e)=>await(0,Qd.default)(s,e),XE=s=>(0,Le.statSync)(s).size/1e6});var fe={};W(fe,{CLI_MODE:()=>ae,gridMessages:()=>QE,gridTypes:()=>Qt,mobileWeb:()=>ZE,runnerTestStatus:()=>xe,sessionType:()=>Yt,socketEventTypes:()=>tv,stepResult:()=>vr,test:()=>ev,testRunStatus:()=>Er,testStatus:()=>Xt,timeoutMessages:()=>je});var je,Er,xe,Xt,QE,ZE,ev,tv,ae,Yt,Qt,vr,ee=F(()=>{"use strict";je={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Er={COMPLETED:"completed",RUNNING:"running"},xe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED"},Xt={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},QE={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},ZE={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},ev={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},tv={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},ae={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},Yt={CODELESS:"codeless",CODEFUL:"codeful"},Qt={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin"},vr={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed"}});function Sr(s){return s.files.length>0?Yt.CODEFUL:Yt.CODELESS}function Zi(s,e){var t,r,n;return((t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length)&&!s.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function sv(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var ea,tp,nt,rv,nv,ov,iv,av,cv,sp=F(()=>{"use strict";ee();ea=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},tp=s=>Boolean(s.resultId&&s.source==="remote-run"),nt=(s,e)=>s.testStatus===Xt.QUARANTINE&&!tp(e)&&!e.runQuarantinedTests;rv=s=>Boolean(s.initCodimMode),nv=s=>Boolean(s.loginMode),ov=s=>Boolean(s.tunnelOnlyMode),iv=s=>Boolean(s.createPrefechedData),av=s=>Boolean(s.installLazyDepsMode),cv=s=>Boolean(s.agentMode)});function _n(s){let e=ta.default.duration(s);return`${e.hours()}:${e.minutes()}:${e.seconds()}.${e.milliseconds()}`}function sa(s){return ta.default.duration(s).asSeconds()}var ta,rp=F(()=>{"use strict";ta=S(require("moment"))});var q={};W(q,{TESTIM_BROWSER_DIR:()=>na,TimeoutError:()=>ke,buildBasicHeader:()=>lE,calcPercentile:()=>fv,copy:()=>Zd,copyDir:()=>An,delay:()=>qe,doesPathExist:()=>yt,download:()=>Xi,downloadAndSave:()=>Rs,extractElementId:()=>pv,getArgsOnRemoteRunFailure:()=>sv,getBrowserInfo:()=>uv,getCdpAddressForHost:()=>gv,getCliLocation:()=>Jt,getDuration:()=>_n,getDurationSec:()=>sa,getEnginesVersion:()=>YE,getEnvironmentGitBranch:()=>xr,getLocalFileSizeInMB:()=>XE,getPlanType:()=>mv,getRunConfigByBrowserName:()=>dv,getRunnerVersion:()=>Gt,getSessionType:()=>Sr,getSource:()=>JE,getSourceAsBuffer:()=>Yi,getSourcePath:()=>ep,getTestUrl:()=>It,getUniqBrowsers:()=>Zi,groupTestsByRetries:()=>hv,guid:()=>Oe,hasTestPlanFlag:()=>ea,isAgentMode:()=>cv,isCreatePrefetchedDataMode:()=>iv,isInitCodimMode:()=>rv,isInstallLazyDepsMode:()=>av,isLoginMode:()=>nv,isPromise:()=>OE,isQuarantineAndNotRemoteRun:()=>nt,isRemoteRun:()=>tp,isTunnelOnlyMode:()=>ov,isURL:()=>dr,promiseFromCallback:()=>Kt,promiseMap:()=>ze,promiseTimeout:()=>de,removePropertyFromObject:()=>ip,unzipFile:()=>Tr});function uv(s){return s=s.toLowerCase(),ra.find(e=>e.browserValue===s)}function dv(s,e,t){s=s.toLowerCase();let r=ra.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||ra[0],n=Ir.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=Ir.find(o=>o.sl.platform===e.platform):e.platformName&&(n=Ir.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=Ir.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=Ir.find(o=>o.bs.platform===t.platform))),Zt.merge(r,n)}function xr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function ip(s,e,t){for(let r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&ip(s[r],e,t))}function pv(s){return s.ELEMENT||s[wi]}function mv(s){s||(s={});let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function hv(s=[]){return Zt.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=Zt.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=Zt.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function gv(s,e){let t=await Promise.resolve().then(()=>(rt(),ht));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var np,Zt,op,lv,na,Ir,ra,fv,M=F(()=>{"use strict";np=S(require("os")),Zt=S(require("lodash")),op=S(require("path"));Es();Qi();sp();rp();bi();Bi();lv=np.homedir(),na=op.join(lv,".testim-browser-profile"),Ir=[{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"}}],ra=[{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"}];fv=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]}});var oa={};W(oa,{$schema:()=>yv,default:()=>vv,definitions:()=>wv,properties:()=>Ev,required:()=>Tv,type:()=>bv});var yv,wv,bv,Tv,Ev,vv,ap=F(()=>{yv="http://json-schema.org/draft-07/schema#",wv={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}}}},bv="object",Tv=["entries"],Ev={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},vv={$schema:yv,definitions:wv,type:bv,required:Tv,properties:Ev}});var ia={};W(ia,{additionalLogDetails:()=>Sv});function Sv(){return{cliLocation:Jt(),userInfo:Ps.userInfo(),platform:Ps.platform(),release:Ps.release()}}var Ps,aa=F(()=>{"use strict";Ps=S(require("os"));M()});var Ct=C((Cr,Ae)=>{"use strict";var ca=require("fs"),la=require("path"),ua=require("crypto"),pa=(M(),y(q)),{debounce:Iv}=require("lodash"),{getLogger:xv}=(U(),y(H)),Rr=xv("local cache"),On=la.resolve(pa.getCliLocation(),"testim-cache"),cp,Nn,ma=!0,lp=!0,da=!1,up=new Promise(s=>{Nn=s}),dp=new Promise(s=>{cp=s}),Rv=1e3*60*60*3,fa=()=>la.resolve(la.resolve(On,"testim.cache"));async function pp(){try{return await pa.promiseTimeout(ca.promises.readFile(fa()).then(async s=>{let e=await dp;return Pv(e,s)}),3e4)}catch{return{}}}var Ln=pp(),Cv=Iv(async s=>{let e;try{let t=await dp,r=ua.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=ua.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await pa.doesPathExist(On)||await ca.promises.mkdir(On,{recursive:!0}),await ca.promises.writeFile(fa(),a)}catch(t){Rr.error("failed saving cache",{err:t}),e=t}Nn(e?{success:!1,error:e}:{success:!0})},200);function Pv(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=ua.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(r);return JSON.parse(Buffer.concat([i,o.final()]))}function kv(s,e,t=Rv,r=void 0){return async()=>{if(!ma)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await mp(e);if(o)return Rr.debug("cache hit:",{fnName:e}),o;if(Rr.debug("cache miss:",{fnName:e}),!lp)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await s();return i&&await fp(e,i,t),i}}async function mp(s){let t=(await Ln)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function fp(s,e,t){if(da)throw Rr.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await Ln;r[s]={value:e,expiry:Date.now()+t},up=new Promise(n=>{Nn=n}),Cv(r)}catch{Rr.error("failed updating cache")}}async function Av(){let s=await Ln;Object.keys(s).forEach(e=>{delete s[e]})}function hp(s){ma=s}function gp(s){lp=s}async function _v(){try{return da=!0,await up}finally{da=!1}}function Ov(s){On=s,Ln=pp()}Ae.exports.setEncryptKey=cp;Ae.exports.memoize=kv;Ae.exports.get=mp;Ae.exports.set=fp;Ae.exports.clear=Av;Ae.exports.disable=hp.bind(Cr,!1);Ae.exports.enable=hp.bind(Cr,!0);Ae.exports.disableCacheMiss=gp.bind(Cr,!1);Ae.exports.enableCacheMiss=gp.bind(Cr,!0);Ae.exports.isEnabled=function(){return ma};Ae.exports.setCacheLocation=Ov;Ae.exports.waitForSave=_v;Ae.exports.getCacheFileLocation=fa});var yp={};W(yp,{requireWithFallback:()=>es});function Nv(s){try{return Dn.resolve(Dn.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function es(s){let e=Nv(s);return require(e)}var Dn,Pr=F(()=>{"use strict";Dn=S(require("path"))});var Ar=C((HN,Sp)=>{"use strict";var wp=require("fs"),Lv=require("util"),kr=require("path"),Dv=require("fs-extra"),bp=(M(),y(q)),{spawn:Mv,exec:Fv}=require("child_process"),{getLogger:Uv}=(U(),y(H)),{additionalLogDetails:qv}=(aa(),y(ia)),{requireWithFallback:jv}=(Pr(),y(yp)),{NpmPackageError:$v,NpmPermissionsError:Tp}=(K(),y(Z)),Ep=Lv.promisify(Fv),vp=Uv("cli-service");async function Bv(s){return(await Ep(`npm view ${s} version`)).stdout.trim()}function Wv(s){try{return jv(s)}catch{return!1}}async function Gv(s,e){try{return await Dv.pathExists(kr.join(s,`./node_modules/${e}/package.json`))}catch{return!1}}function Vv(s,e){return require(kr.join(s,`./node_modules/${e}/package.json`)).version}async function Hv(s,e,t){function r(c){let u=/EACCES[^']+'(.+)'/.exec(c.stderr);return u===null?!1:u[1]}function n(c){return/The "to" argument must be of type string./.exec(c.stderr)}let o=kr.join(s,"npm-shrinkwrap.json"),i=kr.join(s,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await bp.doesPathExist(o)&&(await wp.promises.rename(o,i),a=!0)}catch{}return await Ep(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(c=>{let l=r(c),u=n(c);throw l||u?(vp.info("Failed to install package due to insufficient write access",{...qv(),package:e,path:l||s}),console.error(`
4
4
 
5
5
  Testim failed installing the package ${e} due to insufficient permissions.
6
6
  This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
7
7
  Testim had missing write access to ${l||s}
8
8
 
9
- `),new bp(l||s)):c})}finally{if(a)try{await yp.promises.rename(i,o)}catch{}}}var Vv=Pr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js");function Hv(s,e,t,r){return new Promise((n,o)=>{let i=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",l="",u="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),p=Nv("node",[Vv,"i","--prefix",s,...u,...e,...i],a);p.stderr.pipe(process.stderr),p.stdout.pipe(process.stdout),p.stdout.on("data",f=>{c+=f}),p.stderr.on("data",f=>{l+=f}),p.on("close",f=>{if(f){let m;try{m=`404 Not Found - GET https://registry.npmjs.org/${/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(l)[1].split("@")[0]} - Not found`}catch{m=`Npm Install closed with exit code ${f}
10
- stdout: ${c} stderr: ${l}`}Ep.debug(`Npm Install closed with exit code ${f}`,{message:m}),o(new qv(m))}else n(c)}),setTimeout(()=>{try{p.kill()}finally{o(new wp.TimeoutError)}},r)})}vp.exports={isPackageInstalledInPath:Bv,getLatestPackageVersion:jv,getPackageIfInstalledLocally:$v,getLocallyInstalledPackageVersion:Wv,installPackageLocally:Gv,installPackages:Hv,NpmPermissionsError:bp}});var Pp={};W(Pp,{install:()=>zv,isReady:()=>Xv,start:()=>Jv});var Sp,Ip,xp,Rp,Cp,fa,Kv,zv,Jv,Xv,kp=F(()=>{"use strict";Sp=S(require("fkill")),Ip=S(require("p-retry")),xp=S(kr());rt();M();Cr();Rp="chromedriver",Cp=9515,fa=`http://localhost:${Cp}/wd/hub`,Kv=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],zv=async()=>{await xp.default.installPackageLocally(Jt(),`${Rp} --detect_chromedriver_version`)},Jv=async()=>{process.env.NODE_OPTIONS="",await(0,Sp.default)(`:${Cp}`,{silent:!0}),await es(Rp).start(Kv,!0)},Xv=async({chromeBinaryLocation:s})=>{await(0,Ip.default)(async()=>{var n;let e=await Hi(`${fa}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Gi({url:`${fa}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await Wi(`${fa}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var ks=C((zL,Mp)=>{"use strict";var Dn=require("path"),Yv=require("fs"),Qv=require("ms"),{serializeError:Zv}=require("serialize-error"),{additionalLogDetails:eS}=(ia(),w(oa)),_p=(ne(),w(ce)),{ArgError:Nn,NpmPermissionsError:tS}=(K(),w(Z)),{getCliLocation:sS,isURL:ha,downloadAndSave:rS,getSource:Op,getLocalFileSizeInMB:nS,download:oS,unzipFile:iS,getSourcePath:aS,promiseMap:cS}=(M(),w(q)),Lp=Ct(),Mn=(U(),w(H)).getLogger("prepare runner and testim start"),Np=Qv("0.5 day"),ga=16,Ap=`The size of the custom extension is more than ${ga}MB`;Mp.exports={prepareChromeDriver:pS,prepareCustomExtension:lS,prepareExtension:dS,getSessionPlayerFolder:ya,preparePlayer:gS};async function lS(s,e=!1){if(!s)return;if(ha(s)){let n=Dn.join(process.cwd(),s.replace(/^.*[\\\/]/,""));if(await uS(s)>ga&&!e)throw new Nn(Ap);return await rS(s,n),n}let t=Dn.resolve(s);if(!Yv.existsSync(t))throw new Nn(`Failed to find custom extension in location: ${t}`);if(nS(t)>ga&&!e)throw new Nn(Ap);return t}async function uS(s){let e=(rt(),w(ht));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Mn.warn("failed to download custom extension",{err:t}),new Nn(`Failed to download custom extension from location: ${s}`)}}function dS(s){Mn.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:aS(t)}));return Lp.memoize(()=>cS(e,({location:t,path:r})=>Op(t,r)),"prepareExtension",Np,e)()}async function pS(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=(kp(),w(Pp));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 tS||(Mn.error(a,{...s,...eS(),error:Zv(i)}),console.log(`
9
+ `),new Tp(l||s)):c})}finally{if(a)try{await wp.promises.rename(i,o)}catch{}}}var Kv=kr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js");function zv(s,e,t,r){return new Promise((n,o)=>{let i=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",l="",u="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),p=Mv("node",[Kv,"i","--prefix",s,...u,...e,...i],a);p.stderr.pipe(process.stderr),p.stdout.pipe(process.stdout),p.stdout.on("data",f=>{c+=f}),p.stderr.on("data",f=>{l+=f}),p.on("close",f=>{if(f){let m;try{m=`404 Not Found - GET https://registry.npmjs.org/${/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(l)[1].split("@")[0]} - Not found`}catch{m=`Npm Install closed with exit code ${f}
10
+ stdout: ${c} stderr: ${l}`}vp.debug(`Npm Install closed with exit code ${f}`,{message:m}),o(new $v(m))}else n(c)}),setTimeout(()=>{try{p.kill()}finally{o(new bp.TimeoutError)}},r)})}Sp.exports={isPackageInstalledInPath:Gv,getLatestPackageVersion:Bv,getPackageIfInstalledLocally:Wv,getLocallyInstalledPackageVersion:Vv,installPackageLocally:Hv,installPackages:zv,NpmPermissionsError:Tp}});var kp={};W(kp,{install:()=>Xv,isReady:()=>Qv,start:()=>Yv});var Ip,xp,Rp,Cp,Pp,ha,Jv,Xv,Yv,Qv,Ap=F(()=>{"use strict";Ip=S(require("fkill")),xp=S(require("p-retry")),Rp=S(Ar());rt();M();Pr();Cp="chromedriver",Pp=9515,ha=`http://localhost:${Pp}/wd/hub`,Jv=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Xv=async()=>{await Rp.default.installPackageLocally(Jt(),`${Cp} --detect_chromedriver_version`)},Yv=async()=>{process.env.NODE_OPTIONS="",await(0,Ip.default)(`:${Pp}`,{silent:!0}),await es(Cp).start(Jv,!0)},Qv=async({chromeBinaryLocation:s})=>{await(0,xp.default)(async()=>{var n;let e=await Ki(`${ha}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Vi({url:`${ha}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await Gi(`${ha}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var ks=C((JN,Fp)=>{"use strict";var Fn=require("path"),Zv=require("fs"),eS=require("ms"),{serializeError:tS}=require("serialize-error"),{additionalLogDetails:sS}=(aa(),y(ia)),Op=(ne(),y(ce)),{ArgError:Mn,NpmPermissionsError:rS}=(K(),y(Z)),{getCliLocation:nS,isURL:ga,downloadAndSave:oS,getSource:Np,getLocalFileSizeInMB:iS,download:aS,unzipFile:cS,getSourcePath:lS,promiseMap:uS}=(M(),y(q)),Lp=Ct(),Un=(U(),y(H)).getLogger("prepare runner and testim start"),Dp=eS("0.5 day"),ya=16,_p=`The size of the custom extension is more than ${ya}MB`;Fp.exports={prepareChromeDriver:fS,prepareCustomExtension:dS,prepareExtension:mS,getSessionPlayerFolder:wa,preparePlayer:wS};async function dS(s,e=!1){if(!s)return;if(ga(s)){let n=Fn.join(process.cwd(),s.replace(/^.*[\\\/]/,""));if(await pS(s)>ya&&!e)throw new Mn(_p);return await oS(s,n),n}let t=Fn.resolve(s);if(!Zv.existsSync(t))throw new Mn(`Failed to find custom extension in location: ${t}`);if(iS(t)>ya&&!e)throw new Mn(_p);return t}async function pS(s){let e=(rt(),y(ht));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Un.warn("failed to download custom extension",{err:t}),new Mn(`Failed to download custom extension from location: ${s}`)}}function mS(s){Un.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:lS(t)}));return Lp.memoize(()=>uS(e,({location:t,path:r})=>Np(t,r)),"prepareExtension",Dp,e)()}async function fS(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=(Ap(),y(kp));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 rS||(Un.error(a,{...s,...sS(),error:tS(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 mS(){let s=`${_p.BLOB_URL}/extension/sessionPlayer_LATEST_RELEASE`;return(await oS(s)).body.toString("utf8")}async function fS(s,e){if(!ha(s)||ha(s)&&e||_p.IS_ON_PREM)return s;let t=await mS();return`${s}-${t}`}function ya(){let s=sS();return Dn.resolve(s,"testim-bin")}function hS(){let s=ya();return Dn.resolve(s,"sessionPlayer.zip")}async function Dp(s,e,t=!1){try{return await Op(s,e),await iS(e,ya())}catch(r){if(t)throw r;return await Dp(s,e,!0)}}async function gS(s,e){Mn.info("prepare player",{location:s,canary:e});let t=hS();return Lp.memoize(async()=>{let r=await fS(s,e);return await Dp(r,t),{}},"preparePlayer",Np,[s,e,t])()}});var Up={};W(Up,{CHROMIUM_VERSION:()=>Un,downloadAndInstallChromium:()=>Ta});function yS(){let s=Ar.type().toLowerCase();return s==="darwin"?Ar.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?Ar.arch()==="x64"?"win64":"win32":"linux"}async function Ta(){let s=yS(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new L(`Unsupported platform: ${s}`);let r=parseInt(Un,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${Un}/${n[s]}.zip`,a=Fn.join(wa,n[s]),c=`${a}.zip`,l=Fn.join(a,o[s]);if(await yt(l))return l;if(!await yt(c)){let p=(0,ba.default)("Downloading Chromium").start();try{await Fp.promises.mkdir(wa),await Rs(i,c)}catch(f){let m=`Failed to download Chromium: ${f.message}`;throw p.fail(m),new Error(m)}p.succeed()}let u=(0,ba.default)("Extracting Chromium").start();try{await br(c,wa)}catch(p){let f=`Failed to extract Chromium: ${p.message}`;throw u.fail(f),new Error(f)}return u.succeed(),l}var Fp,Ar,Fn,ba,Un,wa,Ea=F(()=>{"use strict";Fp=S(require("fs")),Ar=S(require("os")),Fn=S(require("path")),ba=S(require("ora"));K();M();Un="1000968",wa=Fn.join(ra,`chrome-${Un}`)});var ot=C((YL,Wp)=>{"use strict";var jp=(rt(),w(ht)),$p=(ne(),w(ce)),qp=(K(),w(Z)).ArgError,_r=(U(),w(H)).getLogger("testim-custom-token"),wS=Ct(),$e,Or,qn,Sa,Ia,jn=null,xa=null,Bp=5*60*1e3;async function bS(s,e){return jn=s,xa=e,await va()}function TS(s,e,t){$e=s.token,jn=e,xa=t,Or=Ra($e),qn=s.refreshToken,Sa=s.ngrokToken,Ia=s.isNgrokWhitelisted}function ES(s=jn,e=xa){return wS.memoize(()=>(_r.info("request to get cli token from server"),jp.post({url:`${$p.SERVICES_HOST}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Bp*10,{projectId:s,token:e})()}async function vS(){return _r.info("request to refresh JWT cli token from server"),$e=(await jp.post({url:`${$p.SERVICES_HOST}/auth/refreshToken`,body:{token:$e,refreshToken:qn}})).token,Or=Ra($e),$e}function va(){return ES().then(s=>(_r.info("successfully get cli token from server"),$e=s.token,Or=Ra($e),qn=s.refreshToken,Sa=s.ngrokToken,Ia=s.isNgrokWhitelisted,$e)).catch(s=>{throw s.message.includes("Unauthorized")?new qp("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."):(_r.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:jn}),new qp(`While trying to retrieve CLI token, caught error: ${s}`))})}function Ra(s){return require("jsonwebtoken").decode(s).exp*1e3}function SS(){return Or?Or<Date.now()+4*Bp?vS().catch(s=>(_r.error("failed to refresh token, executing fallback",s),va())):Promise.resolve($e):va()}function IS(){return qn}function xS(){return $e?{uid:require("jsonwebtoken").decode($e).id,ngrokToken:Sa,isNgrokWhitelisted:Ia}:{}}Wp.exports={init:bS,initFromData:TS,getCustomTokenV3:SS,getTokenV3UserData:xS,getRefreshToken:IS}});var Pa={};W(Pa,{isCi:()=>Ca});var Ca,$n=F(()=>{"use strict";Ca=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var pe=C((QL,Kp)=>{"use strict";var Lr=require("lodash"),RS=require("pako"),Q=require("p-retry"),Vp=require("object-hash"),As=(M(),w(q)),wt=(ne(),w(ce)),CS=(ee(),w(fe)),ts=(rt(),w(ht)),PS=ot(),{ArgError:Gp}=(K(),w(Z)),{getLogger:kS}=(U(),w(H)),AS=As.getRunnerVersion(),bt=kS("testim service api"),Y=3,_S="/grid";function Nr(){return PS.getCustomTokenV3().then(s=>{if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}})}function Be({url:s,body:e,headers:t={},timeout:r,retry:n}){return Nr().then(o=>{let i=Object.assign({},t,o);return ts.post({url:`${wt.SERVICES_HOST}${s||""}`,body:e,headers:i,timeout:r,retry:n})})}function OS(s,e,t,r={},n){return Nr().then(o=>{let i=Object.assign({},r,o);return ts.postForm(`${wt.SERVICES_HOST}${s||""}`,e,t,i,n)})}function Bn(s,e){return Nr().then(t=>ts.put(`${wt.SERVICES_HOST}${s||""}`,e,t))}function LS(s,e){return Nr().then(t=>ts.deleteReq(`${wt.SERVICES_HOST}${s||""}`,e,t))}function be(s,e,t,r){return Nr().then(n=>ts.get(`${wt.SERVICES_HOST}${s||""}`,e,n,r,t))}function NS(s,e){return Q(()=>be(`/storage${s}`,null,{isBinary:!0},e),{retries:Y})}function DS(s,e){let t=r=>r==null?[]:typeof r=="string"&&JSON.parse(r)||r;return Q({retries:Y}).then(r=>r.map(n=>(n.testConfigIds=t(n.testConfigIds),n.beforeAllLabels=t(n.beforeAllLabels),n.testLabels=t(n.testLabels),n.afterAllLabels=t(n.afterAllLabels),n)))}async function MS({branch:s,projectId:e}){let t=await Q(()=>be(`/branch/branchData/${s}`,{projectId:e}),{retries:Y});return t==null?void 0:t.sfdcCredential}function FS({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return Q(()=>be(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:Y})}function US(s,e,t){return Q(()=>Be({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:Y})}function qS(s,e,t,r,n,o,i=Y){return Q(()=>Bn("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:AS,...o}),{retries:i})}function jS(s,e,t,r,n,o,i,a){return Q(()=>Bn("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:Y})}function $S({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:u}){let p=($n(),w(Pa)).isCi;return Be({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:u,metadata:{isCiRun:p,localRunUserId:c,isLocalRun:l}},retry:3})}function BS(s,e,t,r,n={},o,i){let a=Date.now();return Q(()=>Bn("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:Y})}async function WS(s,e,t,r,n){return Q(()=>Be({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:Y})}function GS({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:u}){return Q(()=>Be({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:u}}),{retries:Y,factor:1})}async function VS({appId:s,projectId:e}){try{return await Q(()=>be(`/mobile-app/app/${s}?projectId=${e}`),{retries:Y,factor:1})}catch(t){bt.error("failed getting application details",{appId:s,error:t});return}}function HS(s){return Q(()=>be(`/plan/project/${s}/usage-current-billing-period`),{retries:Y}).catch(e=>{bt.error("failed getting usage for current billing period",{projectId:s,error:e})})}function KS(s,e,t){return Q(()=>be(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:Y})}function zS(s,e,t,r){return Q(()=>be(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:Y,factor:1})}function JS(s,e){return Be({url:`/grid/keep-alive?reqId=${As.guid()}`,body:{projectId:s,slots:e},timeout:1e4})}function XS(s,e,t,r,n){return Be({url:`/grid/release?reqId=${As.guid()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function YS(s){return Be({url:"/grid/hybrid/provider",body:s})}function QS(s,e,t,r,n){return Q(()=>be("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:As.guid()}),{retries:Y})}function ZS(s,e,t,r,n){return Q(()=>be(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:As.guid()}),{retries:Y})}async function eI({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n}){var o,i;try{return await Q(()=>ts.post({url:`${wt.SERVICES_HOST}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n}}),{retries:Y})}catch(a){throw bt.error("error initializing info from server",a),(o=a==null?void 0:a.message)!=null&&o.includes("Bad Request")?new Gp("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 Gp("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):a}}async function tI(){if(wt.EDITOR_URL)return wt.EDITOR_URL;try{return await Q(()=>be("/system-info/editor-url"),{retries:Y,onFailedAttempt:s=>{if(s.attemptNumber>=Y)throw s}})}catch{return bt.error("cannot retrieve editor-url from server"),"https://app.testim.io"}}function sI(s){return Q(()=>be("/grid",{companyId:s}),{retries:Y})}var rI=async()=>Q(()=>be("/grid/lt/config"),{retries:Y}),nI=async s=>Q(()=>be(`/labFeature/v2/project/${s}`),{retries:Y});function oI(s,e,t){return Q(()=>be(`/real-data/${e}?${t}&projectId=${s}`),{retries:Y})}function iI(s,e,t,r,n){return Q(()=>Be({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:Y})}function aI(s,e,t,r){return Q(()=>Be({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:Y})}function cI(s,e,t,r){return Q(()=>Be({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:Y})}function lI(s){return s.startsWith("/")?s:`/${s}`}function uI(s,e,t){let r=lI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Hp(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${As.guid()}${i||""}`,c=`${e}/${t}/${a}`,l=uI(c,"test-result-artifacts",s),u=Buffer.from(RS.gzip(r,{level:3})),p={file:{fileName:a,buffer:u}};return await Q(()=>OS(`/storage${l}`,{},p,{"X-Asset-Encoding":"gzip"}),{retries:Y,factor:1}),l}var dI=Lr.memoize(async(s,e,t,r)=>{if(!Lr.isEmpty(r))return await Hp(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${Vp(r)}:${e}:${t}`),pI=Lr.memoize(async(s,e,t,r,n)=>Lr.isEmpty(r)?void 0:await Hp(s,e,t,JSON.stringify((()=>{let i=Lr.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&(i[c]=CS.test.HIDDEN_PARAM)})}return i})(r)),"test-test-data","application/json"),(s,e,t,r)=>`${Vp(r)}:${e}:${t}`);function mI({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return Q(()=>Be({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:Y})}async function fI(s){try{return await be(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return bt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function hI(s,e){try{return await Bn("/tunnel",{companyId:s,routes:e})}catch(t){return bt.warn("could'nt get tunnel.",{err:t}),{}}}async function gI(s,e){try{return await Be({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){bt.warn("could'nt get tunnel.",{err:t});return}}async function yI(s,e){try{return await LS(`/tunnel/${e}`,{companyId:s})}catch(t){return bt.warn("could'nt get tunnel.",{err:t}),{}}}function wI(s){return ts.post({url:`${wt.SERVICES_HOST}/result/remoteRunFailure`,body:s})}async function bI({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${_S}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await Q(()=>be(o,{projectId:s}),{retries:Y})}catch(i){return bt.warn("could'nt get devices from headspin grid.",{err:i}),null}}Kp.exports={getAppDetails:VS,getS3Artifact:NS,getTestPlan:DS,saveTestPlanResult:US,updateTestStatus:qS,updateExecutionTests:jS,reportExecutionStarted:$S,reportExecutionFinished:BS,getTestPlanTestList:WS,getSuiteTestList:GS,getUsageForCurrentBillingPeriod:HS,getTestResults:zS,getGridByName:QS,releaseGridSlot:XS,keepAliveGrid:JS,getGridById:ZS,getAllGrids:sI,fetchLambdatestConfig:rI,getRealData:oI,updateTestResult:iI,clearTestResult:aI,saveRemoteStep:cI,getEditorUrl:tI,getLabFeaturesByProjectId:nI,uploadRunDataArtifact:dI,updateTestDataArtifact:pI,initializeUserWithAuth:eI,addTestRetry:mI,getHybridGridProvider:YS,loadSfdcCredential:MS,loadTest:FS,isTestResultCompleted:KS,getApplitoolsIntegrationData:fI,getCloudflareTunnel:hI,forceUpdateCloudflareTunnelRoutes:gI,deleteCloudflareTunnel:yI,updateRemoteRunFailure:wI,getMobileDevicesFromGrid:bI}});var Re={};W(Re,{getSessionPlayer:()=>_s,options:()=>Aa});var Wn,Aa,ka,_s,he=F(()=>{"use strict";Wn=require("path"),Aa={playerPath:void 0},_s=()=>{if(ka)return ka;let s=Ie();s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=ks(),t=e(),r=Aa.playerPath?(0,Wn.resolve)(Aa.playerPath,"src/background/sessionPlayerInit.ts"):(0,Wn.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),ka=n,n}});function vI(s){process.nextTick(()=>{if([ae.SELENIUM,ae.APPIUM].includes(s))try{(he(),w(Re)).getSessionPlayer(),require("jsdom")}catch{}})}async function Gn(s){let{project:e,token:t,lightweightMode:r,useLocalChromeDriver:n,useChromeLauncher:o,mode:i}=s,a=Boolean(r==null?void 0:r.general),c=Boolean(n||o),l=a?EI:TI;_a.log("before initializeUserWithAuth");let u=await Jp.memoize(async()=>(vI(i),await zp.initializeUserWithAuth({projectId:e,token:t,branchName:s.branch,lightweightMode:r,localGrid:c})),"initializeUserWithAuth",l,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:a,localGrid:c})();return _a.log("after initializeUserWithAuth"),Xp.initFromData(u.authData,s.project,s.token),u}var _a,zp,Jp,Xp,TI,EI,Yp=F(()=>{"use strict";_a=S(Ie()),zp=S(pe()),Jp=S(Ct()),Xp=S(ot());ee();TI=1e3*60*5,EI=1e3*60*60*10});var Na={};W(Na,{initializeUserWithAuth:()=>Gn,prepare:()=>La,prepareMockNetwork:()=>II});async function La(s){var o;let e=Promise.resolve(),t=!s.host&&!s.gridId&&!s.grid&&(!s.testPlan||s.testPlan.length===0),r=s.files.length!==0;(t&&r||s.useLocalChromeDriver)&&(s.chromeBinaryLocation=s.downloadBrowser?await Ta():s.chromeBinaryLocation,e=Pt.prepareChromeDriver({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((o=s.lightweightMode)==null?void 0:o.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==ae.EXTENSION&&await Pt.preparePlayer(s.playerLocation,s.canary),s.mode===ae.EXTENSION&&!s.ext&&await Pt.prepareExtension(s.extensionLocation);let n;if(s.installCustomExtension){let i=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);n=await Pt.prepareCustomExtension(s.installCustomExtension,i)}return await e,n}async function II(s){var i;SI.info("prepare MockNetwork",{location:s});let e=await Xi(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Qp*1e6)throw new Error(`${Oa} exceeded ${Qp}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Oa} cannot be parsed.${Vn.EOL}${a}`)}let n=new Zp.default;if(!n.validate(na,r)){let a=(i=n.errors)==null?void 0:i.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Vn.EOL);throw new Error(`${Oa} is malformed.${Vn.EOL}${a}`)}return r.entries}var Vn,Pt,Zp,Qp,Oa,SI,Da=F(()=>{"use strict";Vn=S(require("os"));M();ip();Pt=S(ks()),Zp=S(require("ajv"));ee();Ea();Yp();Qp=1,Oa="JSON file supplied to --mock-network-pattern",SI=(U(),w(H)).getLogger("prepare runner")});var Kn={};W(Kn,{registerExitHook:()=>Fa,registerProcessForCleanup:()=>Ma,reset:()=>xI});function Ma(s,e=process){async function t(r){await de(Ke(Hn,n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Dr.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(Dr.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Dr.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Dr.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Dr.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function Fa(s){Hn.push(s)}function xI(){Hn.splice(0,Hn.length)}var Dr,Hn,Mr=F(()=>{"use strict";U();M();Dr=G("process-handler"),Hn=[]});var Jn={};W(Jn,{getExtensionsUrl:()=>nm,getPlayerUrl:()=>Fr,getResolvedExtensionUrl:()=>$a});function nm(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?Ri:fr}/extension/testim-firefox-profile${t}`,n=`${e?Ci:fr}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function $a(s){let{chrome:e,firefox:t}=nm(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function Fr(s){let e=`${fr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Xn=F(()=>{"use strict";ne()});var Os=C((pN,lm)=>{"use strict";var om=(ne(),w(ce)),kI=require("analytics-node"),im=new kI("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),am=require("crypto").randomBytes(20).toString("hex");function AI(s){om.IS_ON_PREM||((!s||!s.userId)&&(s={anonymousId:am}),im.identify(s))}function _I(s,e){return cm("ci",s,e)}function cm(s,e,t){if(om.IS_ON_PREM)return;let r=s?{userId:s}:{anonymousId:am};im.track(Object.assign(r,{event:e,properties:t}))}lm.exports={identify:AI,track:cm,trackWithCIUser:_I}});function dm(s){return s.start&&um.track(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function pm(s){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,r=!1,n=!1,o=!1;if(s.start&&(o=!0),Number.isNaN(s.agentPort))throw new L("Agent port is not number");if(typeof s.agent=="string"&&e.some(a=>s.agent.includes(a))){let a=s.agent.split(",").map(c=>c.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(r=!0),a.includes("playground-selenium")&&(n=!0)}let i=Fr(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:r,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||i,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var um,mm=F(()=>{"use strict";Xn();um=S(Os());K()});function Qn(s){let{platform:e}=process;e==="win32"?(0,Yn.exec)(`start chrome ${s}`):e==="darwin"?(0,Yn.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,Yn.exec)(`google-chrome ${s}`)}var Yn,Ba=F(()=>{"use strict";Yn=require("child_process")});var Ls={};W(Ls,{doLogin:()=>MI,getProjectId:()=>LI,getToken:()=>NI});async function LI(){return gm("projectId")}async function NI(){return gm("token")}function hm(s,e){return Promise.race([s,qe(e).then(()=>{throw new ke("timeout")})])}async function DI(){let s=(await import("express")).default(),e=async function(){return hm(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>S(pe())),n=await r();Qn(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function MI({overwriteExisting:s=!0,projects:e=null}={}){let t=Wa.homedir(),r=Ga.join(t,".testim");if(await yt(r)&&!s)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 hm(Promise.resolve(DI()),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await fm(r,o);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(u=>({title:u.name,value:u}))});o.token=l.project.ci.token,o.projectId=l.project.id,await fm(r,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function fm(s,e){await Va.promises.writeFile(s,Zn.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function gm(s){let e=Wa.homedir(),t=Ga.join(e,".testim"),r=await yt(t),n={};if(r)try{n=Zn.parse((await Va.promises.readFile(t)).toString())}catch{}return n=n||{},n[s]}var Wa,Ga,Zn,Va,Ns=F(()=>{"use strict";Wa=S(require("os")),Ga=S(require("path")),Zn=S(require("yaml"));M();Va=require("fs");Ba()});var vm={};W(vm,{process:()=>VI});var Ha,wm,d,Ka,bm,ze,Ce,Ds,FI,Te,UI,qI,jI,$I,ym,Tm,BI,za,to,Em,WI,eo,it,GI,VI,Sm=F(()=>{"use strict";Ha=S(require("ms")),wm=S(require("chalk")),d=S(require("commander")),Ka=S(require("fs")),bm=S(require("url")),ze=S(require("lodash")),Ce=S(require("path"));M();Xn();mm();Ds=S(Ct());ee();K();Es();FI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Te=(s,e)=>(e.push(s),e),UI=s=>s.split(","),qI=(s,e)=>!s||s.length===0?e:s,jI=()=>{d.default.grid||d.default.gridId||(d.default.host||(d.default.host="ondemand.saucelabs.com"),d.default.port||(d.default.port=80))},$I=()=>{d.default.grid||d.default.gridId||(d.default.host||(d.default.host="hub-cloud.browserstack.com"),d.default.port||(d.default.port=80))},ym=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Tm=()=>{function s(h){return h.includes("-h, --help")}function e(h){return h.includes("--params [params-json-string]")}function t(h){return h.includes("--ext")||h.includes("--extension-path")}function r(h){return h.includes("--player-path")||h.includes("--player-require-path")}function n(h){return h.includes("--executionId")||h.includes("--source")||h.includes("--resultId")||h.includes("--remoteRunId")||h.includes("--schedulerId")}function o(h){return h.includes("--get-browser-timeout")||h.includes("--get-browser-retries")||h.includes("--get-session-timeout")||h.includes("--get-session-retries")||h.includes("--driver-request-timeout")||h.includes("--driver-request-retries")}function i(h){return h.includes("--user")}function a(h){return h.includes("shouldMonitorPerformance")}function c(h){return h.includes("--save-rca-locally")}function l(h){return h.includes("--exit-code-ignore-failing-tests")}function u(h){return h.includes("--high-speed")}function p(h){return h.includes("--urls")}function f(h){return h.includes("--test-start-timeout")}function m(h){return h.includes("--install-lazy-deps")}d.default.help(h=>h.split(`
17
- `).filter(y=>!t(y)&&!e(y)&&!s(y)&&!r(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!c(y)&&!l(y)&&!u(y)&&!p(y)&&!f(y)&&!m(y)).join(`
18
- `))},BI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(wm.default.yellow(`
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 hS(){let s=`${Op.BLOB_URL}/extension/sessionPlayer_LATEST_RELEASE`;return(await aS(s)).body.toString("utf8")}async function gS(s,e){if(!ga(s)||ga(s)&&e||Op.IS_ON_PREM)return s;let t=await hS();return`${s}-${t}`}function wa(){let s=nS();return Fn.resolve(s,"testim-bin")}function yS(){let s=wa();return Fn.resolve(s,"sessionPlayer.zip")}async function Mp(s,e,t=!1){try{return await Np(s,e),await cS(e,wa())}catch(r){if(t)throw r;return await Mp(s,e,!0)}}async function wS(s,e){Un.info("prepare player",{location:s,canary:e});let t=yS();return Lp.memoize(async()=>{let r=await gS(s,e);return await Mp(r,t),{}},"preparePlayer",Dp,[s,e,t])()}});var qp={};W(qp,{CHROMIUM_VERSION:()=>jn,downloadAndInstallChromium:()=>Ea});function bS(){let s=_r.type().toLowerCase();return s==="darwin"?_r.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?_r.arch()==="x64"?"win64":"win32":"linux"}async function Ea(){let s=bS(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new N(`Unsupported platform: ${s}`);let r=parseInt(jn,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${jn}/${n[s]}.zip`,a=qn.join(ba,n[s]),c=`${a}.zip`,l=qn.join(a,o[s]);if(await yt(l))return l;if(!await yt(c)){let p=(0,Ta.default)("Downloading Chromium").start();try{await Up.promises.mkdir(ba),await Rs(i,c)}catch(f){let m=`Failed to download Chromium: ${f.message}`;throw p.fail(m),new Error(m)}p.succeed()}let u=(0,Ta.default)("Extracting Chromium").start();try{await Tr(c,ba)}catch(p){let f=`Failed to extract Chromium: ${p.message}`;throw u.fail(f),new Error(f)}return u.succeed(),l}var Up,_r,qn,Ta,jn,ba,va=F(()=>{"use strict";Up=S(require("fs")),_r=S(require("os")),qn=S(require("path")),Ta=S(require("ora"));K();M();jn="1000968",ba=qn.join(na,`chrome-${jn}`)});var ot=C((QN,Gp)=>{"use strict";var $p=(rt(),y(ht)),Bp=(ne(),y(ce)),jp=(K(),y(Z)).ArgError,Or=(U(),y(H)).getLogger("testim-custom-token"),TS=Ct(),$e,Nr,$n,Ia,xa,Bn=null,Ra=null,Wp=5*60*1e3;async function ES(s,e){return Bn=s,Ra=e,await Sa()}function vS(s,e,t){$e=s.token,Bn=e,Ra=t,Nr=Ca($e),$n=s.refreshToken,Ia=s.ngrokToken,xa=s.isNgrokWhitelisted}function SS(s=Bn,e=Ra){return TS.memoize(()=>(Or.info("request to get cli token from server"),$p.post({url:`${Bp.SERVICES_HOST}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Wp*10,{projectId:s,token:e})()}async function IS(){return Or.info("request to refresh JWT cli token from server"),$e=(await $p.post({url:`${Bp.SERVICES_HOST}/auth/refreshToken`,body:{token:$e,refreshToken:$n}})).token,Nr=Ca($e),$e}function Sa(){return SS().then(s=>(Or.info("successfully get cli token from server"),$e=s.token,Nr=Ca($e),$n=s.refreshToken,Ia=s.ngrokToken,xa=s.isNgrokWhitelisted,$e)).catch(s=>{throw s.message.includes("Unauthorized")?new jp("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."):(Or.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Bn}),new jp(`While trying to retrieve CLI token, caught error: ${s}`))})}function Ca(s){return require("jsonwebtoken").decode(s).exp*1e3}function xS(){return Nr?Nr<Date.now()+4*Wp?IS().catch(s=>(Or.error("failed to refresh token, executing fallback",s),Sa())):Promise.resolve($e):Sa()}function RS(){return $n}function CS(){return $e?{uid:require("jsonwebtoken").decode($e).id,ngrokToken:Ia,isNgrokWhitelisted:xa}:{}}Gp.exports={init:ES,initFromData:vS,getCustomTokenV3:xS,getTokenV3UserData:CS,getRefreshToken:RS}});var ka={};W(ka,{isCi:()=>Pa});var Pa,Wn=F(()=>{"use strict";Pa=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var pe=C((ZN,zp)=>{"use strict";var Lr=require("lodash"),PS=require("pako"),Q=require("p-retry"),Hp=require("object-hash"),As=(M(),y(q)),wt=(ne(),y(ce)),kS=(ee(),y(fe)),ts=(rt(),y(ht)),AS=ot(),{ArgError:Vp}=(K(),y(Z)),{getLogger:_S}=(U(),y(H)),OS=As.getRunnerVersion(),bt=_S("testim service api"),Y=3,NS="/grid";function Dr(){return AS.getCustomTokenV3().then(s=>{if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}})}function Be({url:s,body:e,headers:t={},timeout:r,retry:n}){return Dr().then(o=>{let i=Object.assign({},t,o);return ts.post({url:`${wt.SERVICES_HOST}${s||""}`,body:e,headers:i,timeout:r,retry:n})})}function LS(s,e,t,r={},n){return Dr().then(o=>{let i=Object.assign({},r,o);return ts.postForm(`${wt.SERVICES_HOST}${s||""}`,e,t,i,n)})}function Gn(s,e){return Dr().then(t=>ts.put(`${wt.SERVICES_HOST}${s||""}`,e,t))}function DS(s,e){return Dr().then(t=>ts.deleteReq(`${wt.SERVICES_HOST}${s||""}`,e,t))}function be(s,e,t,r){return Dr().then(n=>ts.get(`${wt.SERVICES_HOST}${s||""}`,e,n,r,t))}function MS(s,e){return Q(()=>be(`/storage${s}`,null,{isBinary:!0},e),{retries:Y})}function FS(s,e){let t=r=>r==null?[]:typeof r=="string"&&JSON.parse(r)||r;return Q({retries:Y}).then(r=>r.map(n=>(n.testConfigIds=t(n.testConfigIds),n.beforeAllLabels=t(n.beforeAllLabels),n.testLabels=t(n.testLabels),n.afterAllLabels=t(n.afterAllLabels),n)))}async function US({branch:s,projectId:e}){let t=await Q(()=>be(`/branch/branchData/${s}`,{projectId:e}),{retries:Y});return t==null?void 0:t.sfdcCredential}function qS({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return Q(()=>be(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:Y})}function jS(s,e,t){return Q(()=>Be({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:Y})}function $S(s,e,t,r,n,o,i=Y){return Q(()=>Gn("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:OS,...o}),{retries:i})}function BS(s,e,t,r,n,o,i,a){return Q(()=>Gn("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:Y})}function WS({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:u}){let p=(Wn(),y(ka)).isCi;return Be({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:u,metadata:{isCiRun:p,localRunUserId:c,isLocalRun:l}},retry:3})}function GS(s,e,t,r,n={},o,i){let a=Date.now();return Q(()=>Gn("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:Y})}async function VS(s,e,t,r,n){return Q(()=>Be({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:Y})}function HS({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:u}){return Q(()=>Be({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:u}}),{retries:Y,factor:1})}async function KS({appId:s,projectId:e}){try{return await Q(()=>be(`/mobile-app/app/${s}?projectId=${e}`),{retries:Y,factor:1})}catch(t){bt.error("failed getting application details",{appId:s,error:t});return}}function zS(s){return Q(()=>be(`/plan/project/${s}/usage-current-billing-period`),{retries:Y}).catch(e=>{bt.error("failed getting usage for current billing period",{projectId:s,error:e})})}function JS(s,e,t){return Q(()=>be(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:Y})}function XS(s,e,t,r){return Q(()=>be(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:Y,factor:1})}function YS(s,e){return Be({url:`/grid/keep-alive?reqId=${As.guid()}`,body:{projectId:s,slots:e},timeout:1e4})}function QS(s,e,t,r,n){return Be({url:`/grid/release?reqId=${As.guid()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function ZS(s){return Be({url:"/grid/hybrid/provider",body:s})}function eI(s,e,t,r,n){return Q(()=>be("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:As.guid()}),{retries:Y})}function tI(s,e,t,r,n){return Q(()=>be(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:As.guid()}),{retries:Y})}async function sI({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n}){var o,i;try{return await Q(()=>ts.post({url:`${wt.SERVICES_HOST}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n}}),{retries:Y})}catch(a){throw bt.error("error initializing info from server",a),(o=a==null?void 0:a.message)!=null&&o.includes("Bad Request")?new Vp("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 Vp("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):a}}async function rI(){if(wt.EDITOR_URL)return wt.EDITOR_URL;try{return await Q(()=>be("/system-info/editor-url"),{retries:Y,onFailedAttempt:s=>{if(s.attemptNumber>=Y)throw s}})}catch{return bt.error("cannot retrieve editor-url from server"),"https://app.testim.io"}}function nI(s){return Q(()=>be("/grid",{companyId:s}),{retries:Y})}var oI=async()=>Q(()=>be("/grid/lt/config"),{retries:Y}),iI=async s=>Q(()=>be(`/labFeature/v2/project/${s}`),{retries:Y});function aI(s,e,t){return Q(()=>be(`/real-data/${e}?${t}&projectId=${s}`),{retries:Y})}function cI(s,e,t,r,n){return Q(()=>Be({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:Y})}function lI(s,e,t,r){return Q(()=>Be({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:Y})}function uI(s,e,t,r){return Q(()=>Be({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:Y})}function dI(s){return s.startsWith("/")?s:`/${s}`}function pI(s,e,t){let r=dI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Kp(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${As.guid()}${i||""}`,c=`${e}/${t}/${a}`,l=pI(c,"test-result-artifacts",s),u=Buffer.from(PS.gzip(r,{level:3})),p={file:{fileName:a,buffer:u}};return await Q(()=>LS(`/storage${l}`,{},p,{"X-Asset-Encoding":"gzip"}),{retries:Y,factor:1}),l}var mI=Lr.memoize(async(s,e,t,r)=>{if(!Lr.isEmpty(r))return await Kp(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${Hp(r)}:${e}:${t}`),fI=Lr.memoize(async(s,e,t,r,n)=>Lr.isEmpty(r)?void 0:await Kp(s,e,t,JSON.stringify((()=>{let i=Lr.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(c=>{i[c]&&(i[c]=kS.test.HIDDEN_PARAM)})}return i})(r)),"test-test-data","application/json"),(s,e,t,r)=>`${Hp(r)}:${e}:${t}`);function hI({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return Q(()=>Be({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:Y})}async function gI(s){try{return await be(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return bt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function yI(s,e){try{return await Gn("/tunnel",{companyId:s,routes:e})}catch(t){return bt.warn("could'nt get tunnel.",{err:t}),{}}}async function wI(s,e){try{return await Be({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){bt.warn("could'nt get tunnel.",{err:t});return}}async function bI(s,e){try{return await DS(`/tunnel/${e}`,{companyId:s})}catch(t){return bt.warn("could'nt get tunnel.",{err:t}),{}}}function TI(s){return ts.post({url:`${wt.SERVICES_HOST}/result/remoteRunFailure`,body:s})}async function EI({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${NS}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await Q(()=>be(o,{projectId:s}),{retries:Y})}catch(i){return bt.warn("could'nt get devices from headspin grid.",{err:i}),null}}zp.exports={getAppDetails:KS,getS3Artifact:MS,getTestPlan:FS,saveTestPlanResult:jS,updateTestStatus:$S,updateExecutionTests:BS,reportExecutionStarted:WS,reportExecutionFinished:GS,getTestPlanTestList:VS,getSuiteTestList:HS,getUsageForCurrentBillingPeriod:zS,getTestResults:XS,getGridByName:eI,releaseGridSlot:QS,keepAliveGrid:YS,getGridById:tI,getAllGrids:nI,fetchLambdatestConfig:oI,getRealData:aI,updateTestResult:cI,clearTestResult:lI,saveRemoteStep:uI,getEditorUrl:rI,getLabFeaturesByProjectId:iI,uploadRunDataArtifact:mI,updateTestDataArtifact:fI,initializeUserWithAuth:sI,addTestRetry:hI,getHybridGridProvider:ZS,loadSfdcCredential:US,loadTest:qS,isTestResultCompleted:JS,getApplitoolsIntegrationData:gI,getCloudflareTunnel:yI,forceUpdateCloudflareTunnelRoutes:wI,deleteCloudflareTunnel:bI,updateRemoteRunFailure:TI,getMobileDevicesFromGrid:EI}});var Re={};W(Re,{getSessionPlayer:()=>_s,options:()=>_a});var Vn,_a,Aa,_s,he=F(()=>{"use strict";Vn=require("path"),_a={playerPath:void 0},_s=()=>{if(Aa)return Aa;let s=Ie();s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=ks(),t=e(),r=_a.playerPath?(0,Vn.resolve)(_a.playerPath,"src/background/sessionPlayerInit.ts"):(0,Vn.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Aa=n,n}});function II(s){process.nextTick(()=>{if([ae.SELENIUM,ae.APPIUM].includes(s))try{(he(),y(Re)).getSessionPlayer(),require("jsdom")}catch{}})}async function Hn(s){let{project:e,token:t,lightweightMode:r,useLocalChromeDriver:n,useChromeLauncher:o,mode:i}=s,a=Boolean(r==null?void 0:r.general),c=Boolean(n||o),l=a?SI:vI;Oa.log("before initializeUserWithAuth");let u=await Xp.memoize(async()=>(II(i),await Jp.initializeUserWithAuth({projectId:e,token:t,branchName:s.branch,lightweightMode:r,localGrid:c})),"initializeUserWithAuth",l,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:a,localGrid:c})();return Oa.log("after initializeUserWithAuth"),Yp.initFromData(u.authData,s.project,s.token),u}var Oa,Jp,Xp,Yp,vI,SI,Qp=F(()=>{"use strict";Oa=S(Ie()),Jp=S(pe()),Xp=S(Ct()),Yp=S(ot());ee();vI=1e3*60*5,SI=1e3*60*60*10});var Da={};W(Da,{initializeUserWithAuth:()=>Hn,prepare:()=>La,prepareMockNetwork:()=>RI});async function La(s){var o;let e=Promise.resolve(),t=!s.host&&!s.gridId&&!s.grid&&(!s.testPlan||s.testPlan.length===0),r=s.files.length!==0;(t&&r||s.useLocalChromeDriver)&&(s.chromeBinaryLocation=s.downloadBrowser?await Ea():s.chromeBinaryLocation,e=Pt.prepareChromeDriver({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((o=s.lightweightMode)==null?void 0:o.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==ae.EXTENSION&&await Pt.preparePlayer(s.playerLocation,s.canary),s.mode===ae.EXTENSION&&!s.ext&&await Pt.prepareExtension(s.extensionLocation);let n;if(s.installCustomExtension){let i=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);n=await Pt.prepareCustomExtension(s.installCustomExtension,i)}return await e,n}async function RI(s){var i;xI.info("prepare MockNetwork",{location:s});let e=await Yi(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Zp*1e6)throw new Error(`${Na} exceeded ${Zp}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Na} cannot be parsed.${Kn.EOL}${a}`)}let n=new em.default;if(!n.validate(oa,r)){let a=(i=n.errors)==null?void 0:i.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Kn.EOL);throw new Error(`${Na} is malformed.${Kn.EOL}${a}`)}return r.entries}var Kn,Pt,em,Zp,Na,xI,Ma=F(()=>{"use strict";Kn=S(require("os"));M();ap();Pt=S(ks()),em=S(require("ajv"));ee();va();Qp();Zp=1,Na="JSON file supplied to --mock-network-pattern",xI=(U(),y(H)).getLogger("prepare runner")});var Jn={};W(Jn,{registerExitHook:()=>Ua,registerProcessForCleanup:()=>Fa,reset:()=>CI});function Fa(s,e=process){async function t(r){await de(ze(zn,n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Mr.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(Mr.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Mr.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Mr.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Mr.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function Ua(s){zn.push(s)}function CI(){zn.splice(0,zn.length)}var Mr,zn,Fr=F(()=>{"use strict";U();M();Mr=G("process-handler"),zn=[]});var Yn={};W(Yn,{getExtensionsUrl:()=>om,getPlayerUrl:()=>Ur,getResolvedExtensionUrl:()=>Ba});function om(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?Ci:hr}/extension/testim-firefox-profile${t}`,n=`${e?Pi:hr}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function Ba(s){let{chrome:e,firefox:t}=om(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function Ur(s){let e=`${hr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Qn=F(()=>{"use strict";ne()});var Os=C((mL,um)=>{"use strict";var im=(ne(),y(ce)),_I=require("analytics-node"),am=new _I("sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",{flushAt:1}),cm=require("crypto").randomBytes(20).toString("hex");function OI(s){im.IS_ON_PREM||((!s||!s.userId)&&(s={anonymousId:cm}),am.identify(s))}function NI(s,e){return lm("ci",s,e)}function lm(s,e,t){if(im.IS_ON_PREM)return;let r=s?{userId:s}:{anonymousId:cm};am.track(Object.assign(r,{event:e,properties:t}))}um.exports={identify:OI,track:lm,trackWithCIUser:NI}});function pm(s){return s.start&&dm.track(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function mm(s){let e=["playground-playwright","playground-puppeteer","playground-selenium"],t=!1,r=!1,n=!1,o=!1;if(s.start&&(o=!0),Number.isNaN(s.agentPort))throw new N("Agent port is not number");if(typeof s.agent=="string"&&e.some(a=>s.agent.includes(a))){let a=s.agent.split(",").map(c=>c.trim());a.includes("playground-playwright")&&(t=!0),a.includes("playground-puppeteer")&&(r=!0),a.includes("playground-selenium")&&(n=!0)}let i=Ur(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,installPlaygroundPlaywrightDeps:t,installPlaygroundPuppeteerDeps:r,installPlaygroundSeleniumDeps:n,startTestimBrowser:o,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||i,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var dm,fm=F(()=>{"use strict";Qn();dm=S(Os());K()});function eo(s){let{platform:e}=process;e==="win32"?(0,Zn.exec)(`start chrome ${s}`):e==="darwin"?(0,Zn.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,Zn.exec)(`google-chrome ${s}`)}var Zn,Wa=F(()=>{"use strict";Zn=require("child_process")});var Ns={};W(Ns,{doLogin:()=>UI,getProjectId:()=>DI,getToken:()=>MI});async function DI(){return ym("projectId")}async function MI(){return ym("token")}function gm(s,e){return Promise.race([s,qe(e).then(()=>{throw new ke("timeout")})])}async function FI(){let s=(await import("express")).default(),e=async function(){return gm(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>S(pe())),n=await r();eo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function UI({overwriteExisting:s=!0,projects:e=null}={}){let t=Ga.homedir(),r=Va.join(t,".testim");if(await yt(r)&&!s)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 gm(Promise.resolve(FI()),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,c.succeed(),await hm(r,o);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(u=>({title:u.name,value:u}))});o.token=l.project.ci.token,o.projectId=l.project.id,await hm(r,o);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function hm(s,e){await Ha.promises.writeFile(s,to.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function ym(s){let e=Ga.homedir(),t=Va.join(e,".testim"),r=await yt(t),n={};if(r)try{n=to.parse((await Ha.promises.readFile(t)).toString())}catch{}return n=n||{},n[s]}var Ga,Va,to,Ha,Ls=F(()=>{"use strict";Ga=S(require("os")),Va=S(require("path")),to=S(require("yaml"));M();Ha=require("fs");Wa()});var Sm={};W(Sm,{process:()=>KI});var Ka,bm,d,za,Tm,Je,Ce,Ds,qI,Te,jI,$I,BI,WI,wm,Em,GI,Ja,ro,vm,VI,so,it,HI,KI,Im=F(()=>{"use strict";Ka=S(require("ms")),bm=S(require("chalk")),d=S(require("commander")),za=S(require("fs")),Tm=S(require("url")),Je=S(require("lodash")),Ce=S(require("path"));M();Qn();fm();Ds=S(Ct());ee();K();Es();qI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Te=(s,e)=>(e.push(s),e),jI=s=>s.split(","),$I=(s,e)=>!s||s.length===0?e:s,BI=()=>{d.default.grid||d.default.gridId||(d.default.host||(d.default.host="ondemand.saucelabs.com"),d.default.port||(d.default.port=80))},WI=()=>{d.default.grid||d.default.gridId||(d.default.host||(d.default.host="hub-cloud.browserstack.com"),d.default.port||(d.default.port=80))},wm=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Em=()=>{function s(h){return h.includes("-h, --help")}function e(h){return h.includes("--params [params-json-string]")}function t(h){return h.includes("--ext")||h.includes("--extension-path")}function r(h){return h.includes("--player-path")||h.includes("--player-require-path")}function n(h){return h.includes("--executionId")||h.includes("--source")||h.includes("--resultId")||h.includes("--remoteRunId")||h.includes("--schedulerId")}function o(h){return h.includes("--get-browser-timeout")||h.includes("--get-browser-retries")||h.includes("--get-session-timeout")||h.includes("--get-session-retries")||h.includes("--driver-request-timeout")||h.includes("--driver-request-retries")}function i(h){return h.includes("--user")}function a(h){return h.includes("shouldMonitorPerformance")}function c(h){return h.includes("--save-rca-locally")}function l(h){return h.includes("--exit-code-ignore-failing-tests")}function u(h){return h.includes("--high-speed")}function p(h){return h.includes("--urls")}function f(h){return h.includes("--test-start-timeout")}function m(h){return h.includes("--install-lazy-deps")}d.default.help(h=>h.split(`
17
+ `).filter(w=>!t(w)&&!e(w)&&!s(w)&&!r(w)&&!n(w)&&!a(w)&&!i(w)&&!o(w)&&!c(w)&&!l(w)&&!u(w)&&!p(w)&&!f(w)&&!m(w)).join(`
18
+ `))},GI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(bm.default.yellow(`
19
19
  WARNING: ${s} is deprecated. ${t}
20
- `))},za=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:to,argv:Em,stdout:WI,exit:eo,cwd:it}=global.process,GI=["trace","debug","info","warn","error","silent"];d.default.description("Testim.io CLI").option("-h --help","output usage information",Tm).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",Te,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Te,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Te,[]).option("run [file-glob-pattern]","codeful test files to run",Te,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Te,[]).option("-l, --label [label]","labels to search test by",Te,[]).option("-n, --name [test-name]","test name to run",Te,[]).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",UI).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",null).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",Te,[]).option("--test-plan-id [test-plan-id]","test plan to run",Te,[]).option("--suite [suite-name]","suite to run",Te,[]).option("--suite-id [suite-id]","suite ID to run",Te,[]).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",Te,[]).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)",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]","the device unique id").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("-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(to.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,Ha.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,Ha.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: ${za.join("/")}`,Te,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Te,[]).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",Te,[]).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)",Te,[]).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)",Te,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(Em);VI=async()=>{var g,y,b,I,T,v,x,A,N,B,$,k;d.default.inspect&&require("inspector").open(d.default.inspect);let s={},e={},t=[],r={};if(!Em.slice(2).length)throw Tm(),new Vt;if(d.default.requireCredentials){let E=await Promise.resolve().then(()=>(Ns(),Ls)),P=await E.getProjectId(),j=await E.getToken();(!P||!j)&&await E.doLogin()}if(d.default.login)return await(await Promise.resolve().then(()=>(Ns(),Ls))).doLogin(),{loginMode:!0};if(d.default.init)return{initCodimMode:!0,initTestProject:d.default.init};if(d.default.version){let E="Testim CLI Version: ";to.npm_package_version&&(console.log(E,to.npm_package_version),eo(0));let P=Gt();P&&(console.log(E,P),eo(0)),console.log("Could not find version, please check the package.json manually"),eo(0)}if(d.default.installLazyDeps)return{installLazyDepsMode:!0};d.default.disableFileCache&&Ds.disable();let n=d.default.fileCacheLocation||d.default.usePrefechedData||d.default.createPrefechedData;if(n){let E=Ce.resolve(n);Ds.setCacheLocation(E)}if(d.default.usePrefechedData&&Ds.disableCacheMiss(),d.default.playerRequirePath){let E=Ce.resolve(d.default.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",E);let P=Ce.join(E,"tsconfig.node.json"),z=require("ts-node").register({project:P,ignore:[/node_modules/,new RegExp(`^${ze.escapeRegExp(Ce.relative(it(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:z.config.options.paths,baseUrl:z.config.options.baseUrl}),(he(),w(Re)).options.playerPath=E;let oe=require("module"),Me=oe.prototype.require;oe.prototype.require=function(R){return R==="rox-alias"?Me.call(this,"rox-node"):Me.apply(this,arguments)}}if(d.default.caFile&&(global.caFileContent=Ka.readFileSync(d.default.caFile)),d.default.proxy&&(global.proxyUri=d.default.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),d.default.proxyForGrid&&!d.default.proxy)throw new L("missing --proxy option");if(dm(d.default))return pm(d.default);try{let E={};d.default.configFile?E=require(Ce.join(it(),d.default.configFile)).config:d.default.optionsFile&&(E=require(Ce.join(it(),d.default.optionsFile))),E&&typeof E.then=="function"&&(E=await E),Object.keys(E).forEach(P=>{let j=FI(P);d.default[j]=qI(d.default[j],E[P])})}catch(E){throw E.message=`Unable to read options file: ${E.message}`,E}if(d.default.tunneld)return{tunnel:!0,tunnelPort:d.default.tunnelPort,tunnelRoutes:d.default.tunnelRoutes,tunnelRoutesOutput:d.default.tunnelRoutesOutput,tunnelHostHeader:d.default.tunnelHostHeader,tunnelRegion:d.default.tunnelRegion,tunnelDiagnostics:d.default.tunnelDiagnostics,tunnelUseHttpAddress:d.default.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:d.default.token,project:d.default.project};let o=((g=d.default.testConfig)==null?void 0:g.length)||((y=d.default.testConfigId)==null?void 0:y.length),i=((b=d.default.testPlan)==null?void 0:b.length)||((I=d.default.testPlanId)==null?void 0:I.length),a=((T=d.default.suite)==null?void 0:T.length)||((v=d.default.suiteId)==null?void 0:v.length);if(d.default.seleniumCapsFile)try{r=require(Ce.join(it(),d.default.seleniumCapsFile))}catch(E){throw new L(`Failed to parse selenium caps file file error: ${E.message}`)}if((x=d.default.reporters)!=null&&x.includes("junit")&&!d.default.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!d.default.tunnel&&d.default.externalLambdatestTunnelId)throw new L("missing --tunnel parameter");if(!d.default.tunnel&&d.default.externalLambdatestUseWss)throw new L("missing --tunnel parameter");if(!d.default.tunnel&&[d.default.tunnelPort,d.default.tunnelHostHeader,d.default.tunnelRegion,d.default.tunnelDiagnostics].some(Boolean))throw new L("missing --tunnel parameter");if(d.default.chromeExtraPrefs)try{e=require(Ce.join(it(),d.default.chromeExtraPrefs))}catch(E){throw new L(`Failed to read/open chrome extra prefs file error: ${E.message}`)}if(d.default.chromeExtraArgs){let E=d.default.chromeExtraArgs.split(",");for(let P of E){let[j]=P.split("=");ym.includes(j)||d.default.useLocalChromeDriver||d.default.useChromeLauncher?(t.push(P),j==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${j}), allowed values: ${JSON.stringify(ym)}`)}}if(d.default.paramsFile)try{s=Object.assign({},s,require(Ce.join(it(),d.default.paramsFile)))}catch(E){throw new L(`Failed to read/open params file error: ${E.message}`)}if(d.default.params)try{s=Object.assign({},s,JSON.parse(d.default.params))}catch(E){throw new L(`Failed to parse params string error: ${E.message}`)}if(d.default.sauceUser&&!d.default.sauceKey||!d.default.sauceUser&&d.default.sauceKey)throw new L("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(d.default.sauceUser&&d.default.sauceKey&&(jI(),d.default.saucelabs={},d.default.saucelabs.username=d.default.sauceUser,d.default.saucelabs.accessKey=d.default.sauceKey),d.default.sauceOptions)try{let E=require(Ce.join(it(),d.default.sauceOptions)),P=E.platformName&&["ios","android"].includes(E.platformName.toLowerCase());if(E.browserName){let z=E.browserName.toLowerCase();switch(z){case"microsoftedge":d.default.browser="edge";break;default:d.default.browser=z}}d.default.browser==="edge"&&parseFloat(E.version)>=xn&&(d.default.browser="edge-chromium");let j=parseFloat(E.version)<50&&!["dev","beta"].includes(E.version);if(!P&&d.default.browser==="chrome"&&j)throw new L("The minimum chrome supported version is 50.0");d.default.saucelabs=Object.assign({},d.default.saucelabs,E)}catch(E){throw new L(`Failed to parse saucelabs options file error: ${E.message}`)}if(d.default.browserstackUser&&!d.default.browserstackKey||!d.default.browserstackUser&&d.default.browserstackKey)throw new L("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(d.default.browserstackUser&&d.default.browserstackKey&&($I(),d.default.browserstack={},d.default.browserstack["browserstack.user"]=d.default.browserstackUser,d.default.browserstack["browserstack.key"]=d.default.browserstackKey),d.default.browserstackOptions)try{let E=require(Ce.join(it(),d.default.browserstackOptions)),P=E.platform&&["mac","android"].includes(E.platform.toLowerCase());if(E.browserName&&(d.default.browser=E.browserName.toLowerCase()),d.default.browser==="edge"&&parseFloat(E.browser_version)>=xn&&(d.default.browser="edge-chromium"),!P&&parseFloat(E.browser_version)<50&&d.default.browser==="chrome")throw new L("The minimum chrome supported version is 50.0");d.default.browserstack=Object.assign({},d.default.browserstack,E)}catch(E){throw new L(`Failed to parse browserstack options file error: ${E.message}`)}if(d.default.perfecto={},d.default.perfectoToken&&(d.default.perfecto.securityToken=d.default.perfectoToken),d.default.perfectoOptions)try{let E=require(Ce.join(it(),d.default.perfectoOptions)),P={location:"US East",securityToken:d.default.perfectoToken};d.default.perfecto=Object.assign({},P,E)}catch(E){throw new L(`Failed to parse perfecto options file error: ${E.message}`)}if(d.default.testobjectSauce={},d.default.testobjectKey&&(d.default.testobjectSauce.testobjectApiKey=d.default.testobjectKey),d.default.testobjectOptions)try{let E=require(Ce.join(it(),d.default.testobjectOptions)),P={testobjectApiKey:d.default.testobjectKey};d.default.testobjectSauce=Object.assign({},P,E)}catch(E){throw new L(`Failed to parse test object options file error: ${E.message}`)}if(!d.default.project){let P=await(await Promise.resolve().then(()=>(Ns(),Ls))).getProjectId();if(P)d.default.project=P;else throw new L("missing project-id info, either --login to provide new credentials or use --project <project-id>")}d.default.mode||(d.default.mode=d.default.run.length?"selenium":"extension"),d.default.testConfig&&(d.default.testConfig=[d.default.testConfig].flat()),d.default.testConfigId&&(d.default.testConfigId=[d.default.testConfigId].flat()),d.default.retries=!d.default.retries||typeof d.default.retries=="boolean"?1:Number(d.default.retries)+1,d.default.browserTimeout=!d.default.browserTimeout||typeof d.default.browserTimeout=="boolean"?60*1e3:d.default.browserTimeout,d.default.newBrowserWaitTimeout=!d.default.newBrowserWaitTimeout||typeof d.default.newBrowserWaitTimeout=="boolean"?10*60*1e3:d.default.newBrowserWaitTimeout*60*1e3,d.default.getBrowserTimeout||(d.default.getBrowserTimeout=d.default.browserTimeout),d.default.getBrowserRetries||(d.default.getBrowserRetries=Math.round(d.default.newBrowserWaitTimeout/d.default.browserTimeout)),d.default.getSessionTimeout=d.default.browserTimeout<d.default.getSessionTimeout?d.default.getSessionTimeout:d.default.browserTimeout,d.default.driverRequestTimeout=d.default.browserTimeout<d.default.driverRequestTimeout?d.default.driverRequestTimeout:d.default.browserTimeout;let c=Boolean(d.default.timeout);if(d.default.timeout=!d.default.timeout||typeof d.default.timeout=="boolean"?10*60*1e3:d.default.timeout,d.default.beforeParallel=!d.default.beforeParallel||typeof d.default.beforeParallel=="boolean"?1:Number(d.default.beforeParallel),d.default.parallel=!d.default.parallel||typeof d.default.parallel=="boolean"?1:Number(d.default.parallel),d.default.afterParallel=!d.default.afterParallel||typeof d.default.afterParallel=="boolean"?1:Number(d.default.afterParallel),d.default.parallel>1&&d.default.run&&!d.default.gridId&&!d.default.grid&&(!d.default.testPlan||d.default.testPlan.length===0)&&!((A=d.default.testPlanId)!=null&&A.length)&&WI.isTTY&&!d.default.headless&&!to.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||eo(0)),d.default.tunnelPort=!d.default.tunnelPort||typeof d.default.tunnelPort=="boolean"?"80":d.default.tunnelPort,(N=d.default).port&&(N.port=Number(d.default.port)),d.default.retries<=0||Number.isNaN(d.default.retries))throw new L("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(d.default.retries>21)throw new L("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(!d.default.token){let P=await(await Promise.resolve().then(()=>(Ns(),Ls))).getToken();if(P)d.default.token=P;else throw new L("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(d.default.browserTimeout<=0||Number.isNaN(d.default.browserTimeout))throw new L("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d.default.newBrowserWaitTimeout<=0||Number.isNaN(d.default.newBrowserWaitTimeout))throw new L("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d.default.timeout<=0||Number.isNaN(d.default.timeout))throw new L("test run timeout could not be a negative number, --timeout <run-timeout>");if(d.default.beforeParallel<=0||Number.isNaN(d.default.beforeParallel))throw new L("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d.default.parallel<=0||Number.isNaN(d.default.parallel))throw new L("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d.default.afterParallel<=0||Number.isNaN(d.default.afterParallel))throw new L("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![ae.EXTENSION,ae.SELENIUM,ae.APPIUM].includes(d.default.mode))throw new L(`runner mode <${d.default.mode}> is not supported`);if(d.default.mode!==ae.SELENIUM&&d.default.disableNativeEvents)throw new L("disable-native-events is only applicable in selenium mode");if(!d.default.browser&&!o&&!i&&(d.default.browser="chrome"),d.default.appiumLogLevel||(d.default.appiumLogLevel="silent"),!GI.includes(d.default.appiumLogLevel))throw new L(`runner appium-log-level <${d.default.appiumLogLevel}> is not supported`);if(d.default.testPlan&&d.default.testPlan.length===0&&d.default.testPlanId&&d.default.testPlanId.length===0){if(typeof d.default.host!="string"&&typeof d.default.grid!="string"&&typeof d.default.gridId!="string"&&d.default.run.length===0&&!d.default.useLocalChromeDriver&&!d.default.useChromeLauncher&&!d.default.createPrefechedData)throw new L("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(d.default.testId.length||d.default.label.length||d.default.name.length||o||d.default.browser||a||d.default.useLocalChromeDriver||d.default.useChromeLauncher)throw new L("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&&(d.default.beforeParallel!==1||d.default.afterParallel!==1))throw new L("cannot set --before-parallel or --after-parallel without --test-plan option");if((d.default.testId.length||i||d.default.label.length||d.default.name.length||a)&&d.default.file)throw new L("Cannot pass codeful automation tests with --testId --label --name or --suite");if([d.default.host,d.default.grid,d.default.gridId].filter(Boolean).length>1)throw new L("please define exactly one of --grid or --grid-id or --host");if((B=d.default.host)!=null&&B.includes("/")&&(/^(f|ht)tps?:\/\//i.test(d.default.host)||(d.default.host=`http://${d.default.host}`),d.default.host=bm.parse(d.default.host).hostname),d.default.resultLabel.length){d.default.resultLabel=d.default.resultLabel.map(P=>P.trim()).filter(Boolean);let E=d.default.resultLabel.filter(P=>P.length>=250).filter(Boolean);if(d.default.branch==="auto-detect"&&d.default.resultLabel.includes("auto-detect-branch")&&Ir()&&d.default.resultLabel.unshift(Ir()),E.length)throw new L("A result label cannot exceed 250 characters")}let u=$a(d.default),p=Fr(d.default);if(!d.default.w3cCapabilities&&!d.default.oldCapabilities)throw new L("cannot set --w3c-capabilities and --old-capabilities options as false");if(($=d.default).protocol||($.protocol=d.default.port===443?"https":"http"),!["http","https"].includes(d.default.protocol))throw new L("invalid --protocol value, allow --protocol http or https");if(d.default.rerunFailedByRunId&&d.default.branch)throw new L("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(d.default.rerunFailedByRunId&&(a||d.default.name.length||d.default.testId.length||d.default.label.length||i))throw new L("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(d.default.run.length){let E=require("glob");if(d.default.files=ze.flatMap(d.default.run,P=>E.sync(P)),d.default.files.length===0)throw new L(`No files found at path '${d.default.run}'.`)}else d.default.files=[];if(d.default.setRetention&&!ze.inRange(ze.parseInt(d.default.setRetention),1,11))throw new L("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)");(k=d.default).setRetention&&(k.setRetention=Number(d.default.setRetention));let f="is no longer supported, please use --override-mapping-file";if(d.default.mockNetworkHar)throw new L(`--mock-network-har ${f}`);if(d.default.mockNetworkPattern)throw new L(`--mock-network-pattern ${f}`);if(d.default.disableMockNetwork&&d.default.overrideMappingFile)throw new L("You can either use --disable-mock-network or --override-mapping-file");if(!d.default.collectCodeCoverage&&d.default.codeCoverageSourceMapPath)throw new L("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!d.default.collectCodeCoverage&&d.default.codeCoverageReporter.length)throw new L("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!d.default.collectCodeCoverage&&d.default.codeCoverageInclude.length)throw new L("cannot set --code-coverage-include without passing --collect-code-coverage");if(d.default.collectCodeCoverage&&d.default.codeCoverageReporter&&ze.difference(d.default.codeCoverageReporter,za).length){let E=ze.difference(d.default.codeCoverageReporter,za);throw new L(`invalid --code-coverage-reporter parameters ${E.join("/")}`)}d.default.codeCoverageReporter=d.default.codeCoverageReporter.length===0?["html","text"]:d.default.codeCoverageReporter,d.default.codeCoverageInclude=d.default.codeCoverageInclude.length===0?["src/**"]:d.default.codeCoverageInclude;let m={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},h=Object.keys(m).filter(E=>Boolean(d.default[E]));if(d.default.mode!==ae.EXTENSION&&h.length){let E=h.length>1?"are":"is";throw new L(`${h.map(P=>m[P]).join(" and ")} ${E} only applicable in extension mode`)}if(d.default.tmsFieldFile)try{let E=Ka.readFileSync(d.default.tmsFieldFile);d.default.tmsCustomFields=JSON.parse(E)}catch(E){throw new L(`failed to parse field file error: ${E.message}`)}if(d.default.highSpeed&&(BI("--high-speed"," --turbo-mode"),d.default.turboMode=!0),d.default.deviceUdid&&(d.default.deviceModel||d.default.osVersion))throw new L("It is not possible to use --osVersion or --deviceModel with --device-udid. device-udid is unique and cannot be combined with another flag");if(d.default.lightweightMode)try{let E={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"},P=typeof d.default.lightweightMode=="string"?JSON.parse(d.default.lightweightMode):{};d.default.lightweightMode=Object.assign({},E,P)}catch(E){throw new L(`failed to parse lightweightMode settings error: ${E.message}`)}else d.default.turboMode&&d.default.mode===ae.EXTENSION&&(d.default.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 d.default.baseUrl=="boolean")throw new L("base url cannot be used as a flag, and must contain a string value");return{testId:[d.default.testId].flat(),name:[d.default.name].flat(),label:[d.default.label].flat(),suites:[d.default.suite].flat(),suiteIds:[d.default.suiteId].flat(),testPlan:[d.default.testPlan].flat(),testPlanIds:[d.default.testPlanId].flat(),files:[d.default.files].flat(),webpackConfig:d.default.webpackConfig,reportFile:d.default.reportFile,urls:d.default.urls,reportFileClassname:d.default.overrideReportFileClassname,reporters:d.default.reporters,project:d.default.project,host:d.default.host,headless:d.default.headless,useLocalChromeDriver:d.default.useLocalChromeDriver,chromeBinaryLocation:d.default.chromeBinaryLocation,useChromeLauncher:d.default.useChromeLauncher,port:d.default.port,grid:d.default.grid,gridId:d.default.gridId,disableNativeEvents:d.default.disableNativeEvents,saucelabs:d.default.saucelabs,browserstack:d.default.browserstack,baseUrl:d.default.baseUrl,branch:(d.default.branch==="auto-detect"?Ir():d.default.branch)||"master",autoDetect:d.default.branch==="auto-detect",token:d.default.token,userParamsData:s,mode:d.default.mode,isRegressionBaselineRun:d.default.isRegressionBaselineRun,browser:d.default.browser,beforeParallel:d.default.beforeParallel,parallel:d.default.parallel,afterParallel:d.default.afterParallel,canary:d.default.canary,rerunFailedByRunId:d.default.rerunFailedByRunId,disableGridCheck:d.default.disableGridCheck,disableTimeoutRetry:d.default.disableTimeoutRetry,resultLabels:d.default.resultLabel,path:d.default.path,protocol:d.default.protocol,perfecto:d.default.perfecto,experitestToken:d.default.experitestToken,testobjectSauce:d.default.testobjectSauce,gridUsername:d.default.gridUsername,gridPassword:d.default.gridPassword,overrideExecutionName:d.default.overrideExecutionName,tmsSuppressReporting:Boolean(d.default.suppressTmsReporting)||Boolean(d.default.tmsSuppressReporting),tmsRunId:d.default.tmsRunId,tmsCustomFields:d.default.tmsCustomFields,proxyForGrid:d.default.proxyForGrid,retentionDays:d.default.setRetention,passZeroTests:Boolean(d.default.passZeroTests),runQuarantinedTests:Boolean(d.default.runQuarantinedTests),deviceModel:d.default.deviceModel,deviceUdid:d.default.deviceUdid,osVersion:d.default.osVersion,appId:d.default.appId,appiumLogLevel:d.default.appiumLogLevel,ext:d.default.ext,extensionLocation:[d.default.extensionPath||u].flat(),extensionPath:d.default.extensionPath,playerLocation:d.default.playerPath||p,playerPath:d.default.playerPath,playerRequirePath:d.default.playerRequirePath,tunnel:d.default.tunnel,tunnelPort:d.default.tunnelPort,tunnelRoutes:d.default.tunnelRoutes,tunnelRoutesOutput:d.default.tunnelRoutesOutput,tunnelHostHeader:d.default.tunnelHostHeader,tunnelRegion:d.default.tunnelRegion,tunnelDiagnostics:d.default.tunnelDiagnostics,tunnelUseHttpAddress:d.default.tunnelUseHttpAddress,externalLambdatestTunnelId:d.default.externalLambdatestTunnelId,externalLambdatestUseWss:d.default.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(d.default.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(d.default.externalLambdatestMitm),beforeTest:d.default.beforeTest,afterTest:d.default.afterTest,beforeSuite:d.default.beforeSuite,afterSuite:d.default.afterSuite,timeout:d.default.timeout,timeoutWasGiven:c,browserTimeout:d.default.browserTimeout,newBrowserWaitTimeout:d.default.newBrowserWaitTimeout,getBrowserTimeout:d.default.getBrowserTimeout,getBrowserRetries:d.default.getBrowserRetries,getSessionTimeout:d.default.getSessionTimeout,getSessionRetries:d.default.getSessionRetries,driverRequestTimeout:d.default.driverRequestTimeout,driverRequestRetries:d.default.driverRequestRetries,testStartTimeout:d.default.testStartTimeout,testConfigNames:d.default.testConfig,testConfigIds:d.default.testConfigId,overrideMappingFile:d.default.overrideMappingFile,disableMockNetwork:d.default.disableMockNetwork,codeCoverageUrlFilter:d.default.codeCoverageUrlFilter,collectCodeCoverage:d.default.collectCodeCoverage,codeCoverageReportPath:d.default.codeCoverageReportPath,codeCoverageSourceMapPath:d.default.codeCoverageSourceMapPath,codeCoverageReporter:d.default.codeCoverageReporter,codeCoverageInclude:d.default.codeCoverageInclude,executionId:d.default.executionId,remoteRunId:d.default.remoteRunId,schedulerId:d.default.schedulerId,source:d.default.source,resultId:d.default.resultId,installCustomExtension:d.default.installCustomExtension,w3cCapabilities:d.default.w3cCapabilities,oldCapabilities:d.default.oldCapabilities,chromeBlockLocation:d.default.chromeBlockLocation,chromeUserDataDir:d.default.chromeUserDataDir,retries:d.default.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:d.default.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:d.default.monitorPerformance,user:d.default.user,lightweightMode:d.default.lightweightMode,createPrefechedData:d.default.createPrefechedData,saveRCALocally:d.default.saveRcaLocally,exitCodeIgnoreFailingTests:d.default.exitCodeIgnoreFailingTests,disableSockets:d.default.disableSockets,intersections:{labels:d.default.intersectWithLabel.length?[d.default.intersectWithLabel].flat():void 0,suiteNames:d.default.intersectWithSuite.length?[d.default.intersectWithSuite].flat():void 0,suiteIds:d.default.intersectWithSuiteId.length?[d.default.intersectWithSuiteId].flat():void 0},downloadBrowser:d.default.downloadBrowser}}});var KI={};var Ms,Im,xm,so,HI,Rm=F(()=>{"use strict";Ms=S(require("path")),Im=require("fs"),xm=require("child_process"),so=Ms.resolve(__filename),HI=!so.includes("node_modules")&&Ms.dirname(so).endsWith("src");HI&&!(0,Im.existsSync)(Ms.resolve(so,"..","..","..","webdriverio","build","index.js"))&&(console.log("Hi developer, we're initializing the runner dev env for the first time for you \u2764\uFE0F"),(0,xm.execSync)("yarn workspace @testim/webdriverio build",{cwd:Ms.resolve(so,"..","..")}))});var Tt={};W(Tt,{installAllLazyDependencies:()=>XI,lazyRequire:()=>ss});async function ss(s,e={}){let t=Ur.getPackageIfInstalledLocally(s);if(t)return t;let r;e.silent||(r=(0,Cm.default)(`Installing ${s} before first usage...`).start());try{let n=await JI(s);return r&&r.succeed(),n}catch(n){zI.warn("failed to install dependency lazily",{dependency:s,err:n});let o=km(s),i=`${s}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw r&&r.fail(l),n}}async function JI(s){return Fs.has(s)||(Fs.set(s,Pm(s)),Fs.get(s).catch(()=>{Fs.delete(s)})),Fs.get(s)}async function Pm(s){let e=Ur.getPackageIfInstalledLocally(s);if(e)return e;let t=km(s),r=`${s}@${t}`;return await Ur.installPackageLocally(Jt(),r),es(s)}async function XI(){let s=Object.keys(Ja.lazyDependencies);for(let e of s)await Pm(e)}function km(s){let e=Object.entries(Ja.lazyDependencies).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Cm,Ur,Ja,zI,Fs,Je=F(()=>{"use strict";Cm=S(require("ora")),Ur=S(kr());U();M();Ja=S(Cn());Cr();zI=G("lazy-require"),Fs=new Map});var Lm={};W(Lm,{init:()=>QI});async function QI(s){var b,I;let e=typeof s=="string"?s:"";(typeof s!="string"||!s.trim())&&(e=(await(0,Ya.default)({type:"text",name:"project",message:"Please enter Project name",validate:v=>String(v).length>3})).project);let t=kt.resolve(e);At.existsSync(t)&&At.readdirSync(t).length!==0&&(console.log(`${t} is not empty. Quitting...`),process.exit(1));let r=t.substr(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1),n=(0,_m.default)(r);if(!n.validForNewPackages){let T=`The name '${r}' is not a valid package name:`;throw console.log(ro.default.red(T)),n.errors&&n.errors.forEach(v=>console.log(ro.default.red(v))),n.warnings&&n.warnings.forEach(v=>console.log(ro.default.yellowBright(`warning: ${v}`))),new L(`${T}
20
+ `))},Ja=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:ro,argv:vm,stdout:VI,exit:so,cwd:it}=global.process,HI=["trace","debug","info","warn","error","silent"];d.default.description("Testim.io CLI").option("-h --help","output usage information",Em).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",Te,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Te,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Te,[]).option("run [file-glob-pattern]","codeful test files to run",Te,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Te,[]).option("-l, --label [label]","labels to search test by",Te,[]).option("-n, --name [test-name]","test name to run",Te,[]).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",jI).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",null).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",Te,[]).option("--test-plan-id [test-plan-id]","test plan to run",Te,[]).option("--suite [suite-name]","suite to run",Te,[]).option("--suite-id [suite-id]","suite ID to run",Te,[]).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",Te,[]).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)",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]","the device unique id").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("-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(ro.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,Ka.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,Ka.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: ${Ja.join("/")}`,Te,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Te,[]).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",Te,[]).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)",Te,[]).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)",Te,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(vm);KI=async()=>{var g,w,b,I,T,v,x,A,L,B,$,k;d.default.inspect&&require("inspector").open(d.default.inspect);let s={},e={},t=[],r={};if(!vm.slice(2).length)throw Em(),new Vt;if(d.default.requireCredentials){let E=await Promise.resolve().then(()=>(Ls(),Ns)),P=await E.getProjectId(),j=await E.getToken();(!P||!j)&&await E.doLogin()}if(d.default.login)return await(await Promise.resolve().then(()=>(Ls(),Ns))).doLogin(),{loginMode:!0};if(d.default.init)return{initCodimMode:!0,initTestProject:d.default.init};if(d.default.version){let E="Testim CLI Version: ";ro.npm_package_version&&(console.log(E,ro.npm_package_version),so(0));let P=Gt();P&&(console.log(E,P),so(0)),console.log("Could not find version, please check the package.json manually"),so(0)}if(d.default.installLazyDeps)return{installLazyDepsMode:!0};d.default.disableFileCache&&Ds.disable();let n=d.default.fileCacheLocation||d.default.usePrefechedData||d.default.createPrefechedData;if(n){let E=Ce.resolve(n);Ds.setCacheLocation(E)}if(d.default.usePrefechedData&&Ds.disableCacheMiss(),d.default.playerRequirePath){let E=Ce.resolve(d.default.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",E);let P=Ce.join(E,"tsconfig.node.json"),z=require("ts-node").register({project:P,ignore:[/node_modules/,new RegExp(`^${Je.escapeRegExp(Ce.relative(it(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:z.config.options.paths,baseUrl:z.config.options.baseUrl}),(he(),y(Re)).options.playerPath=E;let oe=require("module"),Me=oe.prototype.require;oe.prototype.require=function(R){return R==="rox-alias"?Me.call(this,"rox-node"):Me.apply(this,arguments)}}if(d.default.caFile&&(global.caFileContent=za.readFileSync(d.default.caFile)),d.default.proxy&&(global.proxyUri=d.default.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),d.default.proxyForGrid&&!d.default.proxy)throw new N("missing --proxy option");if(pm(d.default))return mm(d.default);try{let E={};d.default.configFile?E=require(Ce.join(it(),d.default.configFile)).config:d.default.optionsFile&&(E=require(Ce.join(it(),d.default.optionsFile))),E&&typeof E.then=="function"&&(E=await E),Object.keys(E).forEach(P=>{let j=qI(P);d.default[j]=$I(d.default[j],E[P])})}catch(E){throw E.message=`Unable to read options file: ${E.message}`,E}if(d.default.tunneld)return{tunnel:!0,tunnelPort:d.default.tunnelPort,tunnelRoutes:d.default.tunnelRoutes,tunnelRoutesOutput:d.default.tunnelRoutesOutput,tunnelHostHeader:d.default.tunnelHostHeader,tunnelRegion:d.default.tunnelRegion,tunnelDiagnostics:d.default.tunnelDiagnostics,tunnelUseHttpAddress:d.default.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:d.default.token,project:d.default.project};let o=((g=d.default.testConfig)==null?void 0:g.length)||((w=d.default.testConfigId)==null?void 0:w.length),i=((b=d.default.testPlan)==null?void 0:b.length)||((I=d.default.testPlanId)==null?void 0:I.length),a=((T=d.default.suite)==null?void 0:T.length)||((v=d.default.suiteId)==null?void 0:v.length);if(d.default.seleniumCapsFile)try{r=require(Ce.join(it(),d.default.seleniumCapsFile))}catch(E){throw new N(`Failed to parse selenium caps file file error: ${E.message}`)}if((x=d.default.reporters)!=null&&x.includes("junit")&&!d.default.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!d.default.tunnel&&d.default.externalLambdatestTunnelId)throw new N("missing --tunnel parameter");if(!d.default.tunnel&&d.default.externalLambdatestUseWss)throw new N("missing --tunnel parameter");if(!d.default.tunnel&&[d.default.tunnelPort,d.default.tunnelHostHeader,d.default.tunnelRegion,d.default.tunnelDiagnostics].some(Boolean))throw new N("missing --tunnel parameter");if(d.default.chromeExtraPrefs)try{e=require(Ce.join(it(),d.default.chromeExtraPrefs))}catch(E){throw new N(`Failed to read/open chrome extra prefs file error: ${E.message}`)}if(d.default.chromeExtraArgs){let E=d.default.chromeExtraArgs.split(",");for(let P of E){let[j]=P.split("=");wm.includes(j)||d.default.useLocalChromeDriver||d.default.useChromeLauncher?(t.push(P),j==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${j}), allowed values: ${JSON.stringify(wm)}`)}}if(d.default.paramsFile)try{s=Object.assign({},s,require(Ce.join(it(),d.default.paramsFile)))}catch(E){throw new N(`Failed to read/open params file error: ${E.message}`)}if(d.default.params)try{s=Object.assign({},s,JSON.parse(d.default.params))}catch(E){throw new N(`Failed to parse params string error: ${E.message}`)}if(d.default.sauceUser&&!d.default.sauceKey||!d.default.sauceUser&&d.default.sauceKey)throw new N("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(d.default.sauceUser&&d.default.sauceKey&&(BI(),d.default.saucelabs={},d.default.saucelabs.username=d.default.sauceUser,d.default.saucelabs.accessKey=d.default.sauceKey),d.default.sauceOptions)try{let E=require(Ce.join(it(),d.default.sauceOptions)),P=E.platformName&&["ios","android"].includes(E.platformName.toLowerCase());if(E.browserName){let z=E.browserName.toLowerCase();switch(z){case"microsoftedge":d.default.browser="edge";break;default:d.default.browser=z}}d.default.browser==="edge"&&parseFloat(E.version)>=Cn&&(d.default.browser="edge-chromium");let j=parseFloat(E.version)<50&&!["dev","beta"].includes(E.version);if(!P&&d.default.browser==="chrome"&&j)throw new N("The minimum chrome supported version is 50.0");d.default.saucelabs=Object.assign({},d.default.saucelabs,E)}catch(E){throw new N(`Failed to parse saucelabs options file error: ${E.message}`)}if(d.default.browserstackUser&&!d.default.browserstackKey||!d.default.browserstackUser&&d.default.browserstackKey)throw new N("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(d.default.browserstackUser&&d.default.browserstackKey&&(WI(),d.default.browserstack={},d.default.browserstack["browserstack.user"]=d.default.browserstackUser,d.default.browserstack["browserstack.key"]=d.default.browserstackKey),d.default.browserstackOptions)try{let E=require(Ce.join(it(),d.default.browserstackOptions)),P=E.platform&&["mac","android"].includes(E.platform.toLowerCase());if(E.browserName&&(d.default.browser=E.browserName.toLowerCase()),d.default.browser==="edge"&&parseFloat(E.browser_version)>=Cn&&(d.default.browser="edge-chromium"),!P&&parseFloat(E.browser_version)<50&&d.default.browser==="chrome")throw new N("The minimum chrome supported version is 50.0");d.default.browserstack=Object.assign({},d.default.browserstack,E)}catch(E){throw new N(`Failed to parse browserstack options file error: ${E.message}`)}if(d.default.perfecto={},d.default.perfectoToken&&(d.default.perfecto.securityToken=d.default.perfectoToken),d.default.perfectoOptions)try{let E=require(Ce.join(it(),d.default.perfectoOptions)),P={location:"US East",securityToken:d.default.perfectoToken};d.default.perfecto=Object.assign({},P,E)}catch(E){throw new N(`Failed to parse perfecto options file error: ${E.message}`)}if(d.default.testobjectSauce={},d.default.testobjectKey&&(d.default.testobjectSauce.testobjectApiKey=d.default.testobjectKey),d.default.testobjectOptions)try{let E=require(Ce.join(it(),d.default.testobjectOptions)),P={testobjectApiKey:d.default.testobjectKey};d.default.testobjectSauce=Object.assign({},P,E)}catch(E){throw new N(`Failed to parse test object options file error: ${E.message}`)}if(!d.default.project){let P=await(await Promise.resolve().then(()=>(Ls(),Ns))).getProjectId();if(P)d.default.project=P;else throw new N("missing project-id info, either --login to provide new credentials or use --project <project-id>")}d.default.mode||(d.default.mode=d.default.run.length?"selenium":"extension"),d.default.testConfig&&(d.default.testConfig=[d.default.testConfig].flat()),d.default.testConfigId&&(d.default.testConfigId=[d.default.testConfigId].flat()),d.default.retries=!d.default.retries||typeof d.default.retries=="boolean"?1:Number(d.default.retries)+1,d.default.browserTimeout=!d.default.browserTimeout||typeof d.default.browserTimeout=="boolean"?60*1e3:d.default.browserTimeout,d.default.newBrowserWaitTimeout=!d.default.newBrowserWaitTimeout||typeof d.default.newBrowserWaitTimeout=="boolean"?10*60*1e3:d.default.newBrowserWaitTimeout*60*1e3,d.default.getBrowserTimeout||(d.default.getBrowserTimeout=d.default.browserTimeout),d.default.getBrowserRetries||(d.default.getBrowserRetries=Math.round(d.default.newBrowserWaitTimeout/d.default.browserTimeout)),d.default.getSessionTimeout=d.default.browserTimeout<d.default.getSessionTimeout?d.default.getSessionTimeout:d.default.browserTimeout,d.default.driverRequestTimeout=d.default.browserTimeout<d.default.driverRequestTimeout?d.default.driverRequestTimeout:d.default.browserTimeout;let c=Boolean(d.default.timeout);if(d.default.timeout=!d.default.timeout||typeof d.default.timeout=="boolean"?10*60*1e3:d.default.timeout,d.default.beforeParallel=!d.default.beforeParallel||typeof d.default.beforeParallel=="boolean"?1:Number(d.default.beforeParallel),d.default.parallel=!d.default.parallel||typeof d.default.parallel=="boolean"?1:Number(d.default.parallel),d.default.afterParallel=!d.default.afterParallel||typeof d.default.afterParallel=="boolean"?1:Number(d.default.afterParallel),d.default.parallel>1&&d.default.run&&!d.default.gridId&&!d.default.grid&&(!d.default.testPlan||d.default.testPlan.length===0)&&!((A=d.default.testPlanId)!=null&&A.length)&&VI.isTTY&&!d.default.headless&&!ro.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||so(0)),d.default.tunnelPort=!d.default.tunnelPort||typeof d.default.tunnelPort=="boolean"?"80":d.default.tunnelPort,(L=d.default).port&&(L.port=Number(d.default.port)),d.default.retries<=0||Number.isNaN(d.default.retries))throw new N("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(d.default.retries>21)throw new N("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(!d.default.token){let P=await(await Promise.resolve().then(()=>(Ls(),Ns))).getToken();if(P)d.default.token=P;else throw new N("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(d.default.browserTimeout<=0||Number.isNaN(d.default.browserTimeout))throw new N("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d.default.newBrowserWaitTimeout<=0||Number.isNaN(d.default.newBrowserWaitTimeout))throw new N("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d.default.timeout<=0||Number.isNaN(d.default.timeout))throw new N("test run timeout could not be a negative number, --timeout <run-timeout>");if(d.default.beforeParallel<=0||Number.isNaN(d.default.beforeParallel))throw new N("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d.default.parallel<=0||Number.isNaN(d.default.parallel))throw new N("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d.default.afterParallel<=0||Number.isNaN(d.default.afterParallel))throw new N("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![ae.EXTENSION,ae.SELENIUM,ae.APPIUM].includes(d.default.mode))throw new N(`runner mode <${d.default.mode}> is not supported`);if(d.default.mode!==ae.SELENIUM&&d.default.disableNativeEvents)throw new N("disable-native-events is only applicable in selenium mode");if(!d.default.browser&&!o&&!i&&(d.default.browser="chrome"),d.default.appiumLogLevel||(d.default.appiumLogLevel="silent"),!HI.includes(d.default.appiumLogLevel))throw new N(`runner appium-log-level <${d.default.appiumLogLevel}> is not supported`);if(d.default.testPlan&&d.default.testPlan.length===0&&d.default.testPlanId&&d.default.testPlanId.length===0){if(typeof d.default.host!="string"&&typeof d.default.grid!="string"&&typeof d.default.gridId!="string"&&d.default.run.length===0&&!d.default.useLocalChromeDriver&&!d.default.useChromeLauncher&&!d.default.createPrefechedData)throw new N("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(d.default.testId.length||d.default.label.length||d.default.name.length||o||d.default.browser||a||d.default.useLocalChromeDriver||d.default.useChromeLauncher)throw new N("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&&(d.default.beforeParallel!==1||d.default.afterParallel!==1))throw new N("cannot set --before-parallel or --after-parallel without --test-plan option");if((d.default.testId.length||i||d.default.label.length||d.default.name.length||a)&&d.default.file)throw new N("Cannot pass codeful automation tests with --testId --label --name or --suite");if([d.default.host,d.default.grid,d.default.gridId].filter(Boolean).length>1)throw new N("please define exactly one of --grid or --grid-id or --host");if((B=d.default.host)!=null&&B.includes("/")&&(/^(f|ht)tps?:\/\//i.test(d.default.host)||(d.default.host=`http://${d.default.host}`),d.default.host=Tm.parse(d.default.host).hostname),d.default.resultLabel.length){d.default.resultLabel=d.default.resultLabel.map(P=>P.trim()).filter(Boolean);let E=d.default.resultLabel.filter(P=>P.length>=250).filter(Boolean);if(d.default.branch==="auto-detect"&&d.default.resultLabel.includes("auto-detect-branch")&&xr()&&d.default.resultLabel.unshift(xr()),E.length)throw new N("A result label cannot exceed 250 characters")}let u=Ba(d.default),p=Ur(d.default);if(!d.default.w3cCapabilities&&!d.default.oldCapabilities)throw new N("cannot set --w3c-capabilities and --old-capabilities options as false");if(($=d.default).protocol||($.protocol=d.default.port===443?"https":"http"),!["http","https"].includes(d.default.protocol))throw new N("invalid --protocol value, allow --protocol http or https");if(d.default.rerunFailedByRunId&&d.default.branch)throw new N("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(d.default.rerunFailedByRunId&&(a||d.default.name.length||d.default.testId.length||d.default.label.length||i))throw new N("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(d.default.run.length){let E=require("glob");if(d.default.files=Je.flatMap(d.default.run,P=>E.sync(P)),d.default.files.length===0)throw new N(`No files found at path '${d.default.run}'.`)}else d.default.files=[];if(d.default.setRetention&&!Je.inRange(Je.parseInt(d.default.setRetention),1,11))throw new N("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)");(k=d.default).setRetention&&(k.setRetention=Number(d.default.setRetention));let f="is no longer supported, please use --override-mapping-file";if(d.default.mockNetworkHar)throw new N(`--mock-network-har ${f}`);if(d.default.mockNetworkPattern)throw new N(`--mock-network-pattern ${f}`);if(d.default.disableMockNetwork&&d.default.overrideMappingFile)throw new N("You can either use --disable-mock-network or --override-mapping-file");if(!d.default.collectCodeCoverage&&d.default.codeCoverageSourceMapPath)throw new N("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!d.default.collectCodeCoverage&&d.default.codeCoverageReporter.length)throw new N("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!d.default.collectCodeCoverage&&d.default.codeCoverageInclude.length)throw new N("cannot set --code-coverage-include without passing --collect-code-coverage");if(d.default.collectCodeCoverage&&d.default.codeCoverageReporter&&Je.difference(d.default.codeCoverageReporter,Ja).length){let E=Je.difference(d.default.codeCoverageReporter,Ja);throw new N(`invalid --code-coverage-reporter parameters ${E.join("/")}`)}d.default.codeCoverageReporter=d.default.codeCoverageReporter.length===0?["html","text"]:d.default.codeCoverageReporter,d.default.codeCoverageInclude=d.default.codeCoverageInclude.length===0?["src/**"]:d.default.codeCoverageInclude;let m={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},h=Object.keys(m).filter(E=>Boolean(d.default[E]));if(d.default.mode!==ae.EXTENSION&&h.length){let E=h.length>1?"are":"is";throw new N(`${h.map(P=>m[P]).join(" and ")} ${E} only applicable in extension mode`)}if(d.default.tmsFieldFile)try{let E=za.readFileSync(d.default.tmsFieldFile);d.default.tmsCustomFields=JSON.parse(E)}catch(E){throw new N(`failed to parse field file error: ${E.message}`)}if(d.default.highSpeed&&(GI("--high-speed"," --turbo-mode"),d.default.turboMode=!0),d.default.deviceUdid&&(d.default.deviceModel||d.default.osVersion))throw new N("It is not possible to use --osVersion or --deviceModel with --device-udid. device-udid is unique and cannot be combined with another flag");if(d.default.lightweightMode)try{let E={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"},P=typeof d.default.lightweightMode=="string"?JSON.parse(d.default.lightweightMode):{};d.default.lightweightMode=Object.assign({},E,P)}catch(E){throw new N(`failed to parse lightweightMode settings error: ${E.message}`)}else d.default.turboMode&&d.default.mode===ae.EXTENSION&&(d.default.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 d.default.baseUrl=="boolean")throw new N("base url cannot be used as a flag, and must contain a string value");return{testId:[d.default.testId].flat(),name:[d.default.name].flat(),label:[d.default.label].flat(),suites:[d.default.suite].flat(),suiteIds:[d.default.suiteId].flat(),testPlan:[d.default.testPlan].flat(),testPlanIds:[d.default.testPlanId].flat(),files:[d.default.files].flat(),webpackConfig:d.default.webpackConfig,reportFile:d.default.reportFile,urls:d.default.urls,reportFileClassname:d.default.overrideReportFileClassname,reporters:d.default.reporters,project:d.default.project,host:d.default.host,headless:d.default.headless,useLocalChromeDriver:d.default.useLocalChromeDriver,chromeBinaryLocation:d.default.chromeBinaryLocation,useChromeLauncher:d.default.useChromeLauncher,port:d.default.port,grid:d.default.grid,gridId:d.default.gridId,disableNativeEvents:d.default.disableNativeEvents,saucelabs:d.default.saucelabs,browserstack:d.default.browserstack,baseUrl:d.default.baseUrl,branch:(d.default.branch==="auto-detect"?xr():d.default.branch)||"master",autoDetect:d.default.branch==="auto-detect",token:d.default.token,userParamsData:s,mode:d.default.mode,isRegressionBaselineRun:d.default.isRegressionBaselineRun,browser:d.default.browser,beforeParallel:d.default.beforeParallel,parallel:d.default.parallel,afterParallel:d.default.afterParallel,canary:d.default.canary,rerunFailedByRunId:d.default.rerunFailedByRunId,disableGridCheck:d.default.disableGridCheck,disableTimeoutRetry:d.default.disableTimeoutRetry,resultLabels:d.default.resultLabel,path:d.default.path,protocol:d.default.protocol,perfecto:d.default.perfecto,experitestToken:d.default.experitestToken,testobjectSauce:d.default.testobjectSauce,gridUsername:d.default.gridUsername,gridPassword:d.default.gridPassword,overrideExecutionName:d.default.overrideExecutionName,tmsSuppressReporting:Boolean(d.default.suppressTmsReporting)||Boolean(d.default.tmsSuppressReporting),tmsRunId:d.default.tmsRunId,tmsCustomFields:d.default.tmsCustomFields,proxyForGrid:d.default.proxyForGrid,retentionDays:d.default.setRetention,passZeroTests:Boolean(d.default.passZeroTests),runQuarantinedTests:Boolean(d.default.runQuarantinedTests),deviceModel:d.default.deviceModel,deviceUdid:d.default.deviceUdid,osVersion:d.default.osVersion,appId:d.default.appId,appiumLogLevel:d.default.appiumLogLevel,ext:d.default.ext,extensionLocation:[d.default.extensionPath||u].flat(),extensionPath:d.default.extensionPath,playerLocation:d.default.playerPath||p,playerPath:d.default.playerPath,playerRequirePath:d.default.playerRequirePath,tunnel:d.default.tunnel,tunnelPort:d.default.tunnelPort,tunnelRoutes:d.default.tunnelRoutes,tunnelRoutesOutput:d.default.tunnelRoutesOutput,tunnelHostHeader:d.default.tunnelHostHeader,tunnelRegion:d.default.tunnelRegion,tunnelDiagnostics:d.default.tunnelDiagnostics,tunnelUseHttpAddress:d.default.tunnelUseHttpAddress,externalLambdatestTunnelId:d.default.externalLambdatestTunnelId,externalLambdatestUseWss:d.default.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(d.default.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(d.default.externalLambdatestMitm),beforeTest:d.default.beforeTest,afterTest:d.default.afterTest,beforeSuite:d.default.beforeSuite,afterSuite:d.default.afterSuite,timeout:d.default.timeout,timeoutWasGiven:c,browserTimeout:d.default.browserTimeout,newBrowserWaitTimeout:d.default.newBrowserWaitTimeout,getBrowserTimeout:d.default.getBrowserTimeout,getBrowserRetries:d.default.getBrowserRetries,getSessionTimeout:d.default.getSessionTimeout,getSessionRetries:d.default.getSessionRetries,driverRequestTimeout:d.default.driverRequestTimeout,driverRequestRetries:d.default.driverRequestRetries,testStartTimeout:d.default.testStartTimeout,testConfigNames:d.default.testConfig,testConfigIds:d.default.testConfigId,overrideMappingFile:d.default.overrideMappingFile,disableMockNetwork:d.default.disableMockNetwork,codeCoverageUrlFilter:d.default.codeCoverageUrlFilter,collectCodeCoverage:d.default.collectCodeCoverage,codeCoverageReportPath:d.default.codeCoverageReportPath,codeCoverageSourceMapPath:d.default.codeCoverageSourceMapPath,codeCoverageReporter:d.default.codeCoverageReporter,codeCoverageInclude:d.default.codeCoverageInclude,executionId:d.default.executionId,remoteRunId:d.default.remoteRunId,schedulerId:d.default.schedulerId,source:d.default.source,resultId:d.default.resultId,installCustomExtension:d.default.installCustomExtension,w3cCapabilities:d.default.w3cCapabilities,oldCapabilities:d.default.oldCapabilities,chromeBlockLocation:d.default.chromeBlockLocation,chromeUserDataDir:d.default.chromeUserDataDir,retries:d.default.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:d.default.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:d.default.monitorPerformance,user:d.default.user,lightweightMode:d.default.lightweightMode,createPrefechedData:d.default.createPrefechedData,saveRCALocally:d.default.saveRcaLocally,exitCodeIgnoreFailingTests:d.default.exitCodeIgnoreFailingTests,disableSockets:d.default.disableSockets,intersections:{labels:d.default.intersectWithLabel.length?[d.default.intersectWithLabel].flat():void 0,suiteNames:d.default.intersectWithSuite.length?[d.default.intersectWithSuite].flat():void 0,suiteIds:d.default.intersectWithSuiteId.length?[d.default.intersectWithSuiteId].flat():void 0},downloadBrowser:d.default.downloadBrowser}}});var JI={};var Ms,xm,Rm,no,zI,Cm=F(()=>{"use strict";Ms=S(require("path")),xm=require("fs"),Rm=require("child_process"),no=Ms.resolve(__filename),zI=!no.includes("node_modules")&&Ms.dirname(no).endsWith("src");zI&&!(0,xm.existsSync)(Ms.resolve(no,"..","..","..","webdriverio","build","index.js"))&&(console.log("Hi developer, we're initializing the runner dev env for the first time for you \u2764\uFE0F"),(0,Rm.execSync)("yarn workspace @testim/webdriverio build",{cwd:Ms.resolve(no,"..","..")}))});var Tt={};W(Tt,{installAllLazyDependencies:()=>QI,lazyRequire:()=>ss});async function ss(s,e={}){let t=qr.getPackageIfInstalledLocally(s);if(t)return t;let r;e.silent||(r=(0,Pm.default)(`Installing ${s} before first usage...`).start());try{let n=await YI(s);return r&&r.succeed(),n}catch(n){XI.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Am(s),i=`${s}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw r&&r.fail(l),n}}async function YI(s){return Fs.has(s)||(Fs.set(s,km(s)),Fs.get(s).catch(()=>{Fs.delete(s)})),Fs.get(s)}async function km(s){let e=qr.getPackageIfInstalledLocally(s);if(e)return e;let t=Am(s),r=`${s}@${t}`;return await qr.installPackageLocally(Jt(),r),es(s)}async function QI(){let s=Object.keys(Xa.lazyDependencies);for(let e of s)await km(e)}function Am(s){let e=Object.entries(Xa.lazyDependencies).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Pm,qr,Xa,XI,Fs,Xe=F(()=>{"use strict";Pm=S(require("ora")),qr=S(Ar());U();M();Xa=S(kn());Pr();XI=G("lazy-require"),Fs=new Map});var Lm={};W(Lm,{init:()=>ex});async function ex(s){var b,I;let e=typeof s=="string"?s:"";(typeof s!="string"||!s.trim())&&(e=(await(0,Qa.default)({type:"text",name:"project",message:"Please enter Project name",validate:v=>String(v).length>3})).project);let t=kt.resolve(e);At.existsSync(t)&&At.readdirSync(t).length!==0&&(console.log(`${t} is not empty. Quitting...`),process.exit(1));let r=t.substr(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1),n=(0,Om.default)(r);if(!n.validForNewPackages){let T=`The name '${r}' is not a valid package name:`;throw console.log(oo.default.red(T)),n.errors&&n.errors.forEach(v=>console.log(oo.default.red(v))),n.warnings&&n.warnings.forEach(v=>console.log(oo.default.yellowBright(`warning: ${v}`))),new N(`${T}
21
21
  validation errors:
22
22
  ${((b=n.errors)==null?void 0:b.join(`
23
23
  `))||""}
24
24
  warnings:
25
25
  ${((I=n.warnings)==null?void 0:I.join(`
26
- `))||""}`)}let i=(await(0,Ya.default)({type:"toggle",name:"isJs",message:"Add support for TypeScript?",initial:!0,active:"no",inactive:"yes"})).isJs?"template.js":"template.ts",a="codim",c=kt.join(__dirname,a,i),l=kt.join(process.cwd(),e),u=(0,Xa.default)(`Creating new test project in ${l}`).start();await Pn(c,l);let p=kt.join(__dirname,a,i,"package.json"),f=kt.join(process.cwd(),e,"package.json"),h=(await At.promises.readFile(p)).toString().replace("~testim-codeful-test-project~",r);await At.promises.writeFile(f,h);let g="node_modules",y=kt.join(process.cwd(),e,".gitignore");await At.promises.writeFile(y,g),u.succeed(),u=(0,Xa.default)("Installing dependencies").start(),await YI("npm install",{cwd:l}),u.succeed(),console.log(`Testim Dev Kit project folder successfully created in ${l}.`)}var At,kt,Am,Xa,ro,Ya,_m,Om,YI,Nm=F(()=>{"use strict";At=S(require("fs")),kt=S(require("path")),Am=S(require("child_process")),Xa=S(require("ora")),ro=S(require("chalk")),Ya=S(require("prompts")),_m=S(require("validate-npm-package-name")),Om=require("util");K();Yi();YI=(0,Om.promisify)(Am.exec)});var Za={};W(Za,{preloadTests:()=>Qa});async function Qa(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Mm.memoize(async()=>{let t=await Ke(s.testId,r=>Fm.loadTest({...e,testId:r}),{concurrency:2});return Dm.keyBy(t,"testData.id")},"loadTests",ZI,[e,s.testId])()}var Dm,Mm,Fm,ZI,no=F(()=>{"use strict";Dm=S(require("lodash")),Mm=S(Ct()),Fm=S(pe());M();ZI=1e3*60*60*10});var ec={};W(ec,{checkNpmVersion:()=>sx,getPackageVersion:()=>Bm});function Bm(){return Gt()}async function sx(){if(!et)try{let s=await de(tx(),5e3,"The API call to NPM timed out"),e=Bm();e&&qm.lt(e,s)&&console.log(Um.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){ex.warn("Failed to get NPM version",{err:s})}}var Um,qm,jm,$m,ex,tx,tc=F(()=>{"use strict";Um=S(require("chalk")),qm=S(require("semver"));M();ne();jm=S(kr()),$m=S(Ct());U();ex=G("npm-driver"),tx=$m.memoize(()=>jm.getLatestPackageVersion("@testim/testim-cli"),"getNpmVersion")});var sc,rx,Us,Wm,Gm,rc,Vm,Hm=F(()=>{"use strict";M();K();U();Je();sc=G("testimNgrok"),rx=".whitelisted-ngrok.testim.io",Us="",Gm=async(s,e={})=>{if(!e.ngrokToken)throw new L("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${Oe()}-${s.projectData.projectId}${rx}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await ss("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(sc.info("replace https to http"),Us=o.replace("https://","http://")):Us=o,s.tunnelDiagnostics&&rc(),s.baseUrl=Us},rc=async(s=!0)=>{try{let t=(await ss("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===Us);console.log("ngrok stats",n),sc.info("ngrok stats",{tunnel:n})}catch(e){sc.error("error collecting ngrok stats",{err:e})}s&&(Wm=setTimeout(()=>rc(),1e4))},Vm=async s=>{if(!Us)return;clearTimeout(Wm),s.tunnelDiagnostics&&await rc(!1),await(await ss("ngrok")).disconnect(Us)}});var _t,oc,Km,qs,ox,ix,nc,oo,ao,io,ax,zm,Jm,Xm=F(()=>{"use strict";_t=S(require("os")),oc=S(require("fs")),Km=S(require("child_process"));M();qs=S(pe()),ox="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",ix={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"}},nc=_t.tmpdir(),oo=`${nc}/cloudflared`,ao=null,io=null,ax=async()=>{if(await yt(oo))return;let e=ix[_t.platform()+_t.arch()];if(!e)throw new Error(`tunnel on ${_t.platform()+_t.arch()} platform is not supported.`);let t=e.extract?nc+e.path:oo;await Rs(`${ox}/${e.path}`,t),e.extract&&await br(t,nc),await oc.promises.chmod(oo,"755")},zm=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([qs.getCloudflareTunnel(s.company.companyId,t),ax()]);ao=r._id,io=Km.spawn(oo,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await qs.forceUpdateCloudflareTunnelRoutes(s.company.companyId,ao),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await oc.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Jm=async s=>{let e=[];return ao&&e.push(qs.deleteCloudflareTunnel(s.company.companyId,ao)),io&&e.push(new Promise((t,r)=>{io.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),io.kill()})),await Promise.all(e)}});var me={};W(me,{featureFlagsService:()=>lo});var J,Qm,lx,ux,dx,Ym,co,ic,lo,le=F(()=>{"use strict";J=S(require("rox-node"));U();M();ne();Qm=G("FeatureFlagsService"),lx=!et&&!0&&!xi,ux=2e4,dx=60*60*24,Ym=["labs","disabled","enabled"],co=class extends J.default.Variant{constructor(e="disabled"){super(e,Ym)}getValue(){let e=super.getValue();return Ym.includes(e)?e:(Qm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},ic=class{constructor(){this.flags={useNewWSCLI:new J.default.Flag,useSafariWebdriverVisibilityChecks:new J.default.Flag,useClickimVisibilityChecks:new J.default.Flag,runGetElementCodeInAut:new J.default.Flag,enableFrameSwitchOptimization:new J.default.Flag,maximumJsResultSize:new J.default.Configuration(2e3*1024),skipFileInputClicks:new J.default.Flag,errorMessageOnBadNetwork:new J.default.Flag(!0),warnOnBadNetwork:new J.default.Flag(!1),overrideAzureStorageUrl:new J.default.Flag,useJsInputCodeInSafari:new J.default.Flag,useJsInputCodeInFirefox:new J.default.Flag,autoSaveDownloadFileFireFox:new J.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new J.default.Flag(!0),experimentalPreCodeCompilation:new J.default.Flag(!0),experimentalAsyncCustomCode:new J.default.Flag,useSameBrowserForMultiTests:new co("labs"),highSpeedMode:new co,usePortedHtml5DragDrop:new J.default.Flag,testNamesToBeforeSuiteHook:new J.default.Flag,addCustomCapabilities:new J.default.Variant("{}"),enableWorkerThreadsCliCodeExecution:new J.default.Flag(!0),LTNetworkCapabilities:new J.default.Flag,downloadToBase64:new J.default.Flag,dec2022eolBrowsers:new J.default.Flag,publicGridURL:new J.default.Configuration("public-grid.testim.io")},J.default.register("default",this.flags)}setProjectId(e){J.default.setCustomStringProperty("projectId",e)}setProjectType(e){J.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){J.default.setCustomStringProperty("productType",e)}setCompanyId(e){J.default.setCustomStringProperty("companyId",e)}setPlanType(e){J.default.setCustomStringProperty("planType",e)}setIsPOC(e){J.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){J.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){J.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!lx)return;let e={fetchIntervalInSec:dx,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return de(J.default.setup(Si,e),ux).catch(t=>Qm.error("failed to get feature flag status",t))}},lo=new ic});var po=C((ON,ac)=>{"use strict";var jr=require("os"),px=require("ms"),mx=require("fs-extra"),fx=require("p-retry"),hx=require("portfinder"),gx=require("child_process"),qr=(M(),w(q)),yx=(rt(),w(ht)),wx=pe(),{ArgError:Zm}=(K(),w(Z)),{getLogger:bx}=(U(),w(H)),{getExtensionsUrl:Tx}=(Xn(),w(Jn)),{gridTypes:ef,CLI_MODE:Ex}=(ee(),w(fe)),{featureFlagsService:vx}=(le(),w(me)),tf=bx("lambdatestService"),Sx="https://downloads.lambdatest.com/tunnel/v3",Ix={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"},uo=`${jr.tmpdir()}/LT`,xx=`${uo}/LT`,Rx=px("15m"),te=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===ef.LAMBDATEST||e.type===ef.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){te.isLambdatestGrid(e)&&(te.lambdatestConfigPromise=te.lambdatestConfigPromise||wx.fetchLambdatestConfig(),te.lambdatestConfig=await te.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Rx:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await mx.pathExists(xx))return;let t=Ix[jr.platform()+jr.arch()];if(!t)throw new Error(`tunnel on ${jr.platform()+jr.arch()} platform is not supported.`);let r=`${uo}.zip`;await qr.downloadAndSave(`${Sx}/${t}`,r),await qr.unzipFile(r,uo)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){te.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await hx.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;te.tunnelName=qr.guid();let a=["--tunnelName",te.tunnelName,"--infoAPIPort",t];if(e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)a=[...a,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new Zm("tunnel requires username and password");if(i)try{let u=new URL(i);a=[...a,"--proxy-host",u.hostname],u.port&&(a=[...a,"--proxy-port",u.port]),u.username&&u.password&&(a=[...a,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new Zm("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),te.tunnel=gx.spawn("./LT",a,{cwd:uo});let c="",l="";te.tunnel.stdout.on("data",u=>{c+=u.toString()}),te.tunnel.stderr.on("data",u=>{l+=u.toString()});try{let u=await fx(()=>yx.get(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});tf.info("LT tunnel info",u)}catch(u){throw tf.error("Failed to start LT tunnel",{err:u,stdoutResult:c,stderrResult:l}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!te.tunnel))return new Promise((t,r)=>{te.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),te.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=te.lambdatestConfig.CAPABILITIES[t]||{},a={};te.tunnelName&&(a.tunnel=!0,a.tunnelName=te.tunnelName);let c=[],{mode:l,canary:u,ext:p,extensionPath:f,installCustomExtension:m}=e;if(l===Ex.EXTENSION&&!p){let h=Tx({canary:u},!0);!f&&h[t]&&(c=[...c,h[t]]),f&&qr.isURL(f)&&(c=[...c,f])}return m&&qr.isURL(m)&&(c=[...c,m]),{build:r,name:`${n} - ${o}`,platform:te.lambdatestConfig.PLATFORM,selenium_version:te.lambdatestConfig.SELENIUM_VERSION,resolution:te.lambdatestConfig.RESOLUTION,timezone:te.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:vx.flags.LTNetworkCapabilities.isEnabled()}}};ac.exports=te;ac.exports.LambdatestService=te});var lc={};W(lc,{connect:()=>of,disconnect:()=>af,serveTunneling:()=>Px});var mo,sf,cc,rf,nf,Cx,of,af,Px,uc=F(()=>{"use strict";Hm();Mr();Xm();mo=S(require("ora")),sf=S(ot()),cc=S(po());U();ee();rf=G("tunnel"),nf=s=>{var e;return[Qt.LAMBDATEST,Qt.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Cx=s=>s.tunnelRoutes||s.gridData.type===Qt.HYBRID&&s.gridData.tunnel==="cloudflare",of=async s=>{if(!s.tunnel)return;let e=sf.default.getTokenV3UserData(),t;try{nf(s)?(t=(0,mo.default)("Starting testim lambdatest tunnel...").start(),await cc.default.connectTunnel(s)):Cx(s)?(t=(0,mo.default)("Starting testim cloudflare tunnel...").start(),await zm(s)):(t=(0,mo.default)("Starting testim ngrok tunnel...").start(),await Gm(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw rf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},af=async s=>{if(s.tunnel)try{nf(s)?await cc.default.disconnectTunnel(s):"tunnelRoutes"in s?await Jm(s):await Vm(s)}catch(e){let t="catch error - failed to close tunnel";throw rf.error(t,{err:e}),new Error(t)}},Px=async(s,e=new Promise(()=>{}))=>(await of(s),Fa(()=>af(s)),await e)});var js=C((DN,dc)=>{"use strict";var ho=require("lodash"),{GridError:go,ArgError:cf,GridConcurrencyError:kx}=(K(),w(Z)),{hasTestPlanFlag:Ax,promiseMap:_x}=(M(),w(q)),{gridMessages:fo,gridTypes:at}=(ee(),w(fe)),De=(U(),w(H)).getLogger("grid-service"),rs=pe(),$r={},lf=/(^(https?):\/{2})?(.*)/,uf=null;function Ox(s){return s.protocol?s.protocol:[at.TESTIM,at.BROWSERSTACK,at.SAUCELABS].includes(s.type)&&s.port===443?"https":[at.TESTIM_ENTERPRISE,at.LAMBDATEST,at.DEVICE_FARM].includes(s.type)?lf.exec(s.host)[2]||"https":""}function Lx(s){return lf.exec(s)[3]}function yo(s){var y,b,I;let e=s&&Lx(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&Ox(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(y=s==null?void 0:s.hybrid)==null?void 0:y.tunnel,c=(b=s==null?void 0:s.external)==null?void 0:b.user,l=(I=s==null?void 0:s.external)==null?void 0:I.key,u=s==null?void 0:s.type,p=u===at.HYBRID?a&&s.hybrid.external&&s.hybrid.external[s.hybrid.tunnel]&&s.hybrid.external[s.hybrid.tunnel].user:c,f=u===at.HYBRID?a&&s.hybrid.external&&s.hybrid.external[s.hybrid.tunnel]&&s.hybrid.external[s.hybrid.tunnel].key:l,m=s==null?void 0:s.name,h=s&&(s._id||s.gridId),g=s==null?void 0:s.provider;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:h,tunnel:a,user:c,key:l,type:u,name:m,provider:g,tunnelUser:p,tunnelKey:f}}async function df(s,e,t,r,n){let o;try{o=await n()}catch(c){throw De.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(fo.UNKNOWN)}De.info("get grid info",Object.assign({},o,{projectId:s,companyId:e}));let i=()=>o.status==="success",a=()=>o.status==="error"&&o.code;if(!o||!a()&&!i())throw De.error("invalid response - get grid",{res:o}),new Error(fo.UNKNOWN);if(i()){let c=yo(o.grid);return dc.exports.addItemToGridCache(t,e,c.gridId,c.slotId,r),c}throw a()&&o.code==="not-found"?new go(fo.NOT_FOUND):a()&&o.code==="no-available-slot"?new kx(`Failed to run test on ${r} - concurrency limit reached`):(De.error("invalid code error response - get grid",{res:o}),new go(fo.UNKNOWN))}function Nx(s,e,t,r,n){$r[s]={gridId:t,companyId:e,slotId:r,browser:n}}function Dx(s,e,t,r,n,o){return df(t,e,s,n,()=>rs.getGridById(e,t,r,n,o))}function Mx(s,e,t,r,n,o,i){return df(t,e,s,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(u=>(u.name||"").toLowerCase()===r.toLowerCase());return c!=null&&c._id?rs.getGridById(e,t,c._id,n,o):rs.getGridByName(e,t,r,n,o)})}function pf(s){return rs.getAllGrids(s)}async function mf(s,e,t){let n=(await Promise.resolve(t||pf(s))).find(o=>o._id===e);if(!n)throw new cf(`Failed to find grid id: ${e}`);return yo(n)}async function Fx(s,e,t){let n=(await Promise.resolve(t||pf(s))).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new cf(`Failed to find grid name: ${e}`);return yo(n)}async function ff(s,e){let t=$r[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete $r[s],!r){De.warn("failed to find grid slot id",{projectId:e});return}De.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await rs.releaseGridSlot(i,e,r,n,o)}catch(a){De.error("failed to release slot",{projectId:e,err:a})}}async function Ux(s){let e=Object.values($r).filter(Boolean);if(e.length!==0){De.info("keep alive worker slots",{projectId:s,slots:e});try{await rs.keepAliveGrid(s,e)}catch(t){De.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function qx(s){uf=setInterval(Ux,1e4,s)}async function jx(s){let e=Object.keys($r);if(!ho.isEmpty(e)){De.warn("not all slots released before end runner flow",{projectId:s});try{await _x(e,t=>ff(t,s))}catch(t){De.error("failed to release all slots",{err:t,projectId:s})}}}async function $x(s){await jx(s),clearInterval(uf)}function Bx(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Wx(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function hf(s){let t=(()=>ho.isEmpty(s.testobjectSauce)?ho.isEmpty(s.saucelabs)?ho.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=Bx(t,s),c=Wx(t,s);return Promise.resolve({host:r,port:n,path:o,protocol:i,type:t,user:c,key:a})}async function Gx(s,e){let t=s.company.companyId;return await mf(t,e.gridId,s.allGrids)}async function Vx(s){let{allGrids:e=void 0,company:t,host:r,useLocalChromeDriver:n,useChromeLauncher:o,gridId:i,grid:a}=s;if(n||o)return{mode:"local"};if(r)return hf(s);let c=t.companyId;if(i)return mf(c,i,e);if(a)return Fx(c,a,e);if(Ax(s)||s.tunnelOnlyMode){De.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new go("Missing host or grid configuration")}async function Hx(s,e,t,r){return await(async()=>{let{host:i,project:a,grid:c,gridId:l,useLocalChromeDriver:u,useChromeLauncher:p,company:f}=t,m=f==null?void 0:f.companyId;if(u||p)return{mode:"local"};if(i)return hf(t);if(l)return Dx(r,m,a,l,s,e);if(c)return Mx(r,m,a,c,s,e,t);throw new go("Missing host or grid configuration")})()}var Kx=async(s={},e={},t={},r={},n={})=>{let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,c=s.browser||t.browserValue,l=Boolean(s.tunnel),{maxRetries:u,currentRetry:p}=n;if(!i||!a||(a===at.LAMBDATEST&&await r.enableIfNeeded(e),a!==at.HYBRID||!o||!c||!u||!p))return e;let f=await rs.getHybridGridProvider({companyId:o,gridId:i,maxRetries:u,currentRetry:p,browser:c,usingTunnel:l});De.info("handling hybrid grid",{response:f,companyId:o});let m=yo({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&r.disable(),f.provider==="lambdatest"&&await r.enableIfNeeded(m),m};dc.exports={getGridSlot:Hx,releaseGridSlot:ff,getGridData:Vx,getTestPlanGridData:Gx,addItemToGridCache:Nx,keepAlive:{start:qx,end:$x},handleHybridOrVendorIfNeeded:Kx}});var pc=C((MN,gf)=>{"use strict";var wo;function zx(){return wo||"master"}function Jx(s="master",e="false"){if(s!=null&&s.branch&&s.branch==="master"){wo="master";return}if(s&&!s.isArchived){wo=s.branch||s;return}wo=e?"master":null}gf.exports={getCurrentBranch:zx,setCurrentBranch:Jx}});var Br=C((UN,bf)=>{"use strict";var yf=require("ws"),FN=require("lodash"),{WEBSOCKET_HOST:Xx}=(ne(),w(ce)),wf=(M(),w(q)),ns=(U(),w(H)).getLogger("socket-ng-service"),{EventEmitter:Yx}=require("events"),Qx=ot(),Zx=5e3,mc=class extends Yx{constructor(){super(),this.clientId=wf.guid(),this.ws=null,this.filterMap={},this.listeners={}}onReconnect(e){ns.info("test result websocket re-connect"),setTimeout(()=>this.connect(e),Zx)}formatUrl(e){return e.startsWith("http://")?e.replace("http://","ws://"):e.startsWith("https://")?e.replace("https://","wss://"):e}parseEvent(e){try{return JSON.parse(e)}catch(t){ns.error("failed to parse or trigger event",{err:t})}}connect(e){let t=this.formatUrl(Xx);return Qx.getCustomTokenV3().then(r=>new Promise(n=>{let o={};global.proxyUri&&(o.agent=new global.ProxyAgent(global.proxyUri)),this.ws=new yf(`${t}?projectId=${e}&clientId=${this.clientId}&token=${r}`,o),this.ws.on("open",()=>(ns.info("websocket opened"),this.reSendAllExistingFilters(),this.onConnect&&this.onConnect(),n())),this.ws.on("close",i=>{ns.info("websocket closed",{event:i}),(!this.ws||this.ws.readyState===yf.CLOSED)&&this.onReconnect(e,r,t)}),this.ws.on("error",i=>{ns.info("websocket error",{event:i})}),this.ws.on("message",i=>{let a=this.parseEvent(i);a!=null&&a.type&&this.emit(a.type,a.data)})}))}sendMessage(e){if(!this.ws){ns.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(e))}catch(t){ns.error("failed to stringify message for sending",{err:t})}}listenOnce(e,t,r){let n=o=>{t(o)&&(r(o),this.removeListener(e,n))};this.on(e,n)}listenTo(e,t,r,n){function o(a){r(a)&&n(a)}(Array.isArray(t)?t:[t]).forEach(a=>{this.listeners[`${e}:${a}`]=this.listeners[`${e}:${a}`]||[];let c=o.bind(this);this.listeners[`${e}:${a}`].push(c),this.on(a,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(e=>{let t=this.filterMap[e];this.sendMessage({type:"add-filter",filter:t})})}addFilter(e,t,r,n=!1){return new Promise(o=>{let i=wf.guid(),a={query:t,id:i,type:r,fullDocument:n};this.listenOnce("add-filter:done",c=>c.id===i,o),this.sendMessage({type:"add-filter",filter:a}),this.filterMap[e]=a})}removeListeners(e,t){Object.keys(this.listeners).length!==0&&t.forEach(r=>{let n=this.listeners[`${e}:${r}`];n&&(delete this.listeners[`${e}:${r}`],n.forEach(o=>this.removeListener(r,o)))})}removeFilter(e,t){let r=this.filterMap[e];if(!r)return;let n=Array.isArray(t)?t:[t];this.removeListeners(e,n),delete this.filterMap[e],this.sendMessage({type:"remove-filter",filter:r})}};bf.exports=new mc});var Tf={};W(Tf,{labFeaturesService:()=>gc});var eR,tR,fc,hc,gc,yc=F(()=>{"use strict";({featureFlagsService:eR}=(le(),w(me))),{getLabFeaturesByProjectId:tR}=pe(),fc=(U(),w(H)).getLogger("lab-features-service"),hc=class{constructor(){this.featuresForProject=[],this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(fc.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await tR(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){fc.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=eR.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:o}=this,i=n.find(c=>c.featureFlagName===e),a=i==null?void 0:i.enabled;return Boolean(o&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw fc.error(t,{featureFlagName:e.name}),new Error(t)}},gc=new hc});var Wr,wc,sR,bc,rR,Tc,bo,To,Eo,vo,So,Io=F(()=>{"use strict";M();ee();Wr=s=>{let{status:e,sessionType:t,success:r}=s;return e===xe.FAILED||t===Yt.CODEFUL&&r===!1},wc=s=>{let{status:e}=s;return e===xe.ABORTED},sR=s=>{let{status:e,sessionType:t,success:r}=s;return e===xe.PASSED||t===Yt.CODEFUL&&r===!0},bc=s=>s.runnerStatus===xe.SKIPPED,rR=s=>s.testStatus===Xt.EVALUATING,Tc=(s,e)=>e?!s.runConfig:!1,bo=(s,e)=>Object.values(s).filter(t=>bc(t)&&nt(t,e)).length,To=s=>Object.values(s).filter(e=>Wr(e)&&rR(e)).length,Eo=(s,e)=>Object.values(s).filter(t=>Wr(t)&&!Tc(t,e)),vo=(s,e)=>Object.values(s).filter(t=>sR(t)&&!Tc(t,e)),So=(s,e)=>Object.values(s).filter(t=>wc(t)&&!Tc(t,e))});var vf={};W(vf,{DebugReporter:()=>Ec});function nR(s){let e=s.indexOf("--token");if(e===-1&&(e=s.indexOf("--t")),e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var xo,Ef,Ec,Sf=F(()=>{"use strict";U();Io();xo=G("debug-reporter"),Ef={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},Ec=class{constructor(e){this.options=e}onTestStarted(e,t){xo.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;xo.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}onTestPlanStarted(e,t,r,n,o,i,a){let c=nR(process.argv);xo.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:Object.assign({},this.options,Ef),args:c})}onTestPlanFinished(e,t,r,n,o,i){let a=vo(e,i).length,c=Object.keys(e).length-a;xo.info("Test Plan Finished",{isAnonymous:o,passed:a,failed:c,testPlanName:t,options:Object.assign({},this.options,Ef),duration:r,executionId:n})}}});var Sc={};W(Sc,{featureAvailabilityService:()=>$s});var vc,$s,Gr=F(()=>{"use strict";ee();vc=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===Qt.DEVICE_FARM}},$s=new vc});var xc={};W(xc,{ConsoleReporter:()=>Ic});var Ot,Vr,os,If,xf,Ic,Rc=F(()=>{"use strict";Ot=S(require("chalk")),Vr=S(require("lodash"));M();ee();Gr();Io();os={success:Ot.default.green,warn:Ot.default.yellow,error:Ot.default.red},{CLI_MODE:If}=fe,xf="device",Ic=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,r,n){let o=n?"File":"Test",i=e.isTestsContainer?"":`(${e.testId})`,a=e.isTestsContainer?"":`url: ${Ot.default.underline(It(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,r,n){if(n)return;let o=e.success?xe.PASSED:xe.FAILED,i=e.isTestsContainer?" ":`(${e.testId})`,a=os[e.success?"success":"error"];console.log(a(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${o} ${i} duration: ${kn(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=It(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return r.isTestsContainer?r.name:`${r.name} : ${n}`});console.log(os.error("Failed runs are:")),console.log(os.error(t.join(`
27
- \r`)))}onTestPlanFinished(e,t,r,n,o,i){let a=Eo(e,i),c=vo(e,i),l=So(e,i),u=c.length,p=l.length,f=a.length,m="",h="";if($s.isTestStatusEnabled){let T=To(e);m=` FAILED-EVALUATING: ${T}`,f-=T,h=` SKIPPED: ${bo(e,this.options)}`}let g=this.buildTestPlanName(o,t,i),y,b=os[f?"error":"success"],I=`PASSED: ${u} FAILED: ${f}${m} ABORTED: ${p}${h} Duration: ${kn(r)}`;i||g.trim()===""||g.trim()==="Anonymous"?y=`Tests completed. ${I} (Execution ID: ${n})`:y=`Test plan${g} completed ${I} (${n})`,this.printWorkerDivider(),console.log(b(y)),this.printWorkerDivider(),this.printAllFailedTests(a)}buildTestPlanName(e,t,r){if(r)return"";let n=Vr.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,o=Vr.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Vr.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,a=Vr.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,r,n,o,i,a,c){let l=f=>{f.forEach((m,h)=>{var b;let g=(b=m.testData)!=null&&b.index?`- ${m.testData.index} / ${m.testData.total} Data set`:"",y=c?"":`(${m.testId})`;console.log(" ",h+1,":",`${m.name}${nt(m,this.options)?"-quarantine":""}`,y,g)})},u=a?`config '${a}'`:"default configs";if(c)console.log(`Run test plan, Project: ${this.options.project} (Execution ID: ${o}):`);else{let f=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${u}, Project: ${this.options.project}, Branch: ${this.branchToUse}${f}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`)}this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log(c?"File list:":"Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===If.APPIUM?xf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Ot.default.underline(n)} slot from ${Ot.default.underline(r)}`)}onGetSession(e,t,r){let n=r===If.APPIUM?xf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Ot.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e,t,r){let n=t?"file":"test";console.log(this.toWorkerIdPrefix(e),`Wait for ${n} complete`),r&&t&&console.log(this.toWorkerIdPrefix(e),`Chrome Debugger available at ${r}`)}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId;n?console.log(os.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a browser from the grid ${n}`)):this.options.useLocalChromeDriver?console.log(os.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally")):this.options.host&&console.log(os.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your Selenium grid at ${this.options.host}:${this.options.port||4444}`))}}});var kc={};W(kc,{JunitReporter:()=>Cc});function oR(s){let e=s.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function iR(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function aR(s){return`${s.visitedUrlsJson||""}`}async function cR(s,e,t,r,n,o){function i(f){let m=It(s,t,f.testId,f.resultId,r),h={$:{name:oR(f),classname:n,time:ta(f.duration),ownedBy:f.testOwnerName,ownerEmail:f.testOwnerEmail},"system-out":m};if(Wr(f)||wc(f)){let g=`Step Failed: ${f.failureReason||f.reason}`,y=Wr(f)?`${g} More info at: ${m}`:g;h.failure={$:{message:y}}}return bc(f)&&nt(f,o)&&$s.isTestStatusEnabled&&(h.skipped={}),o.urls&&(h["visited-urls-list"]=iR(f),h["visited-urls-json"]=aR(f)),h}function a(f){let{results:m,testPlanName:h,configName:g}=f,y=m||{},I={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failure:u(y),timestamp:c(e)};if($s.isTestStatusEnabled){I.skipped=bo(y,o);let T=To(y);I.failure-=T,I["failure-evaluating"]=T}return{$:I,testcase:Object.keys(y).map(T=>i(y[T]))}}function c(f){let m=Object.keys(f).map(g=>f[g].startTime),h=Math.min.apply(null,m);return h?new Date(h).toISOString():new Date().toISOString()}function l(f){return Object.keys(f).length}function u(f){return Eo(f).length+So(f).length}let p={testsuites:{testsuite:e.map(f=>a(f))}};try{return new Pc.Builder().buildObject(p)}catch(f){return lR(f)}}function lR(s){let e=new Pc.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var Pc,Rf,Cc,Ac=F(()=>{"use strict";Pc=S(require("xml2js"));M();Rf=require("fs");Gr();Io();Cc=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await cR(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Rf.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}}onAllTestPlansFinished(e){return this.createResultsReport(e)}}});var Cf={};W(Cf,{TeamCityReporter:()=>Oc});function Bs(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var _c,Oc,Pf=F(()=>{"use strict";U();_c=G("team-city-reporter");Oc=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return Bs(n)}onTestStarted(e,t,r,n,o){if(r){_c.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,r,n,o,i){if(o){_c.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${Bs(t)}' details='${Bs(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){_c.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${Bs(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${Bs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${Bs(t)}']`)}}});var kf={};W(kf,{JsonReporter:()=>Lc});var Lc,Af=F(()=>{"use strict";Lc=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}}});var _f={};W(_f,{ChromeReporter:()=>Nc});var Nc,Of=F(()=>{"use strict";M();Ba();Nc=class{constructor(e,t){this.options=e,this.branchToUse=t}onTestStarted(e,t,r,n){if(n)return;let o=It(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Qn(o)}}});var Dc={};W(Dc,{reporter:()=>se});function We(s){Ro.prototype[s]=async function(...e){for(let t of this.reporters)t!=null&&t[s]&&await t[s](...e)}}var uR,Ro,se,Et=F(()=>{"use strict";U();uR=G("reporter"),Ro=class{setOptions(e,t){this.reporters=[];let r=e.reporters,{DebugReporter:n}=(Sf(),w(vf));if(this.reporters.push(new n(e)),r===void 0||r.length===0){let{ConsoleReporter:o}=(Rc(),w(xc));if(this.reporters.push(new o(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{JunitReporter:i}=(Ac(),w(kc));this.reporters.push(new i(e,t))}}else{if(r.includes("teamcity")){let{TeamCityReporter:o}=(Pf(),w(Cf));this.reporters.push(new o(e))}if(r.includes("console")){let{ConsoleReporter:o}=(Rc(),w(xc));this.reporters.push(new o(e,t))}if(r.includes("junit")){let{JunitReporter:o}=(Ac(),w(kc));this.reporters.push(new o(e,t))}if(r.includes("json")){let{JsonReporter:o}=(Af(),w(kf));this.reporters.push(new o(e))}if(r.includes("chrome")){let{ChromeReporter:o}=(Of(),w(_f));this.reporters.push(new o(e,t))}}}async onTestPlanFinished(e,t,r,n,o,i,a){let c={};if(a){let l=Object.values(a);if(l.length>0){for(let u of Object.values(a))c[u.id]=u;for(let u of Object.keys(e))l.some(p=>p.parentResultId!==u)||(c[u]=e[u])}else uR.warn("childTestResults is not array"),c=e}else c=e;for(let l of this.reporters)if(l!=null&&l.onTestPlanFinished){let u=Date.now()-(r||0);await l.onTestPlanFinished(c,t,u,n,o,i)}}async onTestPlanStarted(e,t,r,n,o,i,a,c){for(let l of this.reporters)l!=null&&l.onTestPlanStarted&&await l.onTestPlanStarted(e,t,r,n,o,i,a,c)}async onGetSlot(e,t){for(let r of this.reporters)r!=null&&r.onGetSlot&&await r.onGetSlot(e,t)}async onGetSession(e,t,r){for(let n of this.reporters)n!=null&&n.onGetSession&&await n.onGetSession(e,t,r)}async onWaitToTestComplete(e,t,r){for(let n of this.reporters)n!=null&&n.onWaitToTestComplete&&await n.onWaitToTestComplete(e,t,r)}async onWaitToTestStart(e){for(let t of this.reporters)t!=null&&t.onWaitToTestStart&&await t.onWaitToTestStart(e)}async onAllTestPlansFinished(e){for(let t of e)if(t.childTestResults){t.results={};let r=Object.values(t.childTestResults);for(let n of r)t.results[n.id]=n;for(let n of Object.keys(e))r.some(o=>o.parentResultId!==n)||(t.results[n]=e[n])}for(let t of this.reporters)t!=null&&t.onAllTestPlansFinished&&await t.onAllTestPlansFinished(e)}};We("onGetBrowserFailure");We("onGetBrowserSuccess");We("onTestPlanStarted");We("onGetSlot");We("onGetSession");We("onTestFinished");We("onTestFailed");We("onTestPassed");We("onTestStarted");We("onTestIgnored");We("onWaitToTestStart");We("onWaitToTestComplete");se=new Ro});var Mc=C((XN,Mf)=>{"use strict";var Co=Os(),{isCi:Lf}=($n(),w(Pa)),Nf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Lf&&e?"ci-with-user":Lf?"ci":e?"cli-with-user":s;function Df(s,e){return e&&e.type&&(s[`${e.type}Mode`]=!0),s}function dR({executionId:s,projectId:e,testId:t,resultId:r,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:l,user:u,lightweightMode:p,isStartUp:f,projectType:m}){let h=Df({executionId:s,projectId:e,testId:t,resultId:r,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:Nf(l,u),isStartUp:f,projectType:m},p);Co.trackWithCIUser("test-run-ci",h)}function pR({executionId:s,projectId:e,testId:t,resultId:r,result:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,source:u,user:p,lightweightMode:f,logger:m,isStartUp:h,projectType:g}){try{let y=Df({executionId:s,projectId:e,testId:t,resultId:r,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Nf(u,p),isStartUp:h,projectType:g},f);if(n.success){Co.trackWithCIUser("test-run-ci-success",y);return}Co.trackWithCIUser("test-run-ci-fail",Object.assign({},y,{failureReason:n.failureReason}))}catch(y){m.error("failed to update test end analytics",{err:y})}}function mR({executionId:s,projectId:e,sessionType:t}){Co.trackWithCIUser("batch-run-ci",{executionId:s,projectId:e,sessionType:t})}Mf.exports={analyticsTestStart:dR,analyticsTestEnd:pR,analyticsExecsStart:mR}});var Uf=C((YN,Ff)=>{"use strict";var{ReportBase:fR}=require("istanbul-lib-report"),Fc=class extends fR{constructor(e){super(),e=e||{},this.appendToObject=e.appendToObject||{}}onStart(e){let t=e.getCoverageSummary();this.appendToObject=Object.assign(this.appendToObject,t.toJSON())}};Ff.exports=Fc});var Hf=C((Hr,Ws)=>{"use strict";var Uc=pe(),hR=require("fs"),gR=require("fs/promises"),is=require("path"),yR=require("mkdirp"),Po=(Je(),w(Tt)),qf=require("istanbul-lib-report"),wR=require("istanbul-reports"),bR=Uf(),TR=require("ora"),ER=require("moment"),vR=require("test-exclude"),{ArgError:$f}=(K(),w(Z)),{promiseMap:jf}=(M(),w(q)),qc=(U(),w(H)).getLogger("test-run-status"),Bf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},SR=s=>!!Bf(s).search,Wf=s=>s?Bf(s).pathname.substring(1):"",Gf=(s,e)=>{let t=Wf(e);return!new vR({relativePath:!1,include:s}).shouldInstrument(t)},IR=s=>s.substring(0,s.indexOf("?"));Ws.exports.getSourceMap=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Po("convert-source-map");if(t==="file"&&!e)throw new $f("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)};Ws.exports.remapCoverage=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await Promise.all(Object.values(t).map(async n=>{if(!n)return;let o=n.toObject();await Promise.all(o.sources.map(async(i,a)=>{if(Gf(r,i))return;let c=Vf(e,i);await yR(is.parse(c).dir),await gR.writeFile(c,o.sourcesContent[a])}))}))};var xR={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(SR(e)&&(e=IR(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=is.dirname(this.getPath(s));return is.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Vf=(s,e)=>`${is.resolve(s,Wf(e))}.js`;Ws.exports.saveCoverageReports=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=qf.createContext({dir:t,coverageMap:e,watermarks:qf.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Vf(r,a);return hR.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new bR({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:xR}),wR.create(a,c).execute(i)}),o};Ws.exports.convertV8ToIstanbul=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Po("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Gf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()};var RR=async(s,e,t)=>{let{mergeProcessCovs:n}=await Po("@bcoe/v8-coverage"),o={result:[]},i=new Map,c=(await Uc.getRealData(s,"testResult",`runId=${t}`)).data.docs;return await jf(c.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let u=await Uc.getS3Artifact(l,9e4);await jf(u,async p=>{if(!i.has(p.url)){let f=p.text;p.sourceUrl&&(i.set(p.url,"TEMP"),f=await Uc.getS3ArtifactText(p.sourceUrl)),i.set(p.url,{text:f,url:p.url,sourceMapType:p.sourceMapType,hash:p.hash})}delete p.text,o=n([o,{result:[p]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:o}};Ws.exports.calculateCoverage=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;qc.info("start js coverage process");let n=TR(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=is.resolve(s.codeCoverageReportPath||"./coverage"),i=is.resolve(o,`.js/${ER().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?is.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:u}]=await Promise.all([Po("istanbul-lib-coverage"),RR(s.project,e,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}qc.info("start js coverage merge and remap",{numOfFiles:u.size,numMergedCoverages:l.result.length});let p=c.createCoverageMap({}),f={};await Promise.all(l.result.map(async({url:h,functions:g})=>{let{text:y,sourceMapType:b}=u.get(h),I=await Hr.getSourceMap({sourceMapType:b,url:h,source:y,sourceMapDir:a});f[h]=I;let T=await Hr.convertV8ToIstanbul(s,{source:y,sourceMap:I,functions:g});p.merge(T)})),await Hr.remapCoverage(s,i,f);let m=await Hr.saveCoverageReports(s,p,o,i);return n.succeed(),m}catch(c){let l="Failed to report coverage information";c instanceof $f?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),qc.error(l,{err:c})}}});var Gs=C((QN,Jf)=>{"use strict";var jc=require("lodash"),{guid:CR,calcPercentile:Kf}=(M(),w(q)),zf={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},$c=class{constructor(){this.marks=jc.mapValues(zf,()=>[]),this.marks.ALL=[],this.startTimes={}}markStart(e){let t=CR();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){return{seleniumPerfMarks:this.marks,seleniumStats:jc.chain(this.marks).transform((e,t,r)=>{jc.isEmpty(t)||(e[`${r}_COUNT`]=t.length,e[`${r}_P50`]=Kf(t,50),e[`${r}_P95`]=Kf(t,95))},{}).value()}}};Jf.exports={SELENIUM_PERF_MARKS:zf,SeleniumPerfStats:$c}});var Wc=C((ZN,Zf)=>{"use strict";var{ArgError:Xf}=(K(),w(Z)),PR=require("express"),Yf=require("fs-extra"),kR=require("os"),Bc=require("path"),{lazyRequire:AR}=(Je(),w(Tt)),_R=Bc.join(kR.tmpdir(),"testim/rca/"),ko={},Kr={},Qf={"test-log":"consoleLogs","har-file":"networkLogs"},OR=Object.keys(Qf);function LR(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,ko[t.id]?{screenshot:ko[t.id]}:{})),Object.keys(Kr).forEach(t=>{s.assets=s.assets||{},s.assets[Qf[t]]=Kr[t]}),s.assets=s.assets||{},s.assets.screenshots=Object.values(ko)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath=s.failurePath||[],s.assets=s.assets||{},s.assets.screenshots=s.assets.screenshots||[]}}async function NR({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await AR("multer");t=typeof t=="string"?t:_R,await Yf.mkdirp(t);let n=r({storage:r.diskStorage({async destination(i,a,c){let l=JSON.parse(i.body.metadata||"{}");if(!l.testResultId)return c(new Error("missing testResultId"));let u=Bc.join(t,l.testResultId);try{await Yf.mkdirp(u)}catch(p){return c(p)}return c(null,u)},filename(i,a,c){let{fileName:l}=i.body,u=JSON.parse(i.body.metadata||"{}");if(!u.stepId&&!l)return c(new Error("missing stepId or fileName"));if(u.stepId){let p=Bc.extname(l);return c(null,`step_${u.stepId}_${u.stepName||""}${p}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return c(null,l)}})}),o=PR();return o.post("/",n.single("file"),(i,a)=>{let c=JSON.parse(i.body.metadata||"{}");c.stepId&&(ko[c.stepId]=i.file.path),c.testResultId&&OR.includes(c.subType)&&(Kr[c.subType]=Kr[c.subType]||[],Kr[c.subType].push(i.file.path)),a.sendStatus(200)}),o.use((i,a)=>a.status(404).send("Endpoint Not Found")),await new Promise((i,a)=>{let l=require("http").createServer(o);l.listen(s,e),l.on("error",u),l.on("listening",()=>i(l.address()));function u(p){if(p.syscall!=="listen")return a(p);switch(p.code){case"EACCES":case"EPERM":return a(new Xf(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return a(new Xf(`Port ${s} is already in use`));default:return a(p)}}})}Zf.exports={initServer:NR,mapFilesToLocalDrive:LR}});var eh={};W(eh,{OverrideTestDataBuilder:()=>Vc});var Lt,Gc,Vc,th=F(()=>{"use strict";Lt=S(require("lodash"));M();U();Gc=G("override-test-data-builder"),Vc=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return Lt.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)&&!Lt.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Gc.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(Lt.isObject(e.overrideAllTestsData)&&!Lt.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Gc.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Gc.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return Lt.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(u=>this.generateTestUniqId(u)),i=o.indexOf(n),a=o.lastIndexOf(n),c=r[i],l=this.createNewTestItems(c,t);return r.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=Oe();return Object.assign({},e,{resultId:o,testData:{value:r,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});var nh=C((tD,Hc)=>{"use strict";var zr=require("lodash"),He=(M(),w(q)),Ge=(ee(),w(fe)),DR=js(),vt=pe(),{ArgError:rh}=(K(),w(Z)),{getLogger:MR}=(U(),w(H)),{reporter:Vs}=(Et(),w(Dc)),{registerExitHook:FR}=(Mr(),w(Kn)),{calculateCoverage:UR}=Hf(),{SeleniumPerfStats:qR}=Gs(),{mapFilesToLocalDrive:jR}=Wc(),{TESTIM_CONCURRENT_WORKER_COUNT:$R}=(ne(),w(ce)),{featureFlagsService:sh}=(le(),w(me)),{OverrideTestDataBuilder:BR}=(th(),w(eh)),{featureAvailabilityService:WR}=(Gr(),w(Sc)),Ve=MR("test-run-status"),GR=He.getEnvironmentGitBranch(),VR=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,HR=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,KR=He.getRunnerVersion();async function Ao(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ve.warn("failed to run hook",{err:t}),new rh(`failed to run hook promise ${t.message}`)}}var _o=class{constructor(e,t,r,n){this.options=t,this.options.runParams=this.options.runParams||{},this.startTime=null,this.fileUserParamsData=this.options.userParamsData,this.beforeSuiteParams={},this.branchToUse=n,this.exportsGlobal={},this.testInfoList=e,this.executionStartedPromise=Promise.resolve();let o=He.getUniqBrowsers(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:$R||t.parallel||1,browser:o,gitBranch:GR,gitCommit:VR,gitRepoUrl:HR,runnerVersion:KR,gridHost:t.host||t.gridData.host,testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(a=>a.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||t.gridData.gridId,gridName:t.grid||t.gridData.name,gridType:t.gridData.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:He.getSessionType(t)},this.seleniumPerfStats=new qR,this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,isTestsContainer:l,testId:u,name:p,testStatus:f,testCreatorName:m,testCreatorEmail:h,testOwnerName:g,testOwnerEmail:y,testLabels:b,testSuites:I,allLabels:T}=a,v={originalTestResultId:t,previousTestResultId:r,config:zr.cloneDeep(c),testId:u,status:"QUEUED",name:p,resultId:e,isTestsContainer:l,retryCount:i,testStatus:f};return this.testRunStatus[e]=Object.assign({},v,{testCreatorName:m,testCreatorEmail:h,testOwnerName:g,testOwnerEmail:y,testLabels:b,testSuites:I,allLabels:T}),vt.addTestRetry({projectId:n,runId:o,testId:u,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:v})}getAllTestResults(){return this.testRunStatus}testStart(e,t,r,n){let o=this.getTestResult(r);o.workerId=e;let i=this.options.files.length>0;return Vs.onTestStarted(o,e,n,i,r),o}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await vt.updateTestDataArtifact(n,e.testId,e.resultId,e.config.testData,i.defaults)}catch(u){Ve.error("failed to upload test data artifact (runner)",{err:u})}let c=zr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,vt.updateTestStatus(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(He.isQuarantineAndNotRemoteRun(e,this.options))return;let n=this.exportsGlobal;try{let o=await Ao(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ve.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ve.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Ge.testStatus.EVALUATING&&WR.isTestStatusEnabled){Vs.onTestIgnored(e,r,`test in ${Ge.testStatus.EVALUATING} status`);return}if(l){Vs.onTestPassed(o);return}Vs.onTestFailed(r,r.failureReason,He.getTestUrl(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?Ge.runnerTestStatus.PASSED:Ge.runnerTestStatus.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Vs.onTestIgnored(e,r,`test in ${Ge.testStatus.QUARANTINE}`)}testEnd(e,t,r,n,o){let i=this.testRunStatus[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&&jR(i,Ve),i.resultUrl=He.getTestUrl(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;Vs.onTestFinished(i,e,o,c);let l=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await Ao(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ve.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 vt.updateTestStatus(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Ve.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}calcTestRunStatus(){let{options:e,testInfoList:t}=this,r=e.company.companyId;this.testRunStatus=t.reduce((n,o)=>{var a,c,l,u;n[o.resultId]={testId:o.testId,status:He.isQuarantineAndNotRemoteRun(o,e)?Ge.runnerTestStatus.SKIPPED:Ge.runnerTestStatus.QUEUED,name:o.name,resultId:o.resultId,isTestsContainer:o.isTestsContainer,testStatus:o.testStatus||Ge.testStatus.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels};let i=e.browser?He.getRunConfigByBrowserName(e.browser,e.saucelabs,e.browserstack):o.runConfig;if(i&&sh.flags.dec2022eolBrowsers.isEnabled()&&((a=He.getBrowserInfo(i.browserValue))!=null&&a.eol))throw new rh(`Unsupported Browser: ${i.browserName}`);return n[o.resultId].config=Object.assign({},this.execConfig,{companyId:r,testData:(c=o.testData)!=null&&c.value?o.testData.value:null}),n[o.resultId].config.isBeforeTestPlan=o.isBeforeTestPlan,n[o.resultId].config.isAfterTestPlan=o.isAfterTestPlan,n[o.resultId].config.testDataTotal=((l=o.testData)==null?void 0:l.total)||null,n[o.resultId].config.testDataIndex=((u=o.testData)==null?void 0:u.index)||null,n[o.resultId].config.baseUrl=e.baseUrl||o.baseUrl||o.testConfig.baseUrl,n[o.resultId].config.testConfig=o.overrideTestConfig||o.testConfig,n[o.resultId].config.browser=i.browserValue.toLowerCase(),n},{})}async executionStart(e,t,r,n,o){Ve.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;FR(()=>Promise.all([DR.keepAlive.end(t),vt.reportExecutionFinished("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...sh.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await Ao(i.beforeSuite,l),p=new BR(u,zr.cloneDeep(this.testInfoList),t);this.testInfoList=p.overrideTestData(),this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:f}=this,m=[],h=[],g=[];for(let b of f){if(b.isBeforeTestPlan){m.push(b);continue}if(b.isAfterTestPlan){g.push(b);continue}h.push(b)}let y=async()=>{let b=zr.cloneDeep(this.testRunStatus);await He.promiseMap(Object.keys(b),async x=>{var k;let A=b[x],N=(k=A.config)==null?void 0:k.testData,B=A.testId,$=await vt.updateTestDataArtifact(t,B,x,N,c.defaults);$&&(delete A.config.testData,A.config.testDataUrl=$)});let I=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),T={executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:I,intersections:i.intersections},v=vt.reportExecutionStarted(T);return this.executionStartedPromise=v,v.catch(x=>Ve.error(x)),v};try{await y()}catch(b){Ve.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:m,tests:h,afterTests:g}}concatSeleniumPerfMarks(e){zr.chain(e).keys().each(t=>{this.seleniumPerfStats.marks[t]&&(this.seleniumPerfStats.marks[t]=[...this.seleniumPerfStats.marks[t],...e[t]])}).value()}async executionEnd(e){var u;let t=He.groupTestsByRetries(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:p,testStatus:f}of t)p===Ge.runnerTestStatus.PASSED&&n++,p===Ge.runnerTestStatus.SKIPPED&&o++,p===Ge.runnerTestStatus.FAILED&&f===Ge.testStatus.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await Ao(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(p){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ve.warn("error while running afterSuite Hook",{err:p,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await UR(this.options,this.branchToUse,r,e);if(c.coverageSummary=l,!((u=this.options.lightweightMode)!=null&&u.onlyTestIdsNoSuite))try{return await vt.reportExecutionFinished("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(p){throw Ve.error("Failed to update suite finished",{err:p}),p}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await vt.updateExecutionTests(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}};Hc.exports=_o;Hc.exports.TestRunStatus=_o});var Do=C((sD,ph)=>{"use strict";var zR=require("fs"),ah=require("path"),as=require("lodash"),JR=require("crypto"),ch=(M(),w(q)),XR=(ne(),w(ce)),YR=po(),{getLogger:QR}=(U(),w(H)),{featureFlagsService:Oo}=(le(),w(me)),{CLI_MODE:Lo,mobileWeb:ZR,gridTypes:zc}=(ee(),w(fe)),Jr=QR("testim-desired-capabilities-builder"),oh=XR.WEBDRIVER_DEBUG?"verbose":"silent",Kc={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},lh=["--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"],Jc=(...s)=>JR.createHash("sha256").update(s.join("")).digest("hex"),No=s=>s.type===zc.DEVICE_FARM||s.type===zc.HYBRID&&s.provider==="devicefarm",eC=s=>{s.hasOwnProperty("version")&&(s.browserVersion=s.version,delete s.version),s.hasOwnProperty("platform")&&(s.platformName=s.platform,delete s.platform),s.hasOwnProperty("acceptSslCerts")&&(s.acceptInsecurecerts=s.acceptSslCerts,delete s.acceptSslCerts),s.hasOwnProperty("unexpectedAlertBehaviour")&&(s.unhandledPromptBehavior=s.unexpectedAlertBehaviour,delete s.unexpectedAlertBehaviour)};function tC(s,e){let t={browserName:"safari"};return e==="safari technology preview"&&(t["safari.options"]={technologyPreview:!0}),Object.assign(s.desiredCapabilities,t),s}function Xc(s){return zR.readFileSync(s,{encoding:"base64"})}function uh(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&ch.isURL(s))&&s){let r=Xc(s);Jr.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Jc(r)} current extension count: ${e.length}`),e.push(r)}}function dh(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,l=r||c,u=`--load-extension=${l}`;Jr.info(`adding extension: testim unpacked , path: ${l}`),t.push(u);return}let o=s.canary?"-master.zip":".zip",i=ah.join(process.cwd(),`testim-headless${o}`),a=Xc(i);Jr.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Jc(a)} current extension count: ${e.length}`),e.push(a)}function sC(s,e,t,r,n,o,i){var g,y;let a=t.seleniumName||t.browserValue,c=[],l=[...lh];e.headless&&l.push("--headless");let u=()=>e.mode!==Lo.EXTENSION,p={prefs:{"profile.default_content_setting_values.popups":Kc.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Kc.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:u()};No(n)&&(p.prefs["download.default_directory"]="C:\\Users\\testnode",p.w3c=!0,s.desiredCapabilities.version="latest-1",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),No(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(p.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(b=>l.push(`--${b}`)),e.chromeBlockLocation&&(p.prefs["profile.default_content_setting_values.geolocation"]=Kc.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function f(){t.mobileEmulation&&(p.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+ZR.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}f(),uh(r,c,i),e.mode===Lo.EXTENSION&&dh(e,c,l,o,i),c.length>0&&(p.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(p.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),p.args=l;let m={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],h={MicrosoftEdge:"ms",chrome:"goog"}[a];return YR.isLambdatestGrid(n)&&delete p.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[m]=p),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${m}`]=p),s}var rC=as.memoize(sC,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(as.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return Jc(i,a,c,r,l,o)}),ih=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];function nC(s,e,t){let r={"pdfjs.disabled":!0};if(Oo.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":ih.join(","),"browser.helperApps.neverAsk.openFile":ih.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Lo.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=ah.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=Xc(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function oC(s,e,t){let{saucelabs:r}=s;return r!=null&&r.username&&r.accessKey?t?(t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion,Object.assign({},t.sl,r,{name:e})):Object.assign({},r,{name:e}):{}}function iC(s,e,t){return as.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,s.browserstack,{name:e})):Object.assign({},s.browserstack,{name:e})}function aC(s){return s.perfecto?s.perfecto:{}}function cC(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function lC(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=ch.buildBasicHeader(o,i)),a}function uC(s,e,t,r,n,o,i,a=null){var g,y;if(r.mode==="local"){let b=[],I=[...lh],T={};return s.headless&&I.push("--headless"),s.silentDebuggerExtensionApi&&I.push("--silent-debugger-extension-api"),s.remoteDebuggingPort!==void 0&&I.push(`--remote-debugging-port=${s.remoteDebuggingPort}`),s.chromeExtraArgs&&s.chromeExtraArgs.forEach(v=>I.push(`--${v}`)),s.chromeBinaryLocation&&(T.binary=s.chromeBinaryLocation),s.mode!=="selenium"&&dh(s,b,I,null,a),uh(n,b,a),{logLevel:oh,desiredCapabilities:{chromeOptions:{args:I,extensions:b,...T},browserName:"chrome"},host:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=s,u={host:r.host,port:r.port||4444,path:r.path||"/wd/hub",protocol:r.protocol||"http",logLevel:oh,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,s.getSessionTimeout),getSessionRetries:a.getSessionRetries||s.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{javascriptEnabled:!0,locationContextEnabled:!0,handlesAlerts:!0,rotatable:!0,acceptSslCerts:!0,unexpectedAlertBehaviour:"accept",nativeEvents:!0,testName:e}},p=lC(s,r);as.isEmpty(p)||(u.headers=p),No(r)&&(s.oldCapabilities=!1,s.w3cCapabilities=!0,u.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),s.proxyForGrid&&(u.agent=new global.ProxyAgent(global.proxyUri)),s.disableNativeEvents&&(u.desiredCapabilities.nativeEvents=!1),r.user&&r.key&&(r.type==="saucelabs"&&(s.saucelabs=s.saucelabs||{},s.saucelabs.username=s.saucelabs.username||r.user,s.saucelabs.accessKey=s.saucelabs.accessKey||r.key),r.type==="browserstack"&&(s.browserstack=s.browserstack||{},s.browserstack["browserstack.user"]=s.browserstack["browserstack.user"]||r.user,s.browserstack["browserstack.key"]=s.browserstack["browserstack.key"]||r.key)),r.key&&r.type==="perfecto"&&(s.perfecto.securityToken=r.key);let f=Number(s.browserTimeout/1e3),m=s.browser||(t==null?void 0:t.browserValue);as.merge(u.desiredCapabilities,oC(s,e,t),iC(s,e,t),aC(s,e,t),cC(s,m,f),a==null?void 0:a.getCapabilities(s,m,o,i,e));let h=null;switch(!s.ext&&!s.extensionPath&&((g=r.host)!=null&&g.endsWith(".testim.io"))&&!s.canary&&s.mode===Lo.EXTENSION&&(m==="chrome"?h="/opt/testim-headless":m==="edge-chromium"&&(h="C:/selenium/testim-headless")),(y=r.host)!=null&&y.endsWith(".testim.io")&&m==="edge-chromium"&&(u.desiredCapabilities.version="83"),m){case"chrome":case"edge-chromium":u=rC(u,s,t,n,r,h,a);break;case"firefox":u=nC(u,s,a);break;case"safari":case"safari technology preview":u=tC(u,m);break;default:break}as.merge(u.desiredCapabilities,s.seleniumCapsFileContent);try{let b={"hub.lambdatest.com":"lambdatest",[Oo.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},I=A=>A[r.provider]||A[u.host]||A[b[u.host]],T=A=>{var N,B;return I(A)||A[(N=u.desiredCapabilities)==null?void 0:N.browserName]||A[(B=u.desiredCapabilities)==null?void 0:B.version]||A||{}},v=JSON.parse(Oo.flags.addCustomCapabilities.getValue()||"{}"),x=T(T(v));Object.keys(x).length&&(Jr.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(u.desiredCapabilities,x))}catch(b){Jr.error("Failed to load custom capabilities",{error:b,customCapabilities:Oo.flags.addCustomCapabilities.getValue()})}return No(r)&&u.desiredCapabilities&&!u.capabilities&&(eC(u.desiredCapabilities),u.capabilities={alwaysMatch:u.desiredCapabilities,firstMatch:[{}]},delete u.desiredCapabilities),u}function dC({projectType:s,gridInfo:e,testRunConfig:t,nativeApp:r,options:n,appPath:o,androidActivityWait:i}){let{deviceModel:a,osVersion:c,deviceUdid:l}=n,u={};if(!r&&!o)throw Error("missing mobile app!");if(e.type!==zc.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid");let p={protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`,logLevel:n.appiumLogLevel},f={"headspin:capture":!0,"appium:autoAcceptAlerts":!0,"appium:noReset":!0};switch(s){case"ios":f={...f,platformName:"iOS","appium:automationName":"XCUITest",...r&&{"appium:bundleId":r.id},...o&&{"appium:app":o}};break;case"android":f={...f,platformName:"Android","appium:automationName":"UiAutomator2","appium:appWaitActivity":i,...r&&{"appium:appPackage":r.id||r.packageName,"appium:appActivity":r.activity},...o&&{"appium:app":o}};break;default:throw Error(`unsupported mobile project ${s}`)}return a&&(u.model=a),c&&(u.os_version=c),l&&(u.device_id=l,delete u.model,delete u.os_version),as.isEmpty(u)||(f["headspin:selector"]=u),{...p,desiredCapabilities:f,capabilities:f}}ph.exports={buildSeleniumOptions:uC,buildAppiumOptions:dC}});var fh=C((rD,mh)=>{"use strict";mh.exports=function s(e){function t(m){if(!m)return!1;switch(m.nodeType){case Node.ELEMENT_NODE:case Node.DOCUMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:return!0;default:return!1}}function r(m){return m?n(m.parentNode,t):null}function n(m,h){for(let g=m;g&&g!==m.ownerDocument;g=g.parentNode)if(h(g))return g;return null}function o(m,h){for(let g=m;g&&g!==m.ownerDocument;g=r(g))if(h(g))return g;return null}function i(m,h){if(!m||!h)return null;m instanceof DocumentFragment&&(m=m.host);let y=window.getComputedStyle(m).getPropertyValue(h);if(y&&y!=="inherit")return y;let b=r(m);return i(b,h)}function a(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 y=i(m,"stroke-width");return!!y&&parseInt(y,10)>0}return i(m,"overflow")==="hidden"?!1:Array.from(m.childNodes).some(y=>y.nodeType===Node.TEXT_NODE?!0:t(y)?a(y):!1)}function c(m){return i(m,"overflow")==="hidden"}function l(m){return!m||!c(m)||!m.childNodes.length?!1:Array.from(m.childNodes).every(h=>h.nodeType===Node.TEXT_NODE?!1:!t(h)||!a(h)?!0:l(h))}function u(m){return m?m.parentNode&&m.parentNode.host?!0:u(m.parentNode):!1}if(!u(e)&&!document.contains(e))return!1;switch(e.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let m=n(e,h=>h.tagName.toUpperCase()==="SELECT");return s(m)}case"INPUT":if(e.type==="hidden")return!1;break;default:break}if(i(e,"visibility")!=="visible")return!1;let p=!!o(e,m=>Number(i(m,"opacity"))===0),f=!!o(e,m=>i(m,"display")==="none");return!(p||f||!a(e)||l(e))}});var Yc=C((nD,hh)=>{"use strict";function pC(s){return s.message&&s.message.match(/Command not found/)||s.message==="HTTP method not allowed"||s.message==="Unknown error"||s.message&&s.message.match(/Unknown timeout type/)||s.seleniumStack&&s.seleniumStack.type==="UnknownCommand"||s.message&&s.message.match(/did not match a known command/)||s.message&&s.message.match(/Server returned HTTP response code: 405 for URL/)||s.seleniumStack&&s.seleniumStack.message==="The arguments passed to a command are either invalid or malformed."||s.message.match(/Invalid timeout type specified: ms/)}function mC(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}hh.exports={isOldProtocol:pC,encodeForSafari:mC}});var Th=C((oD,bh)=>{"use strict";var fC=require("@testim/webdriverio"),wh=require("promise-queue"),gh=(ne(),w(ce)),{UNICODE_CHARACTERS:yh,W3C_ELEMENT_ID:hC}=(Es(),w(Rn)),gC=fh(),Mo=(U(),w(H)).getLogger("WebDriverApi"),{isOldProtocol:cs,encodeForSafari:yC}=Yc(),{extractElementId:Fo}=(M(),w(q)),{SELENIUM_PERF_MARKS:Uo}=Gs();wh.configure(Promise);var Qc=Ie(),wC=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},Zc=class{constructor(){this.w3cRequests={}}windowHandleMaximize(){return this.addToQueue(()=>this.client.windowHandleMaximize().then(e=>({height:e.value.height,width:e.value.width})))}rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";return Mo.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),Promise.reject(e)}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof gh.REQUESTS_QUEUE_SIZE<"u"&&(e=gh.REQUESTS_QUEUE_SIZE);let t=1/0;this.queue=new wh(e,t)}addToQueue(e){let t=this.seleniumPerfStats.markStart();return this.queue.add(e).catch(r=>this.rejectWithLog(r,e)).finally(()=>this.seleniumPerfStats.markEnd(t))}async initClient(e,t,r){this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.client=fC.remote(e),this.initQueueRequests(),Qc.log("right before addToQueue");let n=this.seleniumPerfStats.markStart(Uo.GET_BROWSER);try{await this.addToQueue(()=>(Mo.info("requesting browser",{testResultId:r,testName:t}),Qc.log("before this.client.init"),this.client.init())),Qc.log("after client init")}finally{await this.seleniumPerfStats.markEnd(n,Uo.GET_BROWSER)}}get isMobile(){return this.client.isMobile}getSessionId(){var e,t;return(t=(e=this.client)==null?void 0:e.requestHandler)==null?void 0:t.sessionID}isChrome(){return this.client.desiredCapabilities.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.client.desiredCapabilities.browserName==="firefox"}isSafari(){return this.client.desiredCapabilities.browserName==="safari"||this.client.desiredCapabilities.browserName==="safari technology preview"}isAndroid(){return this.client.desiredCapabilities.platformName==="Android"}isEdgeChromium(){return this.client.desiredCapabilities.browserName==="MicrosoftEdge"&&!this.client.desiredCapabilities._isOldEdge}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 r=i=>{throw i.executedScript=t,i},n=()=>this.client.requestHandler.create("/session/:sessionId/execute/sync",{script:t,args:e}).catch(r),o=()=>this.client.requestHandler.create("/session/:sessionId/execute",{script:t,args:e}).catch(r);return this.w3cRequests.execute?n():o().catch(i=>{if(cs(i))return this.w3cRequests.execute=!0,n();throw i})})}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 r=()=>this.client.requestHandler.create("/session/:sessionId/execute/async",{script:t,args:e}),n=()=>this.client.requestHandler.create("/session/:sessionId/execute_async",{script:t,args:e});return this.w3cRequests.executeAsync?r():n().catch(o=>{if(cs(o))return this.w3cRequests.executeAsync=!0,r();throw o})})}async executeCDP(e,t={}){if(!this.isChromium())return;let r=await this.client.requestHandler.create({path:"/session/:sessionId/chromium/send_command_and_get_result",method:"POST"},{cmd:e,params:t});return!r||!r.value||!r.value.targetInfos?[]:r.value.targetInfos}takeScreenshot(){let e=this.seleniumPerfStats.markStart(Uo.GET_SCREENSHOT);return this.addToQueue(()=>this.client.screenshot()).finally(()=>this.seleniumPerfStats.markEnd(e,Uo.GET_SCREENSHOT))}getElementBySelector(e){return this.addToQueue(()=>this.client.element(e))}elementIdDisplayed(e){return this.addToQueue(()=>{let t=()=>this.client.elementIdDisplayed(e),r=()=>this.execute(gC,{ELEMENT:e,[hC]:e});return this.w3cRequests.elementIdDisplayed?r():t().catch(n=>{if(cs(n))return this.w3cRequests.elementIdDisplayed=!0,r();throw n})})}windowHandles(){return this.addToQueue(()=>{let e=()=>this.client.requestHandler.create("/session/:sessionId/window_handles"),t=()=>this.client.requestHandler.create("/session/:sessionId/window/handles");return this.w3cRequests.windowHandles?t():e().catch(r=>{if(cs(r))return this.w3cRequests.windowHandles=!0,t();throw r})})}url(e){return this.addToQueue(()=>this.client.url(yC(e,this.isSafari(),Mo)))}reloadTab(){return this.addToQueue(()=>this.client.refresh())}source(){return this.addToQueue(()=>this.client.source())}timeouts(e,t){return this.addToQueue(()=>{let r=()=>this.client.requestHandler.create("/session/:sessionId/timeouts",{type:e,ms:t}),n=()=>this.client.requestHandler.create("/session/:sessionId/timeouts",{[e]:t});return this.w3cRequests.timeouts?n():r().catch(o=>{if(cs(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 r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}setValue(e,t){return this.elementIdClear(Fo(e)).then(()=>this.elementIdValue(Fo(e),t))}getViewportSize(e){return this.execute(wC).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=>yh.hasOwnProperty(i)?[yh[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(e instanceof Array)for(let i of e)r=r.concat(t(i));else return Promise.reject(new Error("number or type of arguments don't agree with keys protocol command"));let n=()=>this.client.requestHandler.create("/session/:sessionId/keys",{value:r}),o=()=>{let i=r.map(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};return this.w3cRequests.keys?o():this.addToQueue(()=>n().catch(i=>{if(cs(i))return this.w3cRequests.keys=!0,o();throw i}))}elementIdValue(e,t){return this.addToQueue(()=>this.client.elementIdValue(e,t))}elementIdClear(e){return this.addToQueue(()=>this.client.elementIdClear(e))}submitForm(e){return this.addToQueue(()=>this.client.submit(Fo(e)))}buttonPress(e){return this.addToQueue(()=>this.client.buttonPress(e))}findElementAndPress(e,t,r,n){return this.moveTo(Fo(e),t,r).then(()=>this.buttonPress(n))}rightClick(e,t,r){return this.findElementAndPress(e,t,r,"right")}leftClick(e,t,r){return this.findElementAndPress(e,t,r,"left")}elementIdClick(e){return this.addToQueue(()=>this.client.elementIdClick(e))}actions(e){return this.addToQueue(()=>this.client.actions(e))}doDoubleClick(){return this.addToQueue(()=>this.client.doDoubleClick())}dragAndDrop(e,t){return this.addToQueue(()=>this.client.dragAndDrop(e,t))}buttonDown(){return this.addToQueue(()=>this.client.buttonDown())}buttonUp(){return this.addToQueue(()=>this.client.buttonUp())}moveTo(e,t,r){let n={};return typeof t=="number"&&(n.xoffset=t),typeof r=="number"&&(n.yoffset=r),this.isSafari()&&!n.hasOwnProperty("yoffset")&&(n.yoffset=1),this.isSafari()&&!n.hasOwnProperty("xoffset")&&(n.xoffset=1),typeof e=="string"&&(n.element=e),this.addToQueue(()=>this.client.requestHandler.create("/session/:sessionId/moveto",n))}uploadFile(e){return this.addToQueue(()=>this.client.uploadFile(e))}getUrl(){return this.addToQueue(()=>this.client.getUrl())}getTitle(){return this.addToQueue(()=>this.client.getTitle())}windowHandleSize(e="current",t){return this.addToQueue(()=>{let r={};typeof e=="object"&&([e,t]=["current",e]);let n={path:`/session/:sessionId/window/${e}/size`,method:"GET"};if(typeof t=="object"&&t.width&&t.height&&(n.method="POST",r={width:Math.abs(t.width),height:Math.abs(t.height)}),n.method==="POST"&&typeof r.width!="number"&&typeof r.height!="number")return Promise.reject(new Error("number or type of arguments don't agree with windowHandleSize protocol command"));let o=()=>this.client.requestHandler.create(n,r),i=()=>(n.path="/session/:sessionId/window/rect",this.client.requestHandler.create(n,r));return this.w3cRequests.windowHandleSize?i():o().catch(a=>{if(cs(a))return this.w3cRequests.windowHandleSize=!0,i();throw a})})}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>this.client.setCookie({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)}))}getCookie(e){return this.addToQueue(()=>this.client.requestHandler.create("/session/:sessionId/cookie").then(t=>(t.value=t.value||[],typeof e=="string"?t.value.find(r=>r.name===e||r.name===encodeURIComponent(encodeURIComponent(e)))||null:t.value||(typeof e=="string"?null:[]))))}deleteCookie(e){return this.addToQueue(()=>this.client.deleteCookie(e))}isVisibleWithinViewport(e){return this.addToQueue(()=>this.client.isVisibleWithinViewport(e))}getCurrentTabId(){return this.addToQueue(()=>this.client.getCurrentTabId())}frame(e){return this.addToQueue(()=>this.client.frame(e))}switchTab(e){return this.addToQueue(()=>this.client.switchTab(e))}alertAccept(){return this.addToQueue(()=>this.client.alertAccept())}log(e="browser"){return this.addToQueue(()=>this.client.log(e))}end(){return this.w3cRequests={},this.queue?this.addToQueue(()=>this.client.end()):Promise.resolve()}forceEnd(){return this.w3cRequests={},this.client?this.client.end():Promise.resolve()}touchPerform(e){return this.addToQueue(()=>this.client.touchPerform(e))}touchAction(e){return this.addToQueue(()=>this.client.touchAction(e))}pressKeycode(e){return this.addToQueue(()=>this.client.pressKeycode(e))}setImmediateValue(e,t){return this.addToQueue(()=>this.client.setImmediateValue(e,t))}elementIdText(e){return this.addToQueue(()=>this.client.elementIdText(e)).then(t=>t.value)}isAppInstalled(e){return this.addToQueue(()=>this.client.isAppInstalled(e)).then(t=>{let r=!!t.value;return Mo.info(`is app (${e}) installed? ${r}`,t),r})}launch(){return this.addToQueue(()=>this.client.launch())}context(e){return this.addToQueue(()=>this.client.context(e))}elementIdLocation(e){return this.addToQueue(()=>this.client.elementIdLocation(e))}};bh.exports=Zc});var vh=C((iD,Eh)=>{"use strict";var bC=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(f){function m(I,T,v){return v>I&&v<T}let h=f.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&m(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,b=h.originY&&m(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:b}},a=function(f,m){return{screenX:0,screenY:0,clientX:f,clientY:m,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(f,m,h){if(!window.PointerEvent)return;let g=a(m,h);return new window.PointerEvent(f,g)},l=function(f,m,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(f,!0,!0,document.defaultView,1,0,0,m,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},u=function(){var m;let f=document.activeElement;for(;(m=f.shadowRoot)!=null&&m.activeElement;)f=f.shadowRoot.activeElement;return f},p=function(f){let m=i(f),h=f.event;return t.includes(h)?c(h,m.x,m.y):l(h,m.x,m.y)};try{n.map(m=>p(m)).filter(Boolean).forEach(m=>r.dispatchEvent(m));let f=u();dispatchFocus(s.elementToFocusLocatedElement,f),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(f){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:f.toString(),success:!1})}};Eh.exports=bC});var qo=C((aD,Sh)=>{"use strict";Sh.exports=function(e,t){function r(i){let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}function n(){var a;let i=document.activeElement;for(;(a=i.shadowRoot)!=null&&a.activeElement;)i=i.shadowRoot.activeElement;return i}function o(i,a){a&&(a.dispatchEvent(r("focusout")),a.dispatchEvent(r("blur"))),i.dispatchEvent(r("focusin")),i.dispatchEvent(r("focus")),typeof i.focus=="function"&&i.focus();let c=n();a&&c===a&&typeof a.blur=="function"&&a.blur()}if(e){let i=getLocatedElement(e);if(i&&i!==t)try{o(i,t)}catch{}}else t&&typeof t.blur=="function"&&t.blur()}});var Xr=C((cD,xh)=>{"use strict";var ls=require("lodash"),_e=(U(),w(H)).getLogger("webdriver"),TC=require("ua-parser-js"),EC=Do(),{SeleniumError:vC,SeleniumCrashError:SC}=(K(),w(Z)),el=(M(),w(q)),IC=Th(),xC=vh(),RC=qo(),{isOldProtocol:us}=Yc(),{featureFlagsService:CC}=(le(),w(me)),{W3C_ELEMENT_ID:PC}=(Es(),w(Rn)),[Nt,kC]=[0,2],{extractElementId:ct,getCdpAddressForHost:AC}=el,jo=Ie(),{SeleniumPerfStats:_C,SELENIUM_PERF_MARKS:ds}=Gs(),Dt=()=>(he(),w(Re)).getSessionPlayer().codeSnippets,OC=()=>(he(),w(Re)).getSessionPlayer().locatorBuilderUtils,Ih=()=>(he(),w(Re)).getSessionPlayer().utils;async function LC(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await AC(r):void 0}catch(r){_e.info("Error getting cdpAddress",r);return}}var tl=class extends IC{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,r,n,o,i,a,c=new _C,l=!1,u){var h,g,y,b,I;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=(y=(g=(h=e==null?void 0:e.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.ignoreHiddenTagsText,this.browserClosedCallbacks=[];let p=EC.buildSeleniumOptions(e,t,r,n,o,i,a,u);p.desiredCapabilities&&delete p.desiredCapabilities.marionette,p.capabilities&&delete p.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(u==null?void 0:u.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=c;let f=l?0:1500,m=l?()=>{}:()=>this.executeJS("window.focus()");try{jo.log("before initClient in webdriver.js init");let T=await this.initClient(p,t,a);jo.log("after initResult before getCdpAddress in init"),this.cdpUrl=await LC(T),jo.log("after getCdpAddress in webdriver.js init"),_e.info(`init new session testName: ${t}`,{sessionId:this.getSessionId(),testResultId:a}),await el.delay(f),await m(),jo.log("after focus and delay in webdriver.js init")}catch(T){if(_e.error("failed to init webdriver",{err:T}),T.seleniumStack){let v=new vC(T.seleniumStack),x=((I=(b=e==null?void 0:e.company)==null?void 0:b.activePlan)==null?void 0:I.plan)==="free";throw v.message.includes("timed out waiting for a node")&&x?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):v}throw new Error("failed to init client driver")}}initUnsupportedActions(e){e&&(this.unsupportedActions={...this.unsupportedActions,move:!0})}isAlive(){return this._isAlive}maxKeepAliveGap(){let e=n=>ls.zip(ls.dropRight(n,1),ls.drop(n,1)),t=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),r=e(t).map(([n,o])=>o-n);return Math.max(...r)}isClosedBrowserError(e){return!e||!e.seleniumStack||!e.message?!1:e.seleniumStack.type==="UnknownError"&&(e.message.includes("CLIENT_STOPPED_SESSION")||e.message.includes("BROWSER_TIMEOUT")||e.message.includes("was terminated due to TIMEOUT"))||e.seleniumStack.type==="NoSuchWindow"&&e.message.includes("window was already closed")||e.seleniumStack.type==="SelectorTimeoutError"&&e.message.includes("chrome not reachable")}start(){if(this.started)return;this.started=!0;let e=this,t=function(){function r(a){e._keepAliveRequests.push({start:Date.now(),id:a})}function n(a,c){(e._keepAliveRequests.find(l=>l.id===c)||{})[a]=Date.now()}function o(){return window.getTestimStatus&&window.getTestimStatus()}if(e.queue.getQueueLength()>0)return Promise.resolve();let i=el.guid();return r(i),e.executeJS(o).then(()=>{e._isAlive=!0,n("end",i),e.browserClosedFailedKeepAlives=0}).catch(a=>{if(n("error",i),a.seleniumStack&&a.seleniumStack.type==="UnexpectedAlertOpen")return e.browserClosedFailedKeepAlives=0,_e.warn("close unexpected alert open"),e.alertAccept().catch(c=>_e.warn("failed to click on alert",{err:c}));if(_e.warn("err while getting testim status",{err:a}),e._isAlive=!1,e.isClosedBrowserError(a)){e.browserClosedFailedKeepAlives++;let c=3;e.browserClosedFailedKeepAlives>=c&&e.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else e.browserClosedFailedKeepAlives=0})};this.keepAliveTimer=setInterval(t,1e4)}switchToLocatedFrame(e){return this.getElement(e).then(async t=>{let r=ct(t.value);return await this.switchToFrame({ELEMENT:r,[PC]:r}),t})}switchToFrame(e){return this.frame(e)}switchToTopFrame(){return this.frame().catch(e=>{var t;throw(t=e.message)!=null&&t.includes("ECONNREFUSED")?new SC:e})}getElement(e){let t=this.seleniumPerfStats.markStart(ds.GET_ELEMENT);return typeof e=="string"||typeof e=="number"?this.getElementBySelector(`[testim_dom_element_id='${e}']`).finally(()=>this.seleniumPerfStats.markEnd(t,ds.GET_ELEMENT)):e&&e.shadowPath&&e.shadowPath.length||CC.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari()?this.execute(`
26
+ `))||""}`)}let i=(await(0,Qa.default)({type:"toggle",name:"isJs",message:"Add support for TypeScript?",initial:!0,active:"no",inactive:"yes"})).isJs?"template.js":"template.ts",a="codim",c=kt.join(__dirname,a,i),l=kt.join(process.cwd(),e),u=(0,Ya.default)(`Creating new test project in ${l}`).start();await An(c,l);let p=kt.join(__dirname,a,i,"package.json"),f=kt.join(process.cwd(),e,"package.json"),h=(await At.promises.readFile(p)).toString().replace("~testim-codeful-test-project~",r);await At.promises.writeFile(f,h);let g="node_modules",w=kt.join(process.cwd(),e,".gitignore");await At.promises.writeFile(w,g),u.succeed(),u=(0,Ya.default)("Installing dependencies").start(),await ZI("npm install",{cwd:l}),u.succeed(),console.log(`Testim Dev Kit project folder successfully created in ${l}.`)}var At,kt,_m,Ya,oo,Qa,Om,Nm,ZI,Dm=F(()=>{"use strict";At=S(require("fs")),kt=S(require("path")),_m=S(require("child_process")),Ya=S(require("ora")),oo=S(require("chalk")),Qa=S(require("prompts")),Om=S(require("validate-npm-package-name")),Nm=require("util");K();Qi();ZI=(0,Nm.promisify)(_m.exec)});var ec={};W(ec,{preloadTests:()=>Za});async function Za(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Fm.memoize(async()=>{let t=await ze(s.testId,r=>Um.loadTest({...e,testId:r}),{concurrency:2});return Mm.keyBy(t,"testData.id")},"loadTests",tx,[e,s.testId])()}var Mm,Fm,Um,tx,io=F(()=>{"use strict";Mm=S(require("lodash")),Fm=S(Ct()),Um=S(pe());M();tx=1e3*60*60*10});var tc={};W(tc,{checkNpmVersion:()=>nx,getPackageVersion:()=>Wm});function Wm(){return Gt()}async function nx(){if(!et)try{let s=await de(rx(),5e3,"The API call to NPM timed out"),e=Wm();e&&jm.lt(e,s)&&console.log(qm.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){sx.warn("Failed to get NPM version",{err:s})}}var qm,jm,$m,Bm,sx,rx,sc=F(()=>{"use strict";qm=S(require("chalk")),jm=S(require("semver"));M();ne();$m=S(Ar()),Bm=S(Ct());U();sx=G("npm-driver"),rx=Bm.memoize(()=>$m.getLatestPackageVersion("@testim/testim-cli"),"getNpmVersion")});var rc,ox,Us,Gm,Vm,nc,Hm,Km=F(()=>{"use strict";M();K();U();Xe();rc=G("testimNgrok"),ox=".whitelisted-ngrok.testim.io",Us="",Vm=async(s,e={})=>{if(!e.ngrokToken)throw new N("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${Oe()}-${s.projectData.projectId}${ox}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await ss("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(rc.info("replace https to http"),Us=o.replace("https://","http://")):Us=o,s.tunnelDiagnostics&&nc(),s.baseUrl=Us},nc=async(s=!0)=>{try{let t=(await ss("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===Us);console.log("ngrok stats",n),rc.info("ngrok stats",{tunnel:n})}catch(e){rc.error("error collecting ngrok stats",{err:e})}s&&(Gm=setTimeout(()=>nc(),1e4))},Hm=async s=>{if(!Us)return;clearTimeout(Gm),s.tunnelDiagnostics&&await nc(!1),await(await ss("ngrok")).disconnect(Us)}});var _t,ic,zm,qs,ax,cx,oc,ao,lo,co,lx,Jm,Xm,Ym=F(()=>{"use strict";_t=S(require("os")),ic=S(require("fs")),zm=S(require("child_process"));M();qs=S(pe()),ax="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",cx={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"}},oc=_t.tmpdir(),ao=`${oc}/cloudflared`,lo=null,co=null,lx=async()=>{if(await yt(ao))return;let e=cx[_t.platform()+_t.arch()];if(!e)throw new Error(`tunnel on ${_t.platform()+_t.arch()} platform is not supported.`);let t=e.extract?oc+e.path:ao;await Rs(`${ax}/${e.path}`,t),e.extract&&await Tr(t,oc),await ic.promises.chmod(ao,"755")},Jm=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([qs.getCloudflareTunnel(s.company.companyId,t),lx()]);lo=r._id,co=zm.spawn(ao,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await qs.forceUpdateCloudflareTunnelRoutes(s.company.companyId,lo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await ic.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Xm=async s=>{let e=[];return lo&&e.push(qs.deleteCloudflareTunnel(s.company.companyId,lo)),co&&e.push(new Promise((t,r)=>{co.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),co.kill()})),await Promise.all(e)}});var me={};W(me,{featureFlagsService:()=>po});var J,Zm,dx,px,mx,Qm,uo,ac,po,le=F(()=>{"use strict";J=S(require("rox-node"));U();M();ne();Zm=G("FeatureFlagsService"),dx=!et&&!0&&!Ri,px=2e4,mx=60*60*24,Qm=["labs","disabled","enabled"],uo=class extends J.default.Variant{constructor(e="disabled"){super(e,Qm)}getValue(){let e=super.getValue();return Qm.includes(e)?e:(Zm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},ac=class{constructor(){this.flags={useNewWSCLI:new J.default.Flag,useSafariWebdriverVisibilityChecks:new J.default.Flag,useClickimVisibilityChecks:new J.default.Flag,runGetElementCodeInAut:new J.default.Flag,enableFrameSwitchOptimization:new J.default.Flag,maximumJsResultSize:new J.default.Configuration(2e3*1024),skipFileInputClicks:new J.default.Flag,errorMessageOnBadNetwork:new J.default.Flag(!0),warnOnBadNetwork:new J.default.Flag(!1),overrideAzureStorageUrl:new J.default.Flag,useJsInputCodeInSafari:new J.default.Flag,useJsInputCodeInFirefox:new J.default.Flag,autoSaveDownloadFileFireFox:new J.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new J.default.Flag(!0),experimentalPreCodeCompilation:new J.default.Flag(!0),experimentalAsyncCustomCode:new J.default.Flag,useSameBrowserForMultiTests:new uo("labs"),highSpeedMode:new uo,usePortedHtml5DragDrop:new J.default.Flag,testNamesToBeforeSuiteHook:new J.default.Flag,addCustomCapabilities:new J.default.Variant("{}"),enableWorkerThreadsCliCodeExecution:new J.default.Flag(!0),LTNetworkCapabilities:new J.default.Flag,downloadToBase64:new J.default.Flag,dec2022eolBrowsers:new J.default.Flag,publicGridURL:new J.default.Configuration("public-grid.testim.io")},J.default.register("default",this.flags)}setProjectId(e){J.default.setCustomStringProperty("projectId",e)}setProjectType(e){J.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){J.default.setCustomStringProperty("productType",e)}setCompanyId(e){J.default.setCustomStringProperty("companyId",e)}setPlanType(e){J.default.setCustomStringProperty("planType",e)}setIsPOC(e){J.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){J.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){J.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!dx)return;let e={fetchIntervalInSec:mx,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return de(J.default.setup(Ii,e),px).catch(t=>Zm.error("failed to get feature flag status",t))}},po=new ac});var fo=C((NL,cc)=>{"use strict";var $r=require("os"),fx=require("ms"),hx=require("fs-extra"),gx=require("p-retry"),yx=require("portfinder"),wx=require("child_process"),jr=(M(),y(q)),bx=(rt(),y(ht)),Tx=pe(),{ArgError:ef}=(K(),y(Z)),{getLogger:Ex}=(U(),y(H)),{getExtensionsUrl:vx}=(Qn(),y(Yn)),{gridTypes:tf,CLI_MODE:Sx}=(ee(),y(fe)),{featureFlagsService:Ix}=(le(),y(me)),sf=Ex("lambdatestService"),xx="https://downloads.lambdatest.com/tunnel/v3",Rx={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"},mo=`${$r.tmpdir()}/LT`,Cx=`${mo}/LT`,Px=fx("15m"),te=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===tf.LAMBDATEST||e.type===tf.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){te.isLambdatestGrid(e)&&(te.lambdatestConfigPromise=te.lambdatestConfigPromise||Tx.fetchLambdatestConfig(),te.lambdatestConfig=await te.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Px:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await hx.pathExists(Cx))return;let t=Rx[$r.platform()+$r.arch()];if(!t)throw new Error(`tunnel on ${$r.platform()+$r.arch()} platform is not supported.`);let r=`${mo}.zip`;await jr.downloadAndSave(`${xx}/${t}`,r),await jr.unzipFile(r,mo)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){te.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await yx.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;te.tunnelName=jr.guid();let a=["--tunnelName",te.tunnelName,"--infoAPIPort",t];if(e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)a=[...a,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new ef("tunnel requires username and password");if(i)try{let u=new URL(i);a=[...a,"--proxy-host",u.hostname],u.port&&(a=[...a,"--proxy-port",u.port]),u.username&&u.password&&(a=[...a,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new ef("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),te.tunnel=wx.spawn("./LT",a,{cwd:mo});let c="",l="";te.tunnel.stdout.on("data",u=>{c+=u.toString()}),te.tunnel.stderr.on("data",u=>{l+=u.toString()});try{let u=await gx(()=>bx.get(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});sf.info("LT tunnel info",u)}catch(u){throw sf.error("Failed to start LT tunnel",{err:u,stdoutResult:c,stderrResult:l}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!te.tunnel))return new Promise((t,r)=>{te.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),te.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=te.lambdatestConfig.CAPABILITIES[t]||{},a={};te.tunnelName&&(a.tunnel=!0,a.tunnelName=te.tunnelName);let c=[],{mode:l,canary:u,ext:p,extensionPath:f,installCustomExtension:m}=e;if(l===Sx.EXTENSION&&!p){let h=vx({canary:u},!0);!f&&h[t]&&(c=[...c,h[t]]),f&&jr.isURL(f)&&(c=[...c,f])}return m&&jr.isURL(m)&&(c=[...c,m]),{build:r,name:`${n} - ${o}`,platform:te.lambdatestConfig.PLATFORM,selenium_version:te.lambdatestConfig.SELENIUM_VERSION,resolution:te.lambdatestConfig.RESOLUTION,timezone:te.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:Ix.flags.LTNetworkCapabilities.isEnabled()}}};cc.exports=te;cc.exports.LambdatestService=te});var uc={};W(uc,{connect:()=>af,disconnect:()=>cf,serveTunneling:()=>Ax});var ho,rf,lc,nf,of,kx,af,cf,Ax,dc=F(()=>{"use strict";Km();Fr();Ym();ho=S(require("ora")),rf=S(ot()),lc=S(fo());U();ee();nf=G("tunnel"),of=s=>{var e;return[Qt.LAMBDATEST,Qt.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},kx=s=>s.tunnelRoutes||s.gridData.type===Qt.HYBRID&&s.gridData.tunnel==="cloudflare",af=async s=>{if(!s.tunnel)return;let e=rf.default.getTokenV3UserData(),t;try{of(s)?(t=(0,ho.default)("Starting testim lambdatest tunnel...").start(),await lc.default.connectTunnel(s)):kx(s)?(t=(0,ho.default)("Starting testim cloudflare tunnel...").start(),await Jm(s)):(t=(0,ho.default)("Starting testim ngrok tunnel...").start(),await Vm(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw nf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},cf=async s=>{if(s.tunnel)try{of(s)?await lc.default.disconnectTunnel(s):"tunnelRoutes"in s?await Xm(s):await Hm(s)}catch(e){let t="catch error - failed to close tunnel";throw nf.error(t,{err:e}),new Error(t)}},Ax=async(s,e=new Promise(()=>{}))=>(await af(s),Ua(()=>cf(s)),await e)});var js=C((ML,pc)=>{"use strict";var yo=require("lodash"),{GridError:wo,ArgError:lf,GridConcurrencyError:_x}=(K(),y(Z)),{hasTestPlanFlag:Ox,promiseMap:Nx}=(M(),y(q)),{gridMessages:go,gridTypes:at}=(ee(),y(fe)),De=(U(),y(H)).getLogger("grid-service"),rs=pe(),Br={},uf=/(^(https?):\/{2})?(.*)/,df=null;function Lx(s){return s.protocol?s.protocol:[at.TESTIM,at.BROWSERSTACK,at.SAUCELABS].includes(s.type)&&s.port===443?"https":[at.TESTIM_ENTERPRISE,at.LAMBDATEST,at.DEVICE_FARM].includes(s.type)?uf.exec(s.host)[2]||"https":""}function Dx(s){return uf.exec(s)[3]}function bo(s){var w,b,I;let e=s&&Dx(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&Lx(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(w=s==null?void 0:s.hybrid)==null?void 0:w.tunnel,c=(b=s==null?void 0:s.external)==null?void 0:b.user,l=(I=s==null?void 0:s.external)==null?void 0:I.key,u=s==null?void 0:s.type,p=u===at.HYBRID?a&&s.hybrid.external&&s.hybrid.external[s.hybrid.tunnel]&&s.hybrid.external[s.hybrid.tunnel].user:c,f=u===at.HYBRID?a&&s.hybrid.external&&s.hybrid.external[s.hybrid.tunnel]&&s.hybrid.external[s.hybrid.tunnel].key:l,m=s==null?void 0:s.name,h=s&&(s._id||s.gridId),g=s==null?void 0:s.provider;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:h,tunnel:a,user:c,key:l,type:u,name:m,provider:g,tunnelUser:p,tunnelKey:f}}async function pf(s,e,t,r,n){let o;try{o=await n()}catch(c){throw De.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(go.UNKNOWN)}De.info("get grid info",Object.assign({},o,{projectId:s,companyId:e}));let i=()=>o.status==="success",a=()=>o.status==="error"&&o.code;if(!o||!a()&&!i())throw De.error("invalid response - get grid",{res:o}),new Error(go.UNKNOWN);if(i()){let c=bo(o.grid);return pc.exports.addItemToGridCache(t,e,c.gridId,c.slotId,r),c}throw a()&&o.code==="not-found"?new wo(go.NOT_FOUND):a()&&o.code==="no-available-slot"?new _x(`Failed to run test on ${r} - concurrency limit reached`):(De.error("invalid code error response - get grid",{res:o}),new wo(go.UNKNOWN))}function Mx(s,e,t,r,n){Br[s]={gridId:t,companyId:e,slotId:r,browser:n}}function Fx(s,e,t,r,n,o){return pf(t,e,s,n,()=>rs.getGridById(e,t,r,n,o))}function Ux(s,e,t,r,n,o,i){return pf(t,e,s,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(u=>(u.name||"").toLowerCase()===r.toLowerCase());return c!=null&&c._id?rs.getGridById(e,t,c._id,n,o):rs.getGridByName(e,t,r,n,o)})}function mf(s){return rs.getAllGrids(s)}async function ff(s,e,t){let n=(await Promise.resolve(t||mf(s))).find(o=>o._id===e);if(!n)throw new lf(`Failed to find grid id: ${e}`);return bo(n)}async function qx(s,e,t){let n=(await Promise.resolve(t||mf(s))).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new lf(`Failed to find grid name: ${e}`);return bo(n)}async function hf(s,e){let t=Br[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete Br[s],!r){De.warn("failed to find grid slot id",{projectId:e});return}De.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await rs.releaseGridSlot(i,e,r,n,o)}catch(a){De.error("failed to release slot",{projectId:e,err:a})}}async function jx(s){let e=Object.values(Br).filter(Boolean);if(e.length!==0){De.info("keep alive worker slots",{projectId:s,slots:e});try{await rs.keepAliveGrid(s,e)}catch(t){De.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function $x(s){df=setInterval(jx,1e4,s)}async function Bx(s){let e=Object.keys(Br);if(!yo.isEmpty(e)){De.warn("not all slots released before end runner flow",{projectId:s});try{await Nx(e,t=>hf(t,s))}catch(t){De.error("failed to release all slots",{err:t,projectId:s})}}}async function Wx(s){await Bx(s),clearInterval(df)}function Gx(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Vx(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function gf(s){let t=(()=>yo.isEmpty(s.testobjectSauce)?yo.isEmpty(s.saucelabs)?yo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=Gx(t,s),c=Vx(t,s);return Promise.resolve({host:r,port:n,path:o,protocol:i,type:t,user:c,key:a})}async function Hx(s,e){let t=s.company.companyId;return await ff(t,e.gridId,s.allGrids)}async function Kx(s){let{allGrids:e=void 0,company:t,host:r,useLocalChromeDriver:n,useChromeLauncher:o,gridId:i,grid:a}=s;if(n||o)return{mode:"local"};if(r)return gf(s);let c=t.companyId;if(i)return ff(c,i,e);if(a)return qx(c,a,e);if(Ox(s)||s.tunnelOnlyMode){De.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new wo("Missing host or grid configuration")}async function zx(s,e,t,r){return await(async()=>{let{host:i,project:a,grid:c,gridId:l,useLocalChromeDriver:u,useChromeLauncher:p,company:f}=t,m=f==null?void 0:f.companyId;if(u||p)return{mode:"local"};if(i)return gf(t);if(l)return Fx(r,m,a,l,s,e);if(c)return Ux(r,m,a,c,s,e,t);throw new wo("Missing host or grid configuration")})()}var Jx=async(s={},e={},t={},r={},n={})=>{let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,c=s.browser||t.browserValue,l=Boolean(s.tunnel),{maxRetries:u,currentRetry:p}=n;if(!i||!a||(a===at.LAMBDATEST&&await r.enableIfNeeded(e),a!==at.HYBRID||!o||!c||!u||!p))return e;let f=await rs.getHybridGridProvider({companyId:o,gridId:i,maxRetries:u,currentRetry:p,browser:c,usingTunnel:l});De.info("handling hybrid grid",{response:f,companyId:o});let m=bo({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&r.disable(),f.provider==="lambdatest"&&await r.enableIfNeeded(m),m};pc.exports={getGridSlot:zx,releaseGridSlot:hf,getGridData:Kx,getTestPlanGridData:Hx,addItemToGridCache:Mx,keepAlive:{start:$x,end:Wx},handleHybridOrVendorIfNeeded:Jx}});var mc=C((FL,yf)=>{"use strict";var To;function Xx(){return To||"master"}function Yx(s="master",e="false"){if(s!=null&&s.branch&&s.branch==="master"){To="master";return}if(s&&!s.isArchived){To=s.branch||s;return}To=e?"master":null}yf.exports={getCurrentBranch:Xx,setCurrentBranch:Yx}});var Wr=C((qL,Tf)=>{"use strict";var wf=require("ws"),UL=require("lodash"),{WEBSOCKET_HOST:Qx}=(ne(),y(ce)),bf=(M(),y(q)),ns=(U(),y(H)).getLogger("socket-ng-service"),{EventEmitter:Zx}=require("events"),eR=ot(),tR=5e3,fc=class extends Zx{constructor(){super(),this.clientId=bf.guid(),this.ws=null,this.filterMap={},this.listeners={}}onReconnect(e){ns.info("test result websocket re-connect"),setTimeout(()=>this.connect(e),tR)}formatUrl(e){return e.startsWith("http://")?e.replace("http://","ws://"):e.startsWith("https://")?e.replace("https://","wss://"):e}parseEvent(e){try{return JSON.parse(e)}catch(t){ns.error("failed to parse or trigger event",{err:t})}}connect(e){let t=this.formatUrl(Qx);return eR.getCustomTokenV3().then(r=>new Promise(n=>{let o={};global.proxyUri&&(o.agent=new global.ProxyAgent(global.proxyUri)),this.ws=new wf(`${t}?projectId=${e}&clientId=${this.clientId}&token=${r}`,o),this.ws.on("open",()=>(ns.info("websocket opened"),this.reSendAllExistingFilters(),this.onConnect&&this.onConnect(),n())),this.ws.on("close",i=>{ns.info("websocket closed",{event:i}),(!this.ws||this.ws.readyState===wf.CLOSED)&&this.onReconnect(e,r,t)}),this.ws.on("error",i=>{ns.info("websocket error",{event:i})}),this.ws.on("message",i=>{let a=this.parseEvent(i);a!=null&&a.type&&this.emit(a.type,a.data)})}))}sendMessage(e){if(!this.ws){ns.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(e))}catch(t){ns.error("failed to stringify message for sending",{err:t})}}listenOnce(e,t,r){let n=o=>{t(o)&&(r(o),this.removeListener(e,n))};this.on(e,n)}listenTo(e,t,r,n){function o(a){r(a)&&n(a)}(Array.isArray(t)?t:[t]).forEach(a=>{this.listeners[`${e}:${a}`]=this.listeners[`${e}:${a}`]||[];let c=o.bind(this);this.listeners[`${e}:${a}`].push(c),this.on(a,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(e=>{let t=this.filterMap[e];this.sendMessage({type:"add-filter",filter:t})})}addFilter(e,t,r,n=!1){return new Promise(o=>{let i=bf.guid(),a={query:t,id:i,type:r,fullDocument:n};this.listenOnce("add-filter:done",c=>c.id===i,o),this.sendMessage({type:"add-filter",filter:a}),this.filterMap[e]=a})}removeListeners(e,t){Object.keys(this.listeners).length!==0&&t.forEach(r=>{let n=this.listeners[`${e}:${r}`];n&&(delete this.listeners[`${e}:${r}`],n.forEach(o=>this.removeListener(r,o)))})}removeFilter(e,t){let r=this.filterMap[e];if(!r)return;let n=Array.isArray(t)?t:[t];this.removeListeners(e,n),delete this.filterMap[e],this.sendMessage({type:"remove-filter",filter:r})}};Tf.exports=new fc});var Ef={};W(Ef,{labFeaturesService:()=>yc});var sR,rR,hc,gc,yc,wc=F(()=>{"use strict";({featureFlagsService:sR}=(le(),y(me))),{getLabFeaturesByProjectId:rR}=pe(),hc=(U(),y(H)).getLogger("lab-features-service"),gc=class{constructor(){this.featuresForProject=[],this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(hc.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await rR(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){hc.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=sR.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:o}=this,i=n.find(c=>c.featureFlagName===e),a=i==null?void 0:i.enabled;return Boolean(o&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw hc.error(t,{featureFlagName:e.name}),new Error(t)}},yc=new gc});var Gr,bc,nR,Tc,oR,Ec,Eo,vo,So,Io,xo,Ro=F(()=>{"use strict";M();ee();Gr=s=>{let{status:e,sessionType:t,success:r}=s;return e===xe.FAILED||t===Yt.CODEFUL&&r===!1},bc=s=>{let{status:e}=s;return e===xe.ABORTED},nR=s=>{let{status:e,sessionType:t,success:r}=s;return e===xe.PASSED||t===Yt.CODEFUL&&r===!0},Tc=s=>s.runnerStatus===xe.SKIPPED,oR=s=>s.testStatus===Xt.EVALUATING,Ec=(s,e)=>e?!s.runConfig:!1,Eo=(s,e)=>Object.values(s).filter(t=>Tc(t)&&nt(t,e)).length,vo=s=>Object.values(s).filter(e=>Gr(e)&&oR(e)).length,So=(s,e)=>Object.values(s).filter(t=>Gr(t)&&!Ec(t,e)),Io=(s,e)=>Object.values(s).filter(t=>nR(t)&&!Ec(t,e)),xo=(s,e)=>Object.values(s).filter(t=>bc(t)&&!Ec(t,e))});var Sf={};W(Sf,{DebugReporter:()=>vc});function iR(s){let e=s.indexOf("--token");if(e===-1&&(e=s.indexOf("--t")),e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Co,vf,vc,If=F(()=>{"use strict";U();Ro();Co=G("debug-reporter"),vf={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},vc=class{constructor(e){this.options=e}onTestStarted(e,t){Co.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;Co.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}onTestPlanStarted(e,t,r,n,o,i,a){let c=iR(process.argv);Co.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:Object.assign({},this.options,vf),args:c})}onTestPlanFinished(e,t,r,n,o,i){let a=Io(e,i).length,c=Object.keys(e).length-a;Co.info("Test Plan Finished",{isAnonymous:o,passed:a,failed:c,testPlanName:t,options:Object.assign({},this.options,vf),duration:r,executionId:n})}}});var Ic={};W(Ic,{featureAvailabilityService:()=>$s});var Sc,$s,Vr=F(()=>{"use strict";ee();Sc=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===Qt.DEVICE_FARM}},$s=new Sc});var Rc={};W(Rc,{ConsoleReporter:()=>xc});var Ot,Hr,os,xf,Rf,xc,Cc=F(()=>{"use strict";Ot=S(require("chalk")),Hr=S(require("lodash"));M();ee();Vr();Ro();os={success:Ot.default.green,warn:Ot.default.yellow,error:Ot.default.red},{CLI_MODE:xf}=fe,Rf="device",xc=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,r,n){let o=n?"File":"Test",i=e.isTestsContainer?"":`(${e.testId})`,a=e.isTestsContainer?"":`url: ${Ot.default.underline(It(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,r,n){if(n)return;let o=e.success?xe.PASSED:xe.FAILED,i=e.isTestsContainer?" ":`(${e.testId})`,a=os[e.success?"success":"error"];console.log(a(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${o} ${i} duration: ${_n(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=It(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return r.isTestsContainer?r.name:`${r.name} : ${n}`});console.log(os.error("Failed runs are:")),console.log(os.error(t.join(`
27
+ \r`)))}onTestPlanFinished(e,t,r,n,o,i){let a=So(e,i),c=Io(e,i),l=xo(e,i),u=c.length,p=l.length,f=a.length,m="",h="";if($s.isTestStatusEnabled){let T=vo(e);m=` FAILED-EVALUATING: ${T}`,f-=T,h=` SKIPPED: ${Eo(e,this.options)}`}let g=this.buildTestPlanName(o,t,i),w,b=os[f?"error":"success"],I=`PASSED: ${u} FAILED: ${f}${m} ABORTED: ${p}${h} Duration: ${_n(r)}`;i||g.trim()===""||g.trim()==="Anonymous"?w=`Tests completed. ${I} (Execution ID: ${n})`:w=`Test plan${g} completed ${I} (${n})`,this.printWorkerDivider(),console.log(b(w)),this.printWorkerDivider(),this.printAllFailedTests(a)}buildTestPlanName(e,t,r){if(r)return"";let n=Hr.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,o=Hr.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Hr.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,a=Hr.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,r,n,o,i,a,c){let l=f=>{f.forEach((m,h)=>{var b;let g=(b=m.testData)!=null&&b.index?`- ${m.testData.index} / ${m.testData.total} Data set`:"",w=c?"":`(${m.testId})`;console.log(" ",h+1,":",`${m.name}${nt(m,this.options)?"-quarantine":""}`,w,g)})},u=a?`config '${a}'`:"default configs";if(c)console.log(`Run test plan, Project: ${this.options.project} (Execution ID: ${o}):`);else{let f=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${u}, Project: ${this.options.project}, Branch: ${this.branchToUse}${f}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`)}this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log(c?"File list:":"Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===xf.APPIUM?Rf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Ot.default.underline(n)} slot from ${Ot.default.underline(r)}`)}onGetSession(e,t,r){let n=r===xf.APPIUM?Rf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Ot.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e,t,r){let n=t?"file":"test";console.log(this.toWorkerIdPrefix(e),`Wait for ${n} complete`),r&&t&&console.log(this.toWorkerIdPrefix(e),`Chrome Debugger available at ${r}`)}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId;n?console.log(os.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a browser from the grid ${n}`)):this.options.useLocalChromeDriver?console.log(os.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally")):this.options.host&&console.log(os.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your Selenium grid at ${this.options.host}:${this.options.port||4444}`))}}});var Ac={};W(Ac,{JunitReporter:()=>Pc});function aR(s){let e=s.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function cR(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function lR(s){return`${s.visitedUrlsJson||""}`}async function uR(s,e,t,r,n,o){function i(f){let m=It(s,t,f.testId,f.resultId,r),h={$:{name:aR(f),classname:n,time:sa(f.duration),ownedBy:f.testOwnerName,ownerEmail:f.testOwnerEmail},"system-out":m};if(Gr(f)||bc(f)){let g=`Step Failed: ${f.failureReason||f.reason}`,w=Gr(f)?`${g} More info at: ${m}`:g;h.failure={$:{message:w}}}return Tc(f)&&nt(f,o)&&$s.isTestStatusEnabled&&(h.skipped={}),o.urls&&(h["visited-urls-list"]=cR(f),h["visited-urls-json"]=lR(f)),h}function a(f){let{results:m,testPlanName:h,configName:g}=f,w=m||{},I={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(w),failure:u(w),timestamp:c(e)};if($s.isTestStatusEnabled){I.skipped=Eo(w,o);let T=vo(w);I.failure-=T,I["failure-evaluating"]=T}return{$:I,testcase:Object.keys(w).map(T=>i(w[T]))}}function c(f){let m=Object.keys(f).map(g=>f[g].startTime),h=Math.min.apply(null,m);return h?new Date(h).toISOString():new Date().toISOString()}function l(f){return Object.keys(f).length}function u(f){return So(f).length+xo(f).length}let p={testsuites:{testsuite:e.map(f=>a(f))}};try{return new kc.Builder().buildObject(p)}catch(f){return dR(f)}}function dR(s){let e=new kc.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var kc,Cf,Pc,_c=F(()=>{"use strict";kc=S(require("xml2js"));M();Cf=require("fs");Vr();Ro();Pc=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await uR(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Cf.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}}onAllTestPlansFinished(e){return this.createResultsReport(e)}}});var Pf={};W(Pf,{TeamCityReporter:()=>Nc});function Bs(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var Oc,Nc,kf=F(()=>{"use strict";U();Oc=G("team-city-reporter");Nc=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return Bs(n)}onTestStarted(e,t,r,n,o){if(r){Oc.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,r,n,o,i){if(o){Oc.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${Bs(t)}' details='${Bs(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){Oc.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${Bs(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${Bs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${Bs(t)}']`)}}});var Af={};W(Af,{JsonReporter:()=>Lc});var Lc,_f=F(()=>{"use strict";Lc=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}}});var Of={};W(Of,{ChromeReporter:()=>Dc});var Dc,Nf=F(()=>{"use strict";M();Wa();Dc=class{constructor(e,t){this.options=e,this.branchToUse=t}onTestStarted(e,t,r,n){if(n)return;let o=It(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return eo(o)}}});var Mc={};W(Mc,{reporter:()=>se});function We(s){Po.prototype[s]=async function(...e){for(let t of this.reporters)t!=null&&t[s]&&await t[s](...e)}}var pR,Po,se,Et=F(()=>{"use strict";U();pR=G("reporter"),Po=class{setOptions(e,t){this.reporters=[];let r=e.reporters,{DebugReporter:n}=(If(),y(Sf));if(this.reporters.push(new n(e)),r===void 0||r.length===0){let{ConsoleReporter:o}=(Cc(),y(Rc));if(this.reporters.push(new o(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{JunitReporter:i}=(_c(),y(Ac));this.reporters.push(new i(e,t))}}else{if(r.includes("teamcity")){let{TeamCityReporter:o}=(kf(),y(Pf));this.reporters.push(new o(e))}if(r.includes("console")){let{ConsoleReporter:o}=(Cc(),y(Rc));this.reporters.push(new o(e,t))}if(r.includes("junit")){let{JunitReporter:o}=(_c(),y(Ac));this.reporters.push(new o(e,t))}if(r.includes("json")){let{JsonReporter:o}=(_f(),y(Af));this.reporters.push(new o(e))}if(r.includes("chrome")){let{ChromeReporter:o}=(Nf(),y(Of));this.reporters.push(new o(e,t))}}}async onTestPlanFinished(e,t,r,n,o,i,a){let c={};if(a){let l=Object.values(a);if(l.length>0){for(let u of Object.values(a))c[u.id]=u;for(let u of Object.keys(e))l.some(p=>p.parentResultId!==u)||(c[u]=e[u])}else pR.warn("childTestResults is not array"),c=e}else c=e;for(let l of this.reporters)if(l!=null&&l.onTestPlanFinished){let u=Date.now()-(r||0);await l.onTestPlanFinished(c,t,u,n,o,i)}}async onTestPlanStarted(e,t,r,n,o,i,a,c){for(let l of this.reporters)l!=null&&l.onTestPlanStarted&&await l.onTestPlanStarted(e,t,r,n,o,i,a,c)}async onGetSlot(e,t){for(let r of this.reporters)r!=null&&r.onGetSlot&&await r.onGetSlot(e,t)}async onGetSession(e,t,r){for(let n of this.reporters)n!=null&&n.onGetSession&&await n.onGetSession(e,t,r)}async onWaitToTestComplete(e,t,r){for(let n of this.reporters)n!=null&&n.onWaitToTestComplete&&await n.onWaitToTestComplete(e,t,r)}async onWaitToTestStart(e){for(let t of this.reporters)t!=null&&t.onWaitToTestStart&&await t.onWaitToTestStart(e)}async onAllTestPlansFinished(e){for(let t of e)if(t.childTestResults){t.results={};let r=Object.values(t.childTestResults);for(let n of r)t.results[n.id]=n;for(let n of Object.keys(e))r.some(o=>o.parentResultId!==n)||(t.results[n]=e[n])}for(let t of this.reporters)t!=null&&t.onAllTestPlansFinished&&await t.onAllTestPlansFinished(e)}};We("onGetBrowserFailure");We("onGetBrowserSuccess");We("onTestPlanStarted");We("onGetSlot");We("onGetSession");We("onTestFinished");We("onTestFailed");We("onTestPassed");We("onTestStarted");We("onTestIgnored");We("onWaitToTestStart");We("onWaitToTestComplete");se=new Po});var Fc=C((YL,Ff)=>{"use strict";var ko=Os(),{isCi:Lf}=(Wn(),y(ka)),Df=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Lf&&e?"ci-with-user":Lf?"ci":e?"cli-with-user":s;function Mf(s,e){return e&&e.type&&(s[`${e.type}Mode`]=!0),s}function mR({executionId:s,projectId:e,testId:t,resultId:r,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:l,user:u,lightweightMode:p,isStartUp:f,projectType:m,appSource:h}){let g=Mf({executionId:s,projectId:e,testId:t,resultId:r,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:Df(l,u),isStartUp:f,projectType:m,...["android","ios"].includes(m)&&h&&{appSource:h}},p);ko.trackWithCIUser("test-run-ci",g)}function fR({executionId:s,projectId:e,testId:t,resultId:r,result:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,source:u,user:p,lightweightMode:f,logger:m,isStartUp:h,projectType:g,appSource:w}){try{let b=Mf({executionId:s,projectId:e,testId:t,resultId:r,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Df(u,p),isStartUp:h,projectType:g,...["android","ios"].includes(g)&&w&&{appSource:w}},f);if(n.success){ko.trackWithCIUser("test-run-ci-success",b);return}ko.trackWithCIUser("test-run-ci-fail",Object.assign({},b,{failureReason:n.failureReason}))}catch(b){m.error("failed to update test end analytics",{err:b})}}function hR({executionId:s,projectId:e,sessionType:t}){ko.trackWithCIUser("batch-run-ci",{executionId:s,projectId:e,sessionType:t})}Ff.exports={analyticsTestStart:mR,analyticsTestEnd:fR,analyticsExecsStart:hR}});var qf=C((QL,Uf)=>{"use strict";var{ReportBase:gR}=require("istanbul-lib-report"),Uc=class extends gR{constructor(e){super(),e=e||{},this.appendToObject=e.appendToObject||{}}onStart(e){let t=e.getCoverageSummary();this.appendToObject=Object.assign(this.appendToObject,t.toJSON())}};Uf.exports=Uc});var Kf=C((Kr,Ws)=>{"use strict";var qc=pe(),yR=require("fs"),wR=require("fs/promises"),is=require("path"),bR=require("mkdirp"),Ao=(Xe(),y(Tt)),jf=require("istanbul-lib-report"),TR=require("istanbul-reports"),ER=qf(),vR=require("ora"),SR=require("moment"),IR=require("test-exclude"),{ArgError:Bf}=(K(),y(Z)),{promiseMap:$f}=(M(),y(q)),jc=(U(),y(H)).getLogger("test-run-status"),Wf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},xR=s=>!!Wf(s).search,Gf=s=>s?Wf(s).pathname.substring(1):"",Vf=(s,e)=>{let t=Gf(e);return!new IR({relativePath:!1,include:s}).shouldInstrument(t)},RR=s=>s.substring(0,s.indexOf("?"));Ws.exports.getSourceMap=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ao("convert-source-map");if(t==="file"&&!e)throw new Bf("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)};Ws.exports.remapCoverage=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await Promise.all(Object.values(t).map(async n=>{if(!n)return;let o=n.toObject();await Promise.all(o.sources.map(async(i,a)=>{if(Vf(r,i))return;let c=Hf(e,i);await bR(is.parse(c).dir),await wR.writeFile(c,o.sourcesContent[a])}))}))};var CR={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(xR(e)&&(e=RR(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=is.dirname(this.getPath(s));return is.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Hf=(s,e)=>`${is.resolve(s,Gf(e))}.js`;Ws.exports.saveCoverageReports=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=jf.createContext({dir:t,coverageMap:e,watermarks:jf.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Hf(r,a);return yR.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ER({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:CR}),TR.create(a,c).execute(i)}),o};Ws.exports.convertV8ToIstanbul=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Ao("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Vf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()};var PR=async(s,e,t)=>{let{mergeProcessCovs:n}=await Ao("@bcoe/v8-coverage"),o={result:[]},i=new Map,c=(await qc.getRealData(s,"testResult",`runId=${t}`)).data.docs;return await $f(c.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let u=await qc.getS3Artifact(l,9e4);await $f(u,async p=>{if(!i.has(p.url)){let f=p.text;p.sourceUrl&&(i.set(p.url,"TEMP"),f=await qc.getS3ArtifactText(p.sourceUrl)),i.set(p.url,{text:f,url:p.url,sourceMapType:p.sourceMapType,hash:p.hash})}delete p.text,o=n([o,{result:[p]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:o}};Ws.exports.calculateCoverage=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;jc.info("start js coverage process");let n=vR(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=is.resolve(s.codeCoverageReportPath||"./coverage"),i=is.resolve(o,`.js/${SR().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?is.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:u}]=await Promise.all([Ao("istanbul-lib-coverage"),PR(s.project,e,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}jc.info("start js coverage merge and remap",{numOfFiles:u.size,numMergedCoverages:l.result.length});let p=c.createCoverageMap({}),f={};await Promise.all(l.result.map(async({url:h,functions:g})=>{let{text:w,sourceMapType:b}=u.get(h),I=await Kr.getSourceMap({sourceMapType:b,url:h,source:w,sourceMapDir:a});f[h]=I;let T=await Kr.convertV8ToIstanbul(s,{source:w,sourceMap:I,functions:g});p.merge(T)})),await Kr.remapCoverage(s,i,f);let m=await Kr.saveCoverageReports(s,p,o,i);return n.succeed(),m}catch(c){let l="Failed to report coverage information";c instanceof Bf?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),jc.error(l,{err:c})}}});var Gs=C((ZL,Xf)=>{"use strict";var $c=require("lodash"),{guid:kR,calcPercentile:zf}=(M(),y(q)),Jf={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Bc=class{constructor(){this.marks=$c.mapValues(Jf,()=>[]),this.marks.ALL=[],this.startTimes={}}markStart(e){let t=kR();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){return{seleniumPerfMarks:this.marks,seleniumStats:$c.chain(this.marks).transform((e,t,r)=>{$c.isEmpty(t)||(e[`${r}_COUNT`]=t.length,e[`${r}_P50`]=zf(t,50),e[`${r}_P95`]=zf(t,95))},{}).value()}}};Xf.exports={SELENIUM_PERF_MARKS:Jf,SeleniumPerfStats:Bc}});var Gc=C((eD,eh)=>{"use strict";var{ArgError:Yf}=(K(),y(Z)),AR=require("express"),Qf=require("fs-extra"),_R=require("os"),Wc=require("path"),{lazyRequire:OR}=(Xe(),y(Tt)),NR=Wc.join(_R.tmpdir(),"testim/rca/"),_o={},zr={},Zf={"test-log":"consoleLogs","har-file":"networkLogs"},LR=Object.keys(Zf);function DR(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,_o[t.id]?{screenshot:_o[t.id]}:{})),Object.keys(zr).forEach(t=>{s.assets=s.assets||{},s.assets[Zf[t]]=zr[t]}),s.assets=s.assets||{},s.assets.screenshots=Object.values(_o)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath=s.failurePath||[],s.assets=s.assets||{},s.assets.screenshots=s.assets.screenshots||[]}}async function MR({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await OR("multer");t=typeof t=="string"?t:NR,await Qf.mkdirp(t);let n=r({storage:r.diskStorage({async destination(i,a,c){let l=JSON.parse(i.body.metadata||"{}");if(!l.testResultId)return c(new Error("missing testResultId"));let u=Wc.join(t,l.testResultId);try{await Qf.mkdirp(u)}catch(p){return c(p)}return c(null,u)},filename(i,a,c){let{fileName:l}=i.body,u=JSON.parse(i.body.metadata||"{}");if(!u.stepId&&!l)return c(new Error("missing stepId or fileName"));if(u.stepId){let p=Wc.extname(l);return c(null,`step_${u.stepId}_${u.stepName||""}${p}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return c(null,l)}})}),o=AR();return o.post("/",n.single("file"),(i,a)=>{let c=JSON.parse(i.body.metadata||"{}");c.stepId&&(_o[c.stepId]=i.file.path),c.testResultId&&LR.includes(c.subType)&&(zr[c.subType]=zr[c.subType]||[],zr[c.subType].push(i.file.path)),a.sendStatus(200)}),o.use((i,a)=>a.status(404).send("Endpoint Not Found")),await new Promise((i,a)=>{let l=require("http").createServer(o);l.listen(s,e),l.on("error",u),l.on("listening",()=>i(l.address()));function u(p){if(p.syscall!=="listen")return a(p);switch(p.code){case"EACCES":case"EPERM":return a(new Yf(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return a(new Yf(`Port ${s} is already in use`));default:return a(p)}}})}eh.exports={initServer:MR,mapFilesToLocalDrive:DR}});var th={};W(th,{OverrideTestDataBuilder:()=>Hc});var Nt,Vc,Hc,sh=F(()=>{"use strict";Nt=S(require("lodash"));M();U();Vc=G("override-test-data-builder"),Hc=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return Nt.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)&&!Nt.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Vc.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(Nt.isObject(e.overrideAllTestsData)&&!Nt.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Vc.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Vc.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return Nt.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(u=>this.generateTestUniqId(u)),i=o.indexOf(n),a=o.lastIndexOf(n),c=r[i],l=this.createNewTestItems(c,t);return r.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=Oe();return Object.assign({},e,{resultId:o,testData:{value:r,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});var oh=C((sD,Kc)=>{"use strict";var Jr=require("lodash"),He=(M(),y(q)),Ge=(ee(),y(fe)),FR=js(),vt=pe(),{ArgError:nh}=(K(),y(Z)),{getLogger:UR}=(U(),y(H)),{reporter:Vs}=(Et(),y(Mc)),{registerExitHook:qR}=(Fr(),y(Jn)),{calculateCoverage:jR}=Kf(),{SeleniumPerfStats:$R}=Gs(),{mapFilesToLocalDrive:BR}=Gc(),{TESTIM_CONCURRENT_WORKER_COUNT:WR}=(ne(),y(ce)),{featureFlagsService:rh}=(le(),y(me)),{OverrideTestDataBuilder:GR}=(sh(),y(th)),{featureAvailabilityService:VR}=(Vr(),y(Ic)),Ve=UR("test-run-status"),HR=He.getEnvironmentGitBranch(),KR=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,zR=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,JR=He.getRunnerVersion();async function Oo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ve.warn("failed to run hook",{err:t}),new nh(`failed to run hook promise ${t.message}`)}}var No=class{constructor(e,t,r,n){this.options=t,this.options.runParams=this.options.runParams||{},this.startTime=null,this.fileUserParamsData=this.options.userParamsData,this.beforeSuiteParams={},this.branchToUse=n,this.exportsGlobal={},this.testInfoList=e,this.executionStartedPromise=Promise.resolve();let o=He.getUniqBrowsers(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:WR||t.parallel||1,browser:o,gitBranch:HR,gitCommit:KR,gitRepoUrl:zR,runnerVersion:JR,gridHost:t.host||t.gridData.host,testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(a=>a.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||t.gridData.gridId,gridName:t.grid||t.gridData.name,gridType:t.gridData.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:He.getSessionType(t)},this.seleniumPerfStats=new $R,this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,isTestsContainer:l,testId:u,name:p,testStatus:f,testCreatorName:m,testCreatorEmail:h,testOwnerName:g,testOwnerEmail:w,testLabels:b,testSuites:I,allLabels:T}=a,v={originalTestResultId:t,previousTestResultId:r,config:Jr.cloneDeep(c),testId:u,status:"QUEUED",name:p,resultId:e,isTestsContainer:l,retryCount:i,testStatus:f};return this.testRunStatus[e]=Object.assign({},v,{testCreatorName:m,testCreatorEmail:h,testOwnerName:g,testOwnerEmail:w,testLabels:b,testSuites:I,allLabels:T}),vt.addTestRetry({projectId:n,runId:o,testId:u,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:v})}getAllTestResults(){return this.testRunStatus}testStart(e,t,r,n){let o=this.getTestResult(r);o.workerId=e;let i=this.options.files.length>0;return Vs.onTestStarted(o,e,n,i,r),o}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await vt.updateTestDataArtifact(n,e.testId,e.resultId,e.config.testData,i.defaults)}catch(u){Ve.error("failed to upload test data artifact (runner)",{err:u})}let c=Jr.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,vt.updateTestStatus(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(He.isQuarantineAndNotRemoteRun(e,this.options))return;let n=this.exportsGlobal;try{let o=await Oo(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ve.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ve.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Ge.testStatus.EVALUATING&&VR.isTestStatusEnabled){Vs.onTestIgnored(e,r,`test in ${Ge.testStatus.EVALUATING} status`);return}if(l){Vs.onTestPassed(o);return}Vs.onTestFailed(r,r.failureReason,He.getTestUrl(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?Ge.runnerTestStatus.PASSED:Ge.runnerTestStatus.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Vs.onTestIgnored(e,r,`test in ${Ge.testStatus.QUARANTINE}`)}testEnd(e,t,r,n,o){let i=this.testRunStatus[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&&BR(i,Ve),i.resultUrl=He.getTestUrl(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;Vs.onTestFinished(i,e,o,c);let l=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await Oo(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ve.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 vt.updateTestStatus(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Ve.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}calcTestRunStatus(){let{options:e,testInfoList:t}=this,r=e.company.companyId;this.testRunStatus=t.reduce((n,o)=>{var a,c,l,u;n[o.resultId]={testId:o.testId,status:He.isQuarantineAndNotRemoteRun(o,e)?Ge.runnerTestStatus.SKIPPED:Ge.runnerTestStatus.QUEUED,name:o.name,resultId:o.resultId,isTestsContainer:o.isTestsContainer,testStatus:o.testStatus||Ge.testStatus.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels};let i=e.browser?He.getRunConfigByBrowserName(e.browser,e.saucelabs,e.browserstack):o.runConfig;if(i&&rh.flags.dec2022eolBrowsers.isEnabled()&&((a=He.getBrowserInfo(i.browserValue))!=null&&a.eol))throw new nh(`Unsupported Browser: ${i.browserName}`);return n[o.resultId].config=Object.assign({},this.execConfig,{companyId:r,testData:(c=o.testData)!=null&&c.value?o.testData.value:null}),n[o.resultId].config.isBeforeTestPlan=o.isBeforeTestPlan,n[o.resultId].config.isAfterTestPlan=o.isAfterTestPlan,n[o.resultId].config.testDataTotal=((l=o.testData)==null?void 0:l.total)||null,n[o.resultId].config.testDataIndex=((u=o.testData)==null?void 0:u.index)||null,n[o.resultId].config.baseUrl=e.baseUrl||o.baseUrl||o.testConfig.baseUrl,n[o.resultId].config.testConfig=o.overrideTestConfig||o.testConfig,n[o.resultId].config.browser=i.browserValue.toLowerCase(),n},{})}async executionStart(e,t,r,n,o){Ve.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;qR(()=>Promise.all([FR.keepAlive.end(t),vt.reportExecutionFinished("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...rh.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await Oo(i.beforeSuite,l),p=new GR(u,Jr.cloneDeep(this.testInfoList),t);this.testInfoList=p.overrideTestData(),this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:f}=this,m=[],h=[],g=[];for(let b of f){if(b.isBeforeTestPlan){m.push(b);continue}if(b.isAfterTestPlan){g.push(b);continue}h.push(b)}let w=async()=>{let b=Jr.cloneDeep(this.testRunStatus);await He.promiseMap(Object.keys(b),async x=>{var k;let A=b[x],L=(k=A.config)==null?void 0:k.testData,B=A.testId,$=await vt.updateTestDataArtifact(t,B,x,L,c.defaults);$&&(delete A.config.testData,A.config.testDataUrl=$)});let I=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),T={executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:I,intersections:i.intersections},v=vt.reportExecutionStarted(T);return this.executionStartedPromise=v,v.catch(x=>Ve.error(x)),v};try{await w()}catch(b){Ve.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:m,tests:h,afterTests:g}}concatSeleniumPerfMarks(e){Jr.chain(e).keys().each(t=>{this.seleniumPerfStats.marks[t]&&(this.seleniumPerfStats.marks[t]=[...this.seleniumPerfStats.marks[t],...e[t]])}).value()}async executionEnd(e){var u;let t=He.groupTestsByRetries(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:p,testStatus:f}of t)p===Ge.runnerTestStatus.PASSED&&n++,p===Ge.runnerTestStatus.SKIPPED&&o++,p===Ge.runnerTestStatus.FAILED&&f===Ge.testStatus.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await Oo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(p){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ve.warn("error while running afterSuite Hook",{err:p,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await jR(this.options,this.branchToUse,r,e);if(c.coverageSummary=l,!((u=this.options.lightweightMode)!=null&&u.onlyTestIdsNoSuite))try{return await vt.reportExecutionFinished("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(p){throw Ve.error("Failed to update suite finished",{err:p}),p}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await vt.updateExecutionTests(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}};Kc.exports=No;Kc.exports.TestRunStatus=No});var Fo=C((rD,mh)=>{"use strict";var XR=require("fs"),ch=require("path"),as=require("lodash"),YR=require("crypto"),lh=(M(),y(q)),QR=(ne(),y(ce)),ZR=fo(),{getLogger:eC}=(U(),y(H)),{featureFlagsService:Lo}=(le(),y(me)),{CLI_MODE:Do,mobileWeb:tC,gridTypes:Jc}=(ee(),y(fe)),Xr=eC("testim-desired-capabilities-builder"),ih=QR.WEBDRIVER_DEBUG?"verbose":"silent",zc={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},uh=["--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"],Xc=(...s)=>YR.createHash("sha256").update(s.join("")).digest("hex"),Mo=s=>s.type===Jc.DEVICE_FARM||s.type===Jc.HYBRID&&s.provider==="devicefarm",sC=s=>{s.hasOwnProperty("version")&&(s.browserVersion=s.version,delete s.version),s.hasOwnProperty("platform")&&(s.platformName=s.platform,delete s.platform),s.hasOwnProperty("acceptSslCerts")&&(s.acceptInsecurecerts=s.acceptSslCerts,delete s.acceptSslCerts),s.hasOwnProperty("unexpectedAlertBehaviour")&&(s.unhandledPromptBehavior=s.unexpectedAlertBehaviour,delete s.unexpectedAlertBehaviour)};function rC(s,e){let t={browserName:"safari"};return e==="safari technology preview"&&(t["safari.options"]={technologyPreview:!0}),Object.assign(s.desiredCapabilities,t),s}function Yc(s){return XR.readFileSync(s,{encoding:"base64"})}function dh(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&lh.isURL(s))&&s){let r=Yc(s);Xr.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Xc(r)} current extension count: ${e.length}`),e.push(r)}}function ph(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,l=r||c,u=`--load-extension=${l}`;Xr.info(`adding extension: testim unpacked , path: ${l}`),t.push(u);return}let o=s.canary?"-master.zip":".zip",i=ch.join(process.cwd(),`testim-headless${o}`),a=Yc(i);Xr.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Xc(a)} current extension count: ${e.length}`),e.push(a)}function nC(s,e,t,r,n,o,i){var g,w;let a=t.seleniumName||t.browserValue,c=[],l=[...uh];e.headless&&l.push("--headless");let u=()=>e.mode!==Do.EXTENSION,p={prefs:{"profile.default_content_setting_values.popups":zc.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":zc.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:u()};Mo(n)&&(p.prefs["download.default_directory"]="C:\\Users\\testnode",p.w3c=!0,s.desiredCapabilities.version="latest-1",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Mo(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(p.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(b=>l.push(`--${b}`)),e.chromeBlockLocation&&(p.prefs["profile.default_content_setting_values.geolocation"]=zc.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(w=(g=e.projectData)==null?void 0:g.defaults)!=null&&w.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function f(){t.mobileEmulation&&(p.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+tC.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}f(),dh(r,c,i),e.mode===Do.EXTENSION&&ph(e,c,l,o,i),c.length>0&&(p.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(p.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),p.args=l;let m={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],h={MicrosoftEdge:"ms",chrome:"goog"}[a];return ZR.isLambdatestGrid(n)&&delete p.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[m]=p),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${m}`]=p),s}var oC=as.memoize(nC,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(as.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return Xc(i,a,c,r,l,o)}),ah=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];function iC(s,e,t){let r={"pdfjs.disabled":!0};if(Lo.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":ah.join(","),"browser.helperApps.neverAsk.openFile":ah.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Do.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=ch.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=Yc(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function aC(s,e,t){let{saucelabs:r}=s;return r!=null&&r.username&&r.accessKey?t?(t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion,Object.assign({},t.sl,r,{name:e})):Object.assign({},r,{name:e}):{}}function cC(s,e,t){return as.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,s.browserstack,{name:e})):Object.assign({},s.browserstack,{name:e})}function lC(s){return s.perfecto?s.perfecto:{}}function uC(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function dC(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=lh.buildBasicHeader(o,i)),a}function pC(s,e,t,r,n,o,i,a=null){var g,w;if(r.mode==="local"){let b=[],I=[...uh],T={};return s.headless&&I.push("--headless"),s.silentDebuggerExtensionApi&&I.push("--silent-debugger-extension-api"),s.remoteDebuggingPort!==void 0&&I.push(`--remote-debugging-port=${s.remoteDebuggingPort}`),s.chromeExtraArgs&&s.chromeExtraArgs.forEach(v=>I.push(`--${v}`)),s.chromeBinaryLocation&&(T.binary=s.chromeBinaryLocation),s.mode!=="selenium"&&ph(s,b,I,null,a),dh(n,b,a),{logLevel:ih,desiredCapabilities:{chromeOptions:{args:I,extensions:b,...T},browserName:"chrome"},host:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=s,u={host:r.host,port:r.port||4444,path:r.path||"/wd/hub",protocol:r.protocol||"http",logLevel:ih,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,s.getSessionTimeout),getSessionRetries:a.getSessionRetries||s.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{javascriptEnabled:!0,locationContextEnabled:!0,handlesAlerts:!0,rotatable:!0,acceptSslCerts:!0,unexpectedAlertBehaviour:"accept",nativeEvents:!0,testName:e}},p=dC(s,r);as.isEmpty(p)||(u.headers=p),Mo(r)&&(s.oldCapabilities=!1,s.w3cCapabilities=!0,u.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),s.proxyForGrid&&(u.agent=new global.ProxyAgent(global.proxyUri)),s.disableNativeEvents&&(u.desiredCapabilities.nativeEvents=!1),r.user&&r.key&&(r.type==="saucelabs"&&(s.saucelabs=s.saucelabs||{},s.saucelabs.username=s.saucelabs.username||r.user,s.saucelabs.accessKey=s.saucelabs.accessKey||r.key),r.type==="browserstack"&&(s.browserstack=s.browserstack||{},s.browserstack["browserstack.user"]=s.browserstack["browserstack.user"]||r.user,s.browserstack["browserstack.key"]=s.browserstack["browserstack.key"]||r.key)),r.key&&r.type==="perfecto"&&(s.perfecto.securityToken=r.key);let f=Number(s.browserTimeout/1e3),m=s.browser||(t==null?void 0:t.browserValue);as.merge(u.desiredCapabilities,aC(s,e,t),cC(s,e,t),lC(s,e,t),uC(s,m,f),a==null?void 0:a.getCapabilities(s,m,o,i,e));let h=null;switch(!s.ext&&!s.extensionPath&&((g=r.host)!=null&&g.endsWith(".testim.io"))&&!s.canary&&s.mode===Do.EXTENSION&&(m==="chrome"?h="/opt/testim-headless":m==="edge-chromium"&&(h="C:/selenium/testim-headless")),(w=r.host)!=null&&w.endsWith(".testim.io")&&m==="edge-chromium"&&(u.desiredCapabilities.version="83"),m){case"chrome":case"edge-chromium":u=oC(u,s,t,n,r,h,a);break;case"firefox":u=iC(u,s,a);break;case"safari":case"safari technology preview":u=rC(u,m);break;default:break}as.merge(u.desiredCapabilities,s.seleniumCapsFileContent);try{let b={"hub.lambdatest.com":"lambdatest",[Lo.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},I=A=>A[r.provider]||A[u.host]||A[b[u.host]],T=A=>{var L,B;return I(A)||A[(L=u.desiredCapabilities)==null?void 0:L.browserName]||A[(B=u.desiredCapabilities)==null?void 0:B.version]||A||{}},v=JSON.parse(Lo.flags.addCustomCapabilities.getValue()||"{}"),x=T(T(v));Object.keys(x).length&&(Xr.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(u.desiredCapabilities,x))}catch(b){Xr.error("Failed to load custom capabilities",{error:b,customCapabilities:Lo.flags.addCustomCapabilities.getValue()})}return Mo(r)&&u.desiredCapabilities&&!u.capabilities&&(sC(u.desiredCapabilities),u.capabilities={alwaysMatch:u.desiredCapabilities,firstMatch:[{}]},delete u.desiredCapabilities),u}function mC({projectType:s,gridInfo:e,testRunConfig:t,nativeApp:r,options:n,appPath:o,androidActivityWait:i}){let{deviceModel:a,osVersion:c,deviceUdid:l}=n,u={};if(!r&&!o)throw Error("missing mobile app!");if(e.type!==Jc.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid");let p={protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`,logLevel:n.appiumLogLevel},f={"headspin:capture":!0,"appium:autoAcceptAlerts":!0,"appium:noReset":!0};switch(s){case"ios":f={...f,platformName:"iOS","appium:automationName":"XCUITest",...r&&{"appium:bundleId":r.id},...o&&{"appium:app":o}};break;case"android":f={...f,platformName:"Android","appium:automationName":"UiAutomator2","appium:appWaitActivity":i,...r&&{"appium:appPackage":r.id||r.packageName,"appium:appActivity":r.activity},...o&&{"appium:app":o}};break;default:throw Error(`unsupported mobile project ${s}`)}return a&&(u.model=a),c&&(u.os_version=c),l&&(u.device_id=l,delete u.model,delete u.os_version),as.isEmpty(u)||(f["headspin:selector"]=u),{...p,desiredCapabilities:f,capabilities:f}}mh.exports={buildSeleniumOptions:pC,buildAppiumOptions:mC}});var hh=C((nD,fh)=>{"use strict";fh.exports=function s(e){function t(m){if(!m)return!1;switch(m.nodeType){case Node.ELEMENT_NODE:case Node.DOCUMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:return!0;default:return!1}}function r(m){return m?n(m.parentNode,t):null}function n(m,h){for(let g=m;g&&g!==m.ownerDocument;g=g.parentNode)if(h(g))return g;return null}function o(m,h){for(let g=m;g&&g!==m.ownerDocument;g=r(g))if(h(g))return g;return null}function i(m,h){if(!m||!h)return null;m instanceof DocumentFragment&&(m=m.host);let w=window.getComputedStyle(m).getPropertyValue(h);if(w&&w!=="inherit")return w;let b=r(m);return i(b,h)}function a(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 w=i(m,"stroke-width");return!!w&&parseInt(w,10)>0}return i(m,"overflow")==="hidden"?!1:Array.from(m.childNodes).some(w=>w.nodeType===Node.TEXT_NODE?!0:t(w)?a(w):!1)}function c(m){return i(m,"overflow")==="hidden"}function l(m){return!m||!c(m)||!m.childNodes.length?!1:Array.from(m.childNodes).every(h=>h.nodeType===Node.TEXT_NODE?!1:!t(h)||!a(h)?!0:l(h))}function u(m){return m?m.parentNode&&m.parentNode.host?!0:u(m.parentNode):!1}if(!u(e)&&!document.contains(e))return!1;switch(e.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let m=n(e,h=>h.tagName.toUpperCase()==="SELECT");return s(m)}case"INPUT":if(e.type==="hidden")return!1;break;default:break}if(i(e,"visibility")!=="visible")return!1;let p=!!o(e,m=>Number(i(m,"opacity"))===0),f=!!o(e,m=>i(m,"display")==="none");return!(p||f||!a(e)||l(e))}});var Qc=C((oD,gh)=>{"use strict";function fC(s){return s.message&&s.message.match(/Command not found/)||s.message==="HTTP method not allowed"||s.message==="Unknown error"||s.message&&s.message.match(/Unknown timeout type/)||s.seleniumStack&&s.seleniumStack.type==="UnknownCommand"||s.message&&s.message.match(/did not match a known command/)||s.message&&s.message.match(/Server returned HTTP response code: 405 for URL/)||s.seleniumStack&&s.seleniumStack.message==="The arguments passed to a command are either invalid or malformed."||s.message.match(/Invalid timeout type specified: ms/)}function hC(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}gh.exports={isOldProtocol:fC,encodeForSafari:hC}});var Eh=C((iD,Th)=>{"use strict";var gC=require("@testim/webdriverio"),bh=require("promise-queue"),yh=(ne(),y(ce)),{UNICODE_CHARACTERS:wh,W3C_ELEMENT_ID:yC}=(Es(),y(Pn)),wC=hh(),Uo=(U(),y(H)).getLogger("WebDriverApi"),{isOldProtocol:cs,encodeForSafari:bC}=Qc(),{extractElementId:Yr}=(M(),y(q)),{SELENIUM_PERF_MARKS:Hs}=Gs();bh.configure(Promise);var Zc=Ie(),TC=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},el=class{constructor(){this.w3cRequests={}}windowHandleMaximize(){return this.addToQueue(()=>this.client.windowHandleMaximize().then(e=>({height:e.value.height,width:e.value.width})))}rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";return Uo.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),Promise.reject(e)}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof yh.REQUESTS_QUEUE_SIZE<"u"&&(e=yh.REQUESTS_QUEUE_SIZE);let t=1/0;this.queue=new bh(e,t)}addToQueue(e){let t=this.seleniumPerfStats.markStart();return this.queue.add(e).catch(r=>this.rejectWithLog(r,e)).finally(()=>this.seleniumPerfStats.markEnd(t))}async initClient(e,t,r){this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.client=gC.remote(e),this.initQueueRequests(),Zc.log("right before addToQueue");let n=this.seleniumPerfStats.markStart(Hs.GET_BROWSER);try{await this.addToQueue(()=>(Uo.info("requesting browser",{testResultId:r,testName:t}),Zc.log("before this.client.init"),this.client.init())),Zc.log("after client init")}finally{await this.seleniumPerfStats.markEnd(n,Hs.GET_BROWSER)}}get isMobile(){return this.client.isMobile}getSessionId(){var e,t;return(t=(e=this.client)==null?void 0:e.requestHandler)==null?void 0:t.sessionID}isChrome(){return this.client.desiredCapabilities.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.client.desiredCapabilities.browserName==="firefox"}isSafari(){return this.client.desiredCapabilities.browserName==="safari"||this.client.desiredCapabilities.browserName==="safari technology preview"}isAndroid(){return this.client.desiredCapabilities.platformName==="Android"}isEdgeChromium(){return this.client.desiredCapabilities.browserName==="MicrosoftEdge"&&!this.client.desiredCapabilities._isOldEdge}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 r=i=>{throw i.executedScript=t,i},n=()=>this.client.requestHandler.create("/session/:sessionId/execute/sync",{script:t,args:e}).catch(r),o=()=>this.client.requestHandler.create("/session/:sessionId/execute",{script:t,args:e}).catch(r);return this.w3cRequests.execute?n():o().catch(i=>{if(cs(i))return this.w3cRequests.execute=!0,n();throw i})})}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 r=()=>this.client.requestHandler.create("/session/:sessionId/execute/async",{script:t,args:e}),n=()=>this.client.requestHandler.create("/session/:sessionId/execute_async",{script:t,args:e});return this.w3cRequests.executeAsync?r():n().catch(o=>{if(cs(o))return this.w3cRequests.executeAsync=!0,r();throw o})})}async executeCDP(e,t={}){if(!this.isChromium())return;let r=await this.client.requestHandler.create({path:"/session/:sessionId/chromium/send_command_and_get_result",method:"POST"},{cmd:e,params:t});return!r||!r.value||!r.value.targetInfos?[]:r.value.targetInfos}takeScreenshot(){let e=this.seleniumPerfStats.markStart(Hs.GET_SCREENSHOT);return this.addToQueue(()=>this.client.screenshot()).finally(()=>this.seleniumPerfStats.markEnd(e,Hs.GET_SCREENSHOT))}takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Hs.GET_SCREENSHOT);return this.addToQueue(()=>this.client.elementIdScreenshot(Yr(e))).finally(()=>this.seleniumPerfStats.markEnd(t,Hs.GET_SCREENSHOT))}getElementBySelector(e){return this.addToQueue(()=>this.client.element(e))}elementIdDisplayed(e){return this.addToQueue(()=>{let t=()=>this.client.elementIdDisplayed(e),r=()=>this.execute(wC,{ELEMENT:e,[yC]:e});return this.w3cRequests.elementIdDisplayed?r():t().catch(n=>{if(cs(n))return this.w3cRequests.elementIdDisplayed=!0,r();throw n})})}windowHandles(){return this.addToQueue(()=>{let e=()=>this.client.requestHandler.create("/session/:sessionId/window_handles"),t=()=>this.client.requestHandler.create("/session/:sessionId/window/handles");return this.w3cRequests.windowHandles?t():e().catch(r=>{if(cs(r))return this.w3cRequests.windowHandles=!0,t();throw r})})}url(e){return this.addToQueue(()=>this.client.url(bC(e,this.isSafari(),Uo)))}reloadTab(){return this.addToQueue(()=>this.client.refresh())}source(){return this.addToQueue(()=>this.client.source())}timeouts(e,t){return this.addToQueue(()=>{let r=()=>this.client.requestHandler.create("/session/:sessionId/timeouts",{type:e,ms:t}),n=()=>this.client.requestHandler.create("/session/:sessionId/timeouts",{[e]:t});return this.w3cRequests.timeouts?n():r().catch(o=>{if(cs(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 r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}setValue(e,t){return this.elementIdClear(Yr(e)).then(()=>this.elementIdValue(Yr(e),t))}getViewportSize(e){return this.execute(TC).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=>wh.hasOwnProperty(i)?[wh[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(e instanceof Array)for(let i of e)r=r.concat(t(i));else return Promise.reject(new Error("number or type of arguments don't agree with keys protocol command"));let n=()=>this.client.requestHandler.create("/session/:sessionId/keys",{value:r}),o=()=>{let i=r.map(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};return this.w3cRequests.keys?o():this.addToQueue(()=>n().catch(i=>{if(cs(i))return this.w3cRequests.keys=!0,o();throw i}))}elementIdValue(e,t){return this.addToQueue(()=>this.client.elementIdValue(e,t))}elementIdClear(e){return this.addToQueue(()=>this.client.elementIdClear(e))}submitForm(e){return this.addToQueue(()=>this.client.submit(Yr(e)))}buttonPress(e){return this.addToQueue(()=>this.client.buttonPress(e))}findElementAndPress(e,t,r,n){return this.moveTo(Yr(e),t,r).then(()=>this.buttonPress(n))}rightClick(e,t,r){return this.findElementAndPress(e,t,r,"right")}leftClick(e,t,r){return this.findElementAndPress(e,t,r,"left")}elementIdClick(e){return this.addToQueue(()=>this.client.elementIdClick(e))}actions(e){return this.addToQueue(()=>this.client.actions(e))}doDoubleClick(){return this.addToQueue(()=>this.client.doDoubleClick())}dragAndDrop(e,t){return this.addToQueue(()=>this.client.dragAndDrop(e,t))}buttonDown(){return this.addToQueue(()=>this.client.buttonDown())}buttonUp(){return this.addToQueue(()=>this.client.buttonUp())}moveTo(e,t,r){let n={};return typeof t=="number"&&(n.xoffset=t),typeof r=="number"&&(n.yoffset=r),this.isSafari()&&!n.hasOwnProperty("yoffset")&&(n.yoffset=1),this.isSafari()&&!n.hasOwnProperty("xoffset")&&(n.xoffset=1),typeof e=="string"&&(n.element=e),this.addToQueue(()=>this.client.requestHandler.create("/session/:sessionId/moveto",n))}uploadFile(e){return this.addToQueue(()=>this.client.uploadFile(e))}getUrl(){return this.addToQueue(()=>this.client.getUrl())}getTitle(){return this.addToQueue(()=>this.client.getTitle())}windowHandleSize(e="current",t){return this.addToQueue(()=>{let r={};typeof e=="object"&&([e,t]=["current",e]);let n={path:`/session/:sessionId/window/${e}/size`,method:"GET"};if(typeof t=="object"&&t.width&&t.height&&(n.method="POST",r={width:Math.abs(t.width),height:Math.abs(t.height)}),n.method==="POST"&&typeof r.width!="number"&&typeof r.height!="number")return Promise.reject(new Error("number or type of arguments don't agree with windowHandleSize protocol command"));let o=()=>this.client.requestHandler.create(n,r),i=()=>(n.path="/session/:sessionId/window/rect",this.client.requestHandler.create(n,r));return this.w3cRequests.windowHandleSize?i():o().catch(a=>{if(cs(a))return this.w3cRequests.windowHandleSize=!0,i();throw a})})}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>this.client.setCookie({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)}))}getCookie(e){return this.addToQueue(()=>this.client.requestHandler.create("/session/:sessionId/cookie").then(t=>(t.value=t.value||[],typeof e=="string"?t.value.find(r=>r.name===e||r.name===encodeURIComponent(encodeURIComponent(e)))||null:t.value||(typeof e=="string"?null:[]))))}deleteCookie(e){return this.addToQueue(()=>this.client.deleteCookie(e))}isVisibleWithinViewport(e){return this.addToQueue(()=>this.client.isVisibleWithinViewport(e))}getCurrentTabId(){return this.addToQueue(()=>this.client.getCurrentTabId())}frame(e){return this.addToQueue(()=>this.client.frame(e))}switchTab(e){return this.addToQueue(()=>this.client.switchTab(e))}alertAccept(){return this.addToQueue(()=>this.client.alertAccept())}log(e="browser"){return this.addToQueue(()=>this.client.log(e))}end(){return this.w3cRequests={},this.queue?this.addToQueue(()=>this.client.end()):Promise.resolve()}forceEnd(){return this.w3cRequests={},this.client?this.client.end():Promise.resolve()}touchPerform(e){return this.addToQueue(()=>this.client.touchPerform(e))}touchAction(e){return this.addToQueue(()=>this.client.touchAction(e))}pressKeycode(e){return this.addToQueue(()=>this.client.pressKeycode(e))}setImmediateValue(e,t){return this.addToQueue(()=>this.client.setImmediateValue(e,t))}elementIdText(e){return this.addToQueue(()=>this.client.elementIdText(e)).then(t=>t.value)}isAppInstalled(e){return this.addToQueue(()=>this.client.isAppInstalled(e)).then(t=>{let r=!!t.value;return Uo.info(`is app (${e}) installed? ${r}`,t),r})}launch(){return this.addToQueue(()=>this.client.launch())}context(e){return this.addToQueue(()=>this.client.context(e))}elementIdLocation(e){return this.addToQueue(()=>this.client.elementIdLocation(e))}};Th.exports=el});var Sh=C((aD,vh)=>{"use strict";var EC=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(f){function m(I,T,v){return v>I&&v<T}let h=f.pointerPosition||{},g=r.getBoundingClientRect(),w=h.originX&&m(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,b=h.originY&&m(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:w,y:b}},a=function(f,m){return{screenX:0,screenY:0,clientX:f,clientY:m,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(f,m,h){if(!window.PointerEvent)return;let g=a(m,h);return new window.PointerEvent(f,g)},l=function(f,m,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(f,!0,!0,document.defaultView,1,0,0,m,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},u=function(){var m;let f=document.activeElement;for(;(m=f.shadowRoot)!=null&&m.activeElement;)f=f.shadowRoot.activeElement;return f},p=function(f){let m=i(f),h=f.event;return t.includes(h)?c(h,m.x,m.y):l(h,m.x,m.y)};try{n.map(m=>p(m)).filter(Boolean).forEach(m=>r.dispatchEvent(m));let f=u();dispatchFocus(s.elementToFocusLocatedElement,f),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(f){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:f.toString(),success:!1})}};vh.exports=EC});var qo=C((cD,Ih)=>{"use strict";Ih.exports=function(e,t){function r(i){let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}function n(){var a;let i=document.activeElement;for(;(a=i.shadowRoot)!=null&&a.activeElement;)i=i.shadowRoot.activeElement;return i}function o(i,a){a&&(a.dispatchEvent(r("focusout")),a.dispatchEvent(r("blur"))),i.dispatchEvent(r("focusin")),i.dispatchEvent(r("focus")),typeof i.focus=="function"&&i.focus();let c=n();a&&c===a&&typeof a.blur=="function"&&a.blur()}if(e){let i=getLocatedElement(e);if(i&&i!==t)try{o(i,t)}catch{}}else t&&typeof t.blur=="function"&&t.blur()}});var Qr=C((lD,Rh)=>{"use strict";var ls=require("lodash"),_e=(U(),y(H)).getLogger("webdriver"),vC=require("ua-parser-js"),SC=Fo(),{SeleniumError:IC,SeleniumCrashError:xC}=(K(),y(Z)),tl=(M(),y(q)),RC=Eh(),CC=Sh(),PC=qo(),{isOldProtocol:us}=Qc(),{featureFlagsService:kC}=(le(),y(me)),{W3C_ELEMENT_ID:AC}=(Es(),y(Pn)),[Lt,_C]=[0,2],{extractElementId:ct,getCdpAddressForHost:OC}=tl,jo=Ie(),{SeleniumPerfStats:NC,SELENIUM_PERF_MARKS:ds}=Gs(),Dt=()=>(he(),y(Re)).getSessionPlayer().codeSnippets,LC=()=>(he(),y(Re)).getSessionPlayer().locatorBuilderUtils,xh=()=>(he(),y(Re)).getSessionPlayer().utils;async function DC(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await OC(r):void 0}catch(r){_e.info("Error getting cdpAddress",r);return}}var sl=class extends RC{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,r,n,o,i,a,c=new NC,l=!1,u){var h,g,w,b,I;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=(w=(g=(h=e==null?void 0:e.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:w.ignoreHiddenTagsText,this.browserClosedCallbacks=[];let p=SC.buildSeleniumOptions(e,t,r,n,o,i,a,u);p.desiredCapabilities&&delete p.desiredCapabilities.marionette,p.capabilities&&delete p.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(u==null?void 0:u.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=c;let f=l?0:1500,m=l?()=>{}:()=>this.executeJS("window.focus()");try{jo.log("before initClient in webdriver.js init");let T=await this.initClient(p,t,a);jo.log("after initResult before getCdpAddress in init"),this.cdpUrl=await DC(T),jo.log("after getCdpAddress in webdriver.js init"),_e.info(`init new session testName: ${t}`,{sessionId:this.getSessionId(),testResultId:a}),await tl.delay(f),await m(),jo.log("after focus and delay in webdriver.js init")}catch(T){if(_e.error("failed to init webdriver",{err:T}),T.seleniumStack){let v=new IC(T.seleniumStack),x=((I=(b=e==null?void 0:e.company)==null?void 0:b.activePlan)==null?void 0:I.plan)==="free";throw v.message.includes("timed out waiting for a node")&&x?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):v}throw new Error("failed to init client driver")}}initUnsupportedActions(e){e&&(this.unsupportedActions={...this.unsupportedActions,move:!0})}isAlive(){return this._isAlive}maxKeepAliveGap(){let e=n=>ls.zip(ls.dropRight(n,1),ls.drop(n,1)),t=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),r=e(t).map(([n,o])=>o-n);return Math.max(...r)}isClosedBrowserError(e){return!e||!e.seleniumStack||!e.message?!1:e.seleniumStack.type==="UnknownError"&&(e.message.includes("CLIENT_STOPPED_SESSION")||e.message.includes("BROWSER_TIMEOUT")||e.message.includes("was terminated due to TIMEOUT"))||e.seleniumStack.type==="NoSuchWindow"&&e.message.includes("window was already closed")||e.seleniumStack.type==="SelectorTimeoutError"&&e.message.includes("chrome not reachable")}start(){if(this.started)return;this.started=!0;let e=this,t=function(){function r(a){e._keepAliveRequests.push({start:Date.now(),id:a})}function n(a,c){(e._keepAliveRequests.find(l=>l.id===c)||{})[a]=Date.now()}function o(){return window.getTestimStatus&&window.getTestimStatus()}if(e.queue.getQueueLength()>0)return Promise.resolve();let i=tl.guid();return r(i),e.executeJS(o).then(()=>{e._isAlive=!0,n("end",i),e.browserClosedFailedKeepAlives=0}).catch(a=>{if(n("error",i),a.seleniumStack&&a.seleniumStack.type==="UnexpectedAlertOpen")return e.browserClosedFailedKeepAlives=0,_e.warn("close unexpected alert open"),e.alertAccept().catch(c=>_e.warn("failed to click on alert",{err:c}));if(_e.warn("err while getting testim status",{err:a}),e._isAlive=!1,e.isClosedBrowserError(a)){e.browserClosedFailedKeepAlives++;let c=3;e.browserClosedFailedKeepAlives>=c&&e.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else e.browserClosedFailedKeepAlives=0})};this.keepAliveTimer=setInterval(t,1e4)}switchToLocatedFrame(e){return this.getElement(e).then(async t=>{let r=ct(t.value);return await this.switchToFrame({ELEMENT:r,[AC]:r}),t})}switchToFrame(e){return this.frame(e)}switchToTopFrame(){return this.frame().catch(e=>{var t;throw(t=e.message)!=null&&t.includes("ECONNREFUSED")?new xC:e})}getElement(e){let t=this.seleniumPerfStats.markStart(ds.GET_ELEMENT);return typeof e=="string"||typeof e=="number"?this.getElementBySelector(`[testim_dom_element_id='${e}']`).finally(()=>this.seleniumPerfStats.markEnd(t,ds.GET_ELEMENT)):e&&e.shadowPath&&e.shadowPath.length||kC.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari()?this.execute(`
28
28
  var fn = ${Dt().getLocatedElementCode};
29
29
  return fn.apply(null, arguments);
30
30
  `,e).finally(()=>this.seleniumPerfStats.markEnd(t,ds.GET_ELEMENT)):this.getElementBySelector(`[testim_dom_element_id='${e&&e.testimId}']`).finally(()=>this.seleniumPerfStats.markEnd(t,ds.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,r){return this.timeouts("script",t).then(()=>this.executeAsync(e,r))}async markDynamicParent(e,t,r){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 = ${Dt().getLocatedElementCode};
32
32
  var setDynamicParentAttribute = ${n.toString()};
33
33
  return setDynamicParentAttribute.apply(null, arguments)
34
- `,{attributeName:OC().DYNAMIC_PARENT_FIELD_NAME,attributeValue:t,locatedElement:e.locatedElement})}getLocatedElementRectWithPadding(e){function t(r){var n=getLocatedElement(r);if(!n)return null;var o=parseInt(window.getComputedStyle(n).paddingTop.replace("px",""),10)||0,i=parseInt(window.getComputedStyle(n).paddingLeft.replace("px",""),10)||0,a=n.getBoundingClientRect();return{top:Math.round(a.top+o),left:Math.round(a.left+i)}}return this.executeJS(`
34
+ `,{attributeName:LC().DYNAMIC_PARENT_FIELD_NAME,attributeValue:t,locatedElement:e.locatedElement})}getLocatedElementRectWithPadding(e){function t(r){var n=getLocatedElement(r);if(!n)return null;var o=parseInt(window.getComputedStyle(n).paddingTop.replace("px",""),10)||0,i=parseInt(window.getComputedStyle(n).paddingLeft.replace("px",""),10)||0,a=n.getBoundingClientRect();return{top:Math.round(a.top+o),left:Math.round(a.left+i)}}return this.executeJS(`
35
35
  var getLocatedElement = ${Dt().getLocatedElementCode};
36
36
  var getLocation = ${t.toString()};
37
37
  return getLocation.apply(null, arguments)
@@ -43,19 +43,19 @@ ${((I=n.warnings)==null?void 0:I.join(`
43
43
  var getLocatedElement = ${Dt().getLocatedElementCode};
44
44
  var extractText = ${t.toString()};
45
45
  return extractText.apply(null, arguments)
46
- `,e,this.ignoreHiddenTagsText).then(r=>r.value)}getHTML(e){let t=Dt().getHtmlCode(null,e),r=this.seleniumPerfStats.markStart(ds.GET_HTML);return this.executeJS(t).then(n=>(this.seleniumPerfStats.markEnd(r,ds.GET_HTML),n.value)).catch(n=>{this.seleniumPerfStats.markEnd(r,ds.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(l=>this.execute(n).then(u=>{let p=l.value.width-u.value.screenWidth,f=l.value.height-u.value.screenHeight;return this.windowHandleSize({width:a.width+p,height:a.height+f})}).then(()=>this.execute(n)).then(u=>{if(c<5&&(u.value.screenWidth!==a.width||u.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 r=!0;return this.setViewportSizeNEW({width:e,height:t},r)}getBrowserMajorVersion(e){try{return parseInt(e.browser.major,10)}catch(t){return _e.error("failed to get browser version",{err:t}),0}}getBrowserAndOS(){function e(t,r){var n=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(n[1]))return"Internet Explorer "+r.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 r=t.value,n=TC(r),o=n.os;return this.browserAndOS={os:o.name+" "+o.version,browserMajor:this.getBrowserMajorVersion(n),browser:e(t.value,n.browser),userAgent:r,browserVersion:n.browser.version},this.browserAndOS})}getUserAgentInfo(){return this.executeJS(`return ${Dt().getUserAgentInfo()}`).then(e=>e.value)}setValue(e,t){return super.setValue(e,t)}getRelativeMoveActions(e,t){let{rect:r,clickOffset:n}=e,o=this.inViewCenter(r),i=Math.floor(n.x-o.x),a=Math.floor(n.y-o.y);return!Ih().isWithinBounds(-o.x,o.x,i)||!Ih().isWithinBounds(-o.y,o.y,a)?(_e.warn("using center as fallback for offset"),this.getMoveActions(0,0,t)):this.getMoveActions(i,a,t)}computeAbsoluteMovement(e){let{frameOffset:t,rect:r,clickOffset:n}=e,o=r.left+n.x+t.x,i=r.top+n.y+t.y;return{x:o,y:i}}actWithActionsAPI(e,t,r,n){let o=this.getRelativeMoveActions(e,r),i=this.getClickActions(n,t);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(i)}]).catch(a=>{_e.error("tried to use element origin but failed because of visibility, trying absolute",a);let{x:c,y:l}=this.computeAbsoluteMovement(e),u=this.getMoveActions(c,l);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:u.concat(i)}])})}doubleClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,Nt,e,["pointerDown","pointerUp","pointerDown","pointerUp"])}doubleClickWithJS(e){return this.executeCodeAsync(`
46
+ `,e,this.ignoreHiddenTagsText).then(r=>r.value)}getHTML(e){let t=Dt().getHtmlCode(null,e),r=this.seleniumPerfStats.markStart(ds.GET_HTML);return this.executeJS(t).then(n=>(this.seleniumPerfStats.markEnd(r,ds.GET_HTML),n.value)).catch(n=>{this.seleniumPerfStats.markEnd(r,ds.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(l=>this.execute(n).then(u=>{let p=l.value.width-u.value.screenWidth,f=l.value.height-u.value.screenHeight;return this.windowHandleSize({width:a.width+p,height:a.height+f})}).then(()=>this.execute(n)).then(u=>{if(c<5&&(u.value.screenWidth!==a.width||u.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 r=!0;return this.setViewportSizeNEW({width:e,height:t},r)}getBrowserMajorVersion(e){try{return parseInt(e.browser.major,10)}catch(t){return _e.error("failed to get browser version",{err:t}),0}}getBrowserAndOS(){function e(t,r){var n=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(n[1]))return"Internet Explorer "+r.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 r=t.value,n=vC(r),o=n.os;return this.browserAndOS={os:o.name+" "+o.version,browserMajor:this.getBrowserMajorVersion(n),browser:e(t.value,n.browser),userAgent:r,browserVersion:n.browser.version},this.browserAndOS})}getUserAgentInfo(){return this.executeJS(`return ${Dt().getUserAgentInfo()}`).then(e=>e.value)}setValue(e,t){return super.setValue(e,t)}getRelativeMoveActions(e,t){let{rect:r,clickOffset:n}=e,o=this.inViewCenter(r),i=Math.floor(n.x-o.x),a=Math.floor(n.y-o.y);return!xh().isWithinBounds(-o.x,o.x,i)||!xh().isWithinBounds(-o.y,o.y,a)?(_e.warn("using center as fallback for offset"),this.getMoveActions(0,0,t)):this.getMoveActions(i,a,t)}computeAbsoluteMovement(e){let{frameOffset:t,rect:r,clickOffset:n}=e,o=r.left+n.x+t.x,i=r.top+n.y+t.y;return{x:o,y:i}}actWithActionsAPI(e,t,r,n){let o=this.getRelativeMoveActions(e,r),i=this.getClickActions(n,t);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:o.concat(i)}]).catch(a=>{_e.error("tried to use element origin but failed because of visibility, trying absolute",a);let{x:c,y:l}=this.computeAbsoluteMovement(e),u=this.getMoveActions(c,l);return this.actions([{type:"pointer",id:"mouse",parameters:{pointerType:"mouse"},actions:u.concat(i)}])})}doubleClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,Lt,e,["pointerDown","pointerUp","pointerDown","pointerUp"])}doubleClickWithJS(e){return this.executeCodeAsync(`
47
47
  var getLocatedElement = ${Dt().getLocatedElementCode};
48
- var dispatchFocus = ${RC.toString()};
49
- var doubleClick = ${xC.toString()};
48
+ var dispatchFocus = ${PC.toString()};
49
+ var doubleClick = ${CC.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(r=>({type:r,button:t}))}getClickActionList(e=[],t){return[{type:"pointer",id:"mouse",actions:this.getClickActions(e,t)}]}leftClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,Nt,e,["pointerDown","pointerUp"])}rightClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,kC,e,["pointerDown","pointerUp"])}rightClick(e,t){return this.unsupportedActions.move?this.rightClickWithActionsAPI(e,t):super.rightClick(e).catch(r=>{if(us(r))return this.unsupportedActions.move=!0,this.rightClickWithActionsAPI(e,t);throw r})}leftClick(e,t){return this.unsupportedActions.move?this.leftClickWithActionsAPI(e,t):super.leftClick(e).catch(r=>{if(us(r))return this.unsupportedActions.move=!0,this.leftClickWithActionsAPI(e,t);throw r})}dragAndDropOldAPI(e,t){return this.moveTo(ct(e)).then(()=>this.buttonDown()).then(()=>this.moveTo(ct(t))).then(()=>this.buttonUp())}calculateElementMiddlePoint(e,t={top:0,left:0}){return this.getLocatedElementRect(e).then(r=>{if(!r||!r.value)throw _e.warn(`could not find element for locatedElement ${e}`),new Error("could not calculate rect");let{x:n,y:o,width:i,height:a}=r.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{rect:r,clickOffset:n}=t,o=this.inViewCenter(r),i=Math.floor(n.x-o.x),a=Math.floor(n.y-o.y);return this.moveTo(ct(e),i,a).catch(c=>{if(us(c))return this.unsupportedActions.move=!0,this.moveToElementWithActionsAPI(e,t);throw c})}getMoveActions(e=1,t=1,r="viewport",n=0){return[{type:"pointerMove",duration:n,x:Math.floor(e)||1,y:Math.floor(t)||1,origin:r}]}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(r=>{_e.error("tried to use element origin but failed because of visibility, trying location",r);let n=this.computeAbsoluteMovement(t);return this.moveWithActionsAPI(n)})}getDragCoordinates(e){let t=e.filter(o=>o.event==="mousemove"||o.event==="pointermove"),r=ls.first(t).pointerPosition,n=ls.last(t).pointerPosition;return{xDiff:n.screenX-r.screenX,yDiff:n.screenY-r.screenY}}dragWithMoveTo(e,t,r,n,o){return this.moveTo(ct(e),n,o).then(()=>this.buttonDown()).then(()=>this.moveTo(ct(e),t,r)).then(()=>this.buttonUp())}dragWithActionsAPI(e,t,r,n,o){let i=this.getMoveActions(n,o,e,1),a=this.getClickActions(["pointerDown"],Nt),c=this.getMoveActions(t,r,"pointer",1),l=this.getClickActions(["pointerUp"],Nt);return this.actions([{type:"pointer",id:"mouse",actions:i.concat(a).concat(c).concat(l)}])}drag(e,t,r,n,o){let{width:i,height:a}=t,c=r-i/2+1,l=n-a/2;return this.getDragCoordinates(o).then(u=>{let{xDiff:p,yDiff:f}=u;return this.unsupportedActions.move?this.dragWithActionsAPI(e,p,f,c,l):this.dragWithMoveTo(e,p,f,c,l).catch(m=>{if(us(m))return this.unsupportedActions.move=!0,this.dragWithActionsAPI(e,p,f,c,l);throw m})})}getMoveRelativeSequence(e,t,r,n){let o=f=>f*f,i=(f,m)=>Math.sqrt(o(f.x-m.x)+o(f.y-m.y)),a={x:e,y:t},c={x:r,y:n},l=10,u=Math.round(i(a,c)/l),p=Array.apply([],new Array(u)).map(()=>({x:Math.round((c.x-a.x)/u),y:Math.round((c.y-a.y)/u)}));return[{x:1,y:1}].concat(p)}getMoveAbsoluteSequence(e,t,r,n){return this.getMoveRelativeSequence(e,t,r,n).reduce((i,a)=>{let c=ls.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,r){let{fromRect:n,fromX:o,fromY:i,toRect:a,toX:c,toY:l}=r,u=this.getMoveRelativeSequence(n.left+o,n.top+i,a.left+c,a.top+l);await this.moveTo(ct(e),Math.round(o),Math.round(i)),await this.buttonDown();for(let p of u)await this.moveTo(null,p.x,p.y);return await this.moveTo(ct(t),Math.round(c),Math.round(l)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(e){let{fromRect:t,fromX:r,fromY:n,toRect:o,toX:i,toY:a}=e,c=Math.round(t.left+r),l=Math.round(t.top+n),u=Math.round(o.left+i),p=Math.round(o.top+a),f=this.getMoveAbsoluteSequence(t.left+r,t.top+n,o.left+i,o.top+a),m=this.getMoveActions(c,l),h=this.getClickActions(["pointerDown"],Nt),g=ls.flatMap(f,T=>this.getMoveActions(T.x,T.y)),y=this.getMoveActions(u,p),b=this.getClickActions(["pointerUp"],Nt),I=m.concat(h).concat(g).concat(y).concat(b);return this.actions([{type:"pointer",id:"mouse",actions:I}])}dragAndDrop(e,t,r){return this.isSafari()?this.unsupportedActions.move?this.dragAndDropWithActionsAPIWithGeneratedMoves(r):this.dragAndDropWithGeneratedMoves(e,t,r).catch(n=>{if(us(n))return this.unsupportedActions.move=!0,this.dragAndDropWithActionsAPIWithGeneratedMoves(r);throw n}):this.unsupportedActions.move?this.dragAndDropWithActionsAPI(r):this.dragAndDropOldAPI(e,t).catch(n=>{if(us(n))return this.unsupportedActions.move=!0,this.dragAndDropWithActionsAPI(r);throw n})}doubleClickFallback(e,t,r){return this.isSafari()?this.doubleClickWithJS(t):this.doubleClickWithActionsAPI(e,r)}doubleClick(e,t,r){return this.unsupportedActions.move||this.isSafari()?this.doubleClickFallback(e,t,r):this.moveTo(ct(e)).then(()=>this.doDoubleClick()).catch(n=>{if(us(n))return this.unsupportedActions.move=!0,this.doubleClickFallback(e,t,r);throw n})}dragAndDropWithActionsAPI(e){let{fromRect:t,fromX:r,fromY:n,toRect:o,toX:i,toY:a}=e,c=Math.round(t.left+r),l=Math.round(t.top+n),u=Math.round(o.left+i),p=Math.round(o.top+a);return this.moveWithActionsAPI({x:c,y:l}).then(()=>{let f=this.getClickActionList(["pointerDown"],Nt);return this.actions(f)}).then(()=>this.moveWithActionsAPI({x:u,y:p})).then(()=>{let f=this.getClickActionList(["pointerUp"],Nt);return this.actions(f)})}getTabIds(){return this.windowHandles().then(e=>e.value)}isVisible(e){return this.elementIdDisplayed(ct(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(r=>_e.error("error getting element location",{err:r})).then(r=>r!=null&&r.value?{top:r.value.y,left:r.value.x,width:r.value.width,height:r.value.height}:t)}end(){return _e.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||_e.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}}};xh.exports=tl});var fs=C((lD,_h)=>{"use strict";var NC=require("fs"),DC=require("os"),$o=require("path"),MC=require("fs-extra"),Ch=require("data-uri-to-buffer"),ms=(M(),w(q)),Rh=kr(),{featureFlagsService:FC}=(le(),w(me)),{spawn:UC,config:qC}=require("threads"),{TimeoutError:jC}=(K(),w(Z)),{getLogger:$C}=(U(),w(H)),{getS3Artifact:BC}=pe(),Pe=$C("cli-service"),ps;qC.set({basepath:{node:__dirname}});function Ph(s){let e=/^\\\\\?\\/.test(s),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function WC(s,e,t,r,n={},o=void 0,i=void 0){let a=Object.keys(n).reduce((g,y)=>(g+=`
54
- var ${y} = require('${Ph(n[y])}');
53
+ `,e.timeout,e)}getClickActions(e=[],t){return e.map(r=>({type:r,button:t}))}getClickActionList(e=[],t){return[{type:"pointer",id:"mouse",actions:this.getClickActions(e,t)}]}leftClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,Lt,e,["pointerDown","pointerUp"])}rightClickWithActionsAPI(e,t){return this.actWithActionsAPI(t,_C,e,["pointerDown","pointerUp"])}rightClick(e,t){return this.unsupportedActions.move?this.rightClickWithActionsAPI(e,t):super.rightClick(e).catch(r=>{if(us(r))return this.unsupportedActions.move=!0,this.rightClickWithActionsAPI(e,t);throw r})}leftClick(e,t){return this.unsupportedActions.move?this.leftClickWithActionsAPI(e,t):super.leftClick(e).catch(r=>{if(us(r))return this.unsupportedActions.move=!0,this.leftClickWithActionsAPI(e,t);throw r})}dragAndDropOldAPI(e,t){return this.moveTo(ct(e)).then(()=>this.buttonDown()).then(()=>this.moveTo(ct(t))).then(()=>this.buttonUp())}calculateElementMiddlePoint(e,t={top:0,left:0}){return this.getLocatedElementRect(e).then(r=>{if(!r||!r.value)throw _e.warn(`could not find element for locatedElement ${e}`),new Error("could not calculate rect");let{x:n,y:o,width:i,height:a}=r.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{rect:r,clickOffset:n}=t,o=this.inViewCenter(r),i=Math.floor(n.x-o.x),a=Math.floor(n.y-o.y);return this.moveTo(ct(e),i,a).catch(c=>{if(us(c))return this.unsupportedActions.move=!0,this.moveToElementWithActionsAPI(e,t);throw c})}getMoveActions(e=1,t=1,r="viewport",n=0){return[{type:"pointerMove",duration:n,x:Math.floor(e)||1,y:Math.floor(t)||1,origin:r}]}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(r=>{_e.error("tried to use element origin but failed because of visibility, trying location",r);let n=this.computeAbsoluteMovement(t);return this.moveWithActionsAPI(n)})}getDragCoordinates(e){let t=e.filter(o=>o.event==="mousemove"||o.event==="pointermove"),r=ls.first(t).pointerPosition,n=ls.last(t).pointerPosition;return{xDiff:n.screenX-r.screenX,yDiff:n.screenY-r.screenY}}dragWithMoveTo(e,t,r,n,o){return this.moveTo(ct(e),n,o).then(()=>this.buttonDown()).then(()=>this.moveTo(ct(e),t,r)).then(()=>this.buttonUp())}dragWithActionsAPI(e,t,r,n,o){let i=this.getMoveActions(n,o,e,1),a=this.getClickActions(["pointerDown"],Lt),c=this.getMoveActions(t,r,"pointer",1),l=this.getClickActions(["pointerUp"],Lt);return this.actions([{type:"pointer",id:"mouse",actions:i.concat(a).concat(c).concat(l)}])}drag(e,t,r,n,o){let{width:i,height:a}=t,c=r-i/2+1,l=n-a/2;return this.getDragCoordinates(o).then(u=>{let{xDiff:p,yDiff:f}=u;return this.unsupportedActions.move?this.dragWithActionsAPI(e,p,f,c,l):this.dragWithMoveTo(e,p,f,c,l).catch(m=>{if(us(m))return this.unsupportedActions.move=!0,this.dragWithActionsAPI(e,p,f,c,l);throw m})})}getMoveRelativeSequence(e,t,r,n){let o=f=>f*f,i=(f,m)=>Math.sqrt(o(f.x-m.x)+o(f.y-m.y)),a={x:e,y:t},c={x:r,y:n},l=10,u=Math.round(i(a,c)/l),p=Array.apply([],new Array(u)).map(()=>({x:Math.round((c.x-a.x)/u),y:Math.round((c.y-a.y)/u)}));return[{x:1,y:1}].concat(p)}getMoveAbsoluteSequence(e,t,r,n){return this.getMoveRelativeSequence(e,t,r,n).reduce((i,a)=>{let c=ls.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,r){let{fromRect:n,fromX:o,fromY:i,toRect:a,toX:c,toY:l}=r,u=this.getMoveRelativeSequence(n.left+o,n.top+i,a.left+c,a.top+l);await this.moveTo(ct(e),Math.round(o),Math.round(i)),await this.buttonDown();for(let p of u)await this.moveTo(null,p.x,p.y);return await this.moveTo(ct(t),Math.round(c),Math.round(l)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(e){let{fromRect:t,fromX:r,fromY:n,toRect:o,toX:i,toY:a}=e,c=Math.round(t.left+r),l=Math.round(t.top+n),u=Math.round(o.left+i),p=Math.round(o.top+a),f=this.getMoveAbsoluteSequence(t.left+r,t.top+n,o.left+i,o.top+a),m=this.getMoveActions(c,l),h=this.getClickActions(["pointerDown"],Lt),g=ls.flatMap(f,T=>this.getMoveActions(T.x,T.y)),w=this.getMoveActions(u,p),b=this.getClickActions(["pointerUp"],Lt),I=m.concat(h).concat(g).concat(w).concat(b);return this.actions([{type:"pointer",id:"mouse",actions:I}])}dragAndDrop(e,t,r){return this.isSafari()?this.unsupportedActions.move?this.dragAndDropWithActionsAPIWithGeneratedMoves(r):this.dragAndDropWithGeneratedMoves(e,t,r).catch(n=>{if(us(n))return this.unsupportedActions.move=!0,this.dragAndDropWithActionsAPIWithGeneratedMoves(r);throw n}):this.unsupportedActions.move?this.dragAndDropWithActionsAPI(r):this.dragAndDropOldAPI(e,t).catch(n=>{if(us(n))return this.unsupportedActions.move=!0,this.dragAndDropWithActionsAPI(r);throw n})}doubleClickFallback(e,t,r){return this.isSafari()?this.doubleClickWithJS(t):this.doubleClickWithActionsAPI(e,r)}doubleClick(e,t,r){return this.unsupportedActions.move||this.isSafari()?this.doubleClickFallback(e,t,r):this.moveTo(ct(e)).then(()=>this.doDoubleClick()).catch(n=>{if(us(n))return this.unsupportedActions.move=!0,this.doubleClickFallback(e,t,r);throw n})}dragAndDropWithActionsAPI(e){let{fromRect:t,fromX:r,fromY:n,toRect:o,toX:i,toY:a}=e,c=Math.round(t.left+r),l=Math.round(t.top+n),u=Math.round(o.left+i),p=Math.round(o.top+a);return this.moveWithActionsAPI({x:c,y:l}).then(()=>{let f=this.getClickActionList(["pointerDown"],Lt);return this.actions(f)}).then(()=>this.moveWithActionsAPI({x:u,y:p})).then(()=>{let f=this.getClickActionList(["pointerUp"],Lt);return this.actions(f)})}getTabIds(){return this.windowHandles().then(e=>e.value)}isVisible(e){return this.elementIdDisplayed(ct(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(r=>_e.error("error getting element location",{err:r})).then(r=>r!=null&&r.value?{top:r.value.y,left:r.value.x,width:r.value.width,height:r.value.height}:t)}end(){return _e.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||_e.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}}};Rh.exports=sl});var fs=C((uD,Oh)=>{"use strict";var MC=require("fs"),FC=require("os"),$o=require("path"),UC=require("fs-extra"),Ph=require("data-uri-to-buffer"),ms=(M(),y(q)),Ch=Ar(),{featureFlagsService:qC}=(le(),y(me)),{spawn:jC,config:$C}=require("threads"),{TimeoutError:BC}=(K(),y(Z)),{getLogger:WC}=(U(),y(H)),{getS3Artifact:GC}=pe(),Pe=WC("cli-service"),ps;$C.set({basepath:{node:__dirname}});function kh(s){let e=/^\\\\\?\\/.test(s),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function VC(s,e,t,r,n={},o=void 0,i=void 0){let a=Object.keys(n).reduce((g,w)=>(g+=`
54
+ var ${w} = require('${kh(n[w])}');
55
55
  `,g),""),c=i?`
56
- ${Ch.toString()}
56
+ ${Ph.toString()}
57
57
  var fileBuffer = dataUriToBuffer('${i}');
58
- `:"var fileBuffer = null;";function l(g,y){function b(){return g.apply(this,y)}return b.prototype=g.prototype,new b}let u=`
58
+ `:"var fileBuffer = null;";function l(g,w){function b(){return g.apply(this,w)}return b.prototype=g.prototype,new b}let u=`
59
59
 
60
60
  const getMessage = arguments => {
61
61
  const args = Array.prototype.slice.call(arguments);
@@ -197,17 +197,17 @@ ${((I=n.warnings)==null?void 0:I.join(`
197
197
  ${p}
198
198
 
199
199
  injectCode(params, args, incomingParams, context, code, done);
200
- `,m=[],h=UC(l(Function,["input","done","progress",f]));return ms.promiseTimeout(new Promise(g=>{h.send({incomingParams:e,context:t,code:r}).on("message",y=>{let b=Object.assign({},y,{tstConsoleLogs:m});Pe.debug("Run code worker response",{messageWithLogs:b,transactionId:s}),g(b)}).on("progress",y=>{m.push(y)}).on("error",y=>{y.message==="malformed data: URI"?Pe.error("Run code worker error",{err:y,transactionId:s,fileDataUrl:i}):Pe.error("Run code worker error",{err:y,transactionId:s}),g({tstConsoleLogs:m,status:"failed",result:{resultValue:y==null?void 0:y.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{Pe.debug("Run code worker has been terminated",{transactionId:s})})}),o).catch(g=>{if(!(g instanceof ms.TimeoutError))throw g;return Pe.warn("timeout to run code",{transactionId:s,err:g}),{tstConsoleLogs:m,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}).finally(()=>h==null?void 0:h.kill())}function GC(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code==="ERR_REQUIRE_ESM"){let t=globalThis.require("path");return{sync:!1,lib:NC.promises.readFile(`${$o}${t.sep}package.json`).then(n=>{let o=JSON.parse(n);return import(t.join(s,o.main||`${t.sep}index.js`))})}}throw e}}function VC(s,e,t,r,n={},o=void 0,i=void 0){ps||(ps=require("worker_threads"));let{Worker:a}=ps,c=Object.keys(n).reduce((y,b)=>(y+=`
201
- var res = requireOrImportMethod('${Ph(n[b])}');
200
+ `,m=[],h=jC(l(Function,["input","done","progress",f]));return ms.promiseTimeout(new Promise(g=>{h.send({incomingParams:e,context:t,code:r}).on("message",w=>{let b=Object.assign({},w,{tstConsoleLogs:m});Pe.debug("Run code worker response",{messageWithLogs:b,transactionId:s}),g(b)}).on("progress",w=>{m.push(w)}).on("error",w=>{w.message==="malformed data: URI"?Pe.error("Run code worker error",{err:w,transactionId:s,fileDataUrl:i}):Pe.error("Run code worker error",{err:w,transactionId:s}),g({tstConsoleLogs:m,status:"failed",result:{resultValue:w==null?void 0:w.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{Pe.debug("Run code worker has been terminated",{transactionId:s})})}),o).catch(g=>{if(!(g instanceof ms.TimeoutError))throw g;return Pe.warn("timeout to run code",{transactionId:s,err:g}),{tstConsoleLogs:m,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}).finally(()=>h==null?void 0:h.kill())}function HC(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code==="ERR_REQUIRE_ESM"){let t=globalThis.require("path");return{sync:!1,lib:MC.promises.readFile(`${$o}${t.sep}package.json`).then(n=>{let o=JSON.parse(n);return import(t.join(s,o.main||`${t.sep}index.js`))})}}throw e}}function KC(s,e,t,r,n={},o=void 0,i=void 0){ps||(ps=require("worker_threads"));let{Worker:a}=ps,c=Object.keys(n).reduce((w,b)=>(w+=`
201
+ var res = requireOrImportMethod('${kh(n[b])}');
202
202
  if (res.sync) {
203
203
  var ${b} = res.lib;
204
204
  } else {
205
205
  var ${b} = await res.lib;
206
206
  }
207
- `,y),""),l=i?`
208
- ${Ch.toString()}
207
+ `,w),""),l=i?`
208
+ ${Ph.toString()}
209
209
  var fileBuffer = dataUriToBuffer('${i}');
210
- `:"var fileBuffer = null;";function u(y,b){function I(){return y.apply(this,b)}return I.prototype=y.prototype,new I}let p=`
210
+ `:"var fileBuffer = null;";function u(w,b){function I(){return w.apply(this,b)}return I.prototype=w.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() + '';
@@ -328,7 +328,7 @@ ${((I=n.warnings)==null?void 0:I.join(`
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;
330
330
  const { parentPort } = require('worker_threads');
331
- var requireOrImportMethod = ${GC}
331
+ var requireOrImportMethod = ${HC}
332
332
 
333
333
  // requireCode will set async to be true if needed.
334
334
  ${c}
@@ -366,72 +366,72 @@ ${((I=n.warnings)==null?void 0:I.join(`
366
366
  injectCode(params, args, incomingParams, context, code);
367
367
  });
368
368
  })();
369
- `,h=[],g=new a(m,{eval:!0});return ms.promiseTimeout(new Promise(y=>{g.on("message",b=>{if(b.action==="finish"){let{data:I}=b,T=Object.assign({},I,{tstConsoleLogs:h});Pe.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),y(T)}else b.action==="progress"&&h.push(b.data)}).on("error",b=>{b.message==="malformed data: URI"?Pe.error("Run code worker error",{err:b,transactionId:s,fileDataUrl:i}):Pe.error("Run code worker error",{err:b,transactionId:s}),y({tstConsoleLogs:h,status:"failed",result:{resultValue:b==null?void 0:b.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{Pe.debug("Run code worker has been terminated",{transactionId:s})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o).catch(y=>{if(!(y instanceof ms.TimeoutError))throw y;return Pe.warn("timeout to run code",{transactionId:s,err:y}),{tstConsoleLogs:h,status:"failed",result:{resultValue:y==null?void 0:y.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}).finally(()=>g==null?void 0:g.terminate())}async function HC(s){try{await MC.remove(s)}catch(e){Pe.warn("failed to remove install npm packages folder",{err:e})}}function kh(s,e,t,r){return`${e}_${t}_${s}_${r}`}function KC(s,e,t,r,n,o){let i=kh(n,e,s,t);return JC(i,r,o).then(({data:a})=>a)}function zC(s,e,t,r,n,o,i,a,c,l){let u=(t.nodePackageParams||[]).reduce((m,h)=>(m[h.paramName]=h.testimPackageLocalLocation,m),{}),p=kh(i,n,e,o);return(l?BC(l):Promise.resolve()).then(m=>{m&&(c=m)}).then(()=>{if(typeof ps>"u")try{ps=require("worker_threads")}catch{ps=!1}Buffer.isBuffer(c)&&(Pe.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let m="data:,";return c==="data:"&&(Pe.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=m),ps&&FC.flags.enableWorkerThreadsCliCodeExecution.isEnabled()?VC(p,t,r,s,u,a,c):WC(p,t,r,s,u,a,c)}).then(m=>Object.assign({},m,{nodeVersion:process.version}))}async function JC(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Ah(),o=$o.join(n,`/${s}`),i=global.proxyUri;async function a(){let c="";try{if(c=await Rh.installPackages(o,r,i,t),Pe.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(u=>{let p=Rh.getLocallyInstalledPackageVersion(o,u.packageName),f=`${u.packageName}@${p}`,m=$o.resolve(o,"node_modules",u.packageName);return Object.assign({},u,{packageFullName:f,packageLocalLocation:m})}),installFolder:o}}catch(l){throw Pe.warn("npm package install failed",{transactionId:s,err:l}),l}}try{return await ms.promiseTimeout(a(),t)}catch(c){throw c instanceof jC&&Pe.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Ah(){return $o.join(DC.tmpdir(),"/testim_local_packages")}function XC(){let s=Ah();return HC(s)}_h.exports={runCodeWithPackages:zC,installPackage:KC,cleanLocalPackageInstallFolder:XC}});var Lh=C((uD,Oh)=>{"use strict";var YC=fs(),{TimeoutError:QC}=(K(),w(Z)),{featureFlagsService:ZC}=(le(),w(me));function eP(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=ZC.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}Oh.exports.run=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:u,fileDataUrl:p,s3filepath:f}=e.data;try{let m=await YC.runCodeWithPackages(r,n,o,i,a,c,l,u,p,f);return m&&eP({result:m.result,tstConsoleLogs:m.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:m,success:!0}}catch(m){throw m instanceof QC?new Error("Timeout while running action"):m}}});var rl=C((dD,Nh)=>{"use strict";var sl=(U(),w(H)).getLogger("cookies-utils");Nh.exports=function(s){class e{set(r){let n=r.domain;return r.hostOnly||n&&!n.startsWith(".")&&(n=`.${n}`),s.setCookie(r.name,r.value,n,r.httpOnly,r.secure,r.path,r.expirationDate).catch(o=>{throw sl.error("failed to set cookie",{err:o}),o})}get(r){return s.getCookie(r.name).catch(n=>{throw sl.error("failed to get cookie",{err:n}),n})}remove(r){return s.deleteCookie(r.name).catch(n=>{throw sl.error("failed to remove cookie",{err:n}),n})}}return new e}});var il=C((pD,Mh)=>{"use strict";var Dh=require("p-retry"),{delay:nl}=(M(),w(q)),{PageNotAvailableError:tP}=(K(),w(Z)),sP=(M(),w(q)),rP=(U(),w(H)).getLogger("window-utils"),ol=class{constructor(e,t){this.id=e,this.driver=t}getElementFromPoint(e,t){function r(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(r,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(r){var n="scrollBehavior"in document.documentElement.style;return n?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.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 r=this;async function n(o=3){try{await r.driver.url(e)}catch(i){if(i.seleniumStack&&i.message.includes("method IWebBrowser2::Navigate2() failed")&&o>0)return rP.warn("selenium navigation failed. retrying to navigate",{err:i}),await nl(1500),n(o-1);throw i}}return Promise.race([n(),nl(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),nl(e)])}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}getFullPageSize(){function e(){var t=document.body,r=document.documentElement,n=Math.max(t.scrollHeight,t.offsetHeight,r.clientHeight,r.scrollHeight,r.offsetHeight),o=Math.max(t.scrollWidth,t.offsetWidth,r.clientWidth,r.scrollWidth,r.offsetWidth);return{height:n,width:o}}return this.driver.executeJS(e).then(t=>t.value)}extractToNewWindow(){return Promise.resolve()}async checkSize(e){await sP.delay(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 r;if(typeof location<"u")r=location;else if(typeof window<"u"&&typeof window.location<"u")r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new tP("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await Dh(()=>this.driver.getBrowserAndOS(),{retries:3});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return Dh(()=>this.driver.getUserAgentInfo(),{retries:3})}};Mh.exports=ol});var Uh=C((mD,Fh)=>{"use strict";var nP=require("p-retry"),al=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e,this.driver=t,this.options=r}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await nP(n,{retries:e,minTimeout:t}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}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}};Fh.exports=al});var Bh=C((fD,$h)=>{"use strict";var oP=require("lodash"),Yr=require("jimp"),iP=(M(),w(q)),aP=(U(),w(H)).getLogger("image-capture-utils"),Qr=class extends Error{constructor(e){super(e),this.rectIsOutsideOfImageError=!0,Object.setPrototypeOf(this,Qr.prototype)}};async function qh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data\:[^;]*\;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return aP.warn("missing elementRect",oP.omit(s,"image")),{};let{elementRect:i}=s,a=await Yr.read(Buffer.from(n[1],"base64")),c=i.left*r+o.left*r,l=i.top*r+o.top*r,u=i.width*r,p=i.height*r;c<0&&(u+=c,u=u<0?0:u,c=0),l<0&&(p+=l,p=p<0?0:p,l=0);let f=a.bitmap.width,m=a.bitmap.height;if(c+u>f&&(u=f-c),l+p>m&&(p=m-l),p<=0||u<=0)throw new Qr("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,u,p).getBase64Async(Yr.MIME_PNG)}}async function cP(s,e){let t=await Yr.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data\:[^;]*\;base64,(.*)$/),i=await Yr.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,l=>{if(l){c(l);return}a()})})}return await t.getBase64Async(Yr.MIME_PNG)}function lP(s,e){return cP(s,e)}function uP(){return Promise.resolve()}function dP(s){function e(r){return typeof s[r]=="string"&&s[r].startsWith("data")}function t(r){return uP(s[r]).then(n=>({key:r,url:n}))}return Promise.all(Object.keys(s).filter(e).map(t)).then(r=>r.reduce((n,o)=>(n[o.key]=o.url,n),s))}function jh(s,e){return e=e||1,s=s||{left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var cl=class{constructor(e,t,r){this.windowUtils=t,this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e,t){e.areas&&(e=e.areas);let r=await this.screenshotUtils.takeScreenshot(t),n=await qh(e,r);return n.screenImage=r.image,n.absoluteScreenHighlight=jh(e.elementRect,r.devicePixelRatio),n}async takeArea(e){e.areas&&(e=e.areas);let t=await this.screenshotUtils.takeScreenshot();return dP({screenImage:t.image,absoluteScreenHighlight:jh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>iP.delay(250),o=Boolean(e);async function i(f,m){o?await t.scrollToPositionWithoutAnimation(f):await t.scrollToPosition(f),await n();let h=await r.takeScreenshot(),g=await qh({elementRect:m},h);return{position:{left:f.x+m.left,top:f.y+m.top},size:{width:m.width,height:m.height},image:g.elementImage}}async function a(f){let m=[];for(let h of f){let g=await i(h.scrollPos,h.cropData);m.push(g)}return m}function c(f,m){let h=Math.max(f.width,m.width),g=m.width,y=Math.max(f.height,m.height),b=m.height,I=Array.from({length:Math.ceil(h/g)},(v,x)=>({scrollX:Math.min(x*g,h-g),cropX:x*g-Math.min(x*g,h-g),cropW:g-(x*g-Math.min(x*g,h-g))})),T=Array.from({length:Math.ceil(y/b)},(v,x)=>({scrollY:Math.min(x*b,y-b),cropY:x*b-Math.min(x*b,y-b),cropH:b-(x*b-Math.min(x*b,y-b))}));return I.flatMap(v=>T.map(x=>({scrollPos:{x:v.scrollX,y:x.scrollY},cropData:{top:x.cropY,left:v.cropX,width:v.cropW,height:x.cropH}})))}async function l(f,m){let h=await t.getCurrentScrollPosition(),g=c(f,m),y=await a(g);return await t.scrollToPosition(h),lP(f,y)}let[u,p]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(u,p)}};$h.exports=cl});var Vh=C((hD,Gh)=>{"use strict";var pP=require("semver"),Wh=(M(),w(q)),mP=il(),fP=Uh(),hP=Bh(),{getLogger:gP}=(U(),w(H)),{getSessionPlayer:ll}=(he(),w(Re)),Bo=gP("tab-service"),ul=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(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}addNewTab(e,t,r,n={}){return this.addedTabs[e].has(t)?Promise.resolve():(this.addedTabs[e].add(t),Bo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n))}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=Wh.guid();function c(l){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!l.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new mP(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:()=>Promise.resolve()},windowUtils:a,imageCaptureUtils:new hP(t,a,new fP(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=ll(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),l=n(a),u=r.map(p=>o.urlBreaker(p)).map(p=>n(p)).filter(p=>p===c);return c===l&&u.length===1}isSameTab(e,t,r){let{tabMatcher:n}=ll();if(n){let l=this.getAllTabInfos(e),u=Object.keys(l).map(p=>l[p]);return n.isSameTab(u,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(l=>o[l].url);if(this.exactUrlMatch(t,r,i))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,i,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}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(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;return typeof n=="number"&&n>1||r?this.driver.switchTab(e):Promise.resolve()}getTabDetails(e,t,r={}){return this.switchTab(e,t,r).then(()=>{if(r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");return r.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=>(Bo.error("failed to get url or title",{err:o}),{title:"",url:""}))}).catch(n=>{Bo.error("failed to switch to tab",{tabId:e,err:n})})}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await Wh.delay(500),await this.waitForTabToOpen(e))}async tryToAddTab(e,t){if(this.pendingTabs[e])return;let r=await this.getUnregisteredTabId(e);r&&(await this.addNewTab(e,r),await this.addFrameHandler(r),this.sessionTabs[e].currentTab=null)}addNewPopup(e,t){let r=this.getAllTabInfos(e);return Object.keys(r).find(o=>r[o].openerStepId===t)?Promise.resolve():this.pendingTabs[e]?(Bo.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=pP.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.filter(o=>o.type==="locate").filter(o=>!o.frameLocators).length>0;return t&&(!r||n)}getTabIdByTabInfo(e,t){var i,a;let{tabMatcher:r,commonConstants:n}=ll();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 l=this.getMainTabId(e);if(l)return l;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(r){let l=this.getAllTabIds(e).map(u=>Object.assign({},this.getTabInfo(e,u),{tabId:u})).filter(u=>!u.isClosed);c=r.matchTabs(t,l)}else{let l=t.tabInfo;l?c=this.getAllTabIds(e).find(u=>{let p=this.getTabInfo(e,u);return this.isSameTab(e,p,l)}):c=this.getMainTabId(e)}return c?this.sessionTabs[e].currentTab===c?c:this.switchTab(c,e).then(()=>(this.sessionTabs[e].currentTab=c,c)).catch(l=>{let u=["no such window","no window found","the window could not be found"];if(l.message&&u.some(p=>l.message.toLowerCase().includes(p)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[c].isClosed=!0,this.getTabIdByTabInfo(e,t);throw l}):this.tryToAddTab(e,o).then(()=>{throw new Error("No tab ID found")})})}};Gh.exports=ul});var pl=C((gD,Hh)=>{"use strict";var yP=rl(),{getSessionPlayer:wP}=(he(),w(Re)),dl=class{constructor(e,t){this.driver=e,this._abortedSteps=[],this.cookieUtils=t||new yP(this.driver)}get sessionPlayerInit(){return wP()}getTimeStamp(){return Date.now()}getTestimId(e){if(!e)return;let{locatorBuilderUtils:t}=this.sessionPlayerInit,r=t.TESTIM_ID_FIELD_NAME;return t.isEmptyResult(e)?t.EMPTY_RESULT_ID:e.getAttribute(r)}resetAbort(){this._abortedSteps=[]}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}restoreNativeAlerts(){}executeOverloadNativeAlertsInFrame(){}getClickOffset(e,t){let{utils:r}=this.sessionPlayerInit;return e&&r.isWithinBounds(0,t.width,e.x)&&r.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(r=>r.value)}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t,r){return this.driver.markDynamicParent(e,t,r)}getCookie(e){return this.cookieUtils.get({name:e}).then(t=>t?[t]:[])}setCookie(e,t){return this.cookieUtils.set(e).then(r=>[r])}getNextDynamicParent(e,t){let r=`return ${this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t)}`;return this.driver.executeJS(r).then(n=>n.value)}};Hh.exports=dl});var Jh=C((yD,zh)=>{"use strict";var{getLogger:bP}=(U(),w(H)),{featureFlagsService:TP}=(le(),w(me)),{getSessionPlayer:EP}=(he(),w(Re)),vP=bP("frame-locator"),SP="ELEMENT",IP="element-6066-11e4-a52e-4f735466cecf",Kh=s=>s?s[SP]||s[IP]:null;zh.exports=function(e){class t{constructor(n,o){this.frameManager=n,this.locateElementPlayer=o,this._cache={}}cacheResults(n,o){this._cache[n]=o}getResultsFromCache(n){return this._cache[n]}cacheFrameLocateResults(n){if(n!=null&&n.seleniumFrameElement&&n.frameLocateResultUrl){let o=Kh(n.seleniumFrameElement);o&&this.cacheResults(o,n.frameLocateResultUrl)}}async foundFrameCallback(n,o,i){let{frameOffset:a,locatedElement:c}=n,{locatorBuilderUtils:l}=EP();if(l.isEmptyResult(c)){let m="got empty result in frame result, not rejected from locate element player";throw vP.error(m),new Error(m)}let u=await e.switchToLocatedFrame(c),p=Kh(u.value),f=this.getResultsFromCache(p);return{frameId:-1,frameOffset:a,tabInfo:o.tabInfo,tabId:o.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:u.value,frameLocateResultUrl:f}}locate(n,o,i,a,c,l){let u=new this.locateElementPlayer(a);return n.targetId=`frameLocator_${o}`,u.locate(n,i,n.targetId).then(p=>(p.isVisible=!0,u.handleLocateResult(p,l,n).catch(()=>{throw new Error}))).then(p=>{let{locatedElement:f}=a.data[n.targetId];return e.getElementLocationWithPadding(f).then(m=>{let h=m.value||{top:0,left:0};return p.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},p})}).then(p=>(u.addFrameDataToContext&&u.addFrameDataToContext(p.targetId,p.locateResult),this.foundFrameCallback(p,c,n.testimFrameId))).then(p=>(this.currentFrameHandler=p,p))}async findFrame(n,o,i,a){let c=TP.flags.enableFrameSwitchOptimization.isEnabled(),l=i.playback.resultsHandler.resultsByChronologicOrder,u=l[l.length-1],p=1,f=Boolean(u)&&u.stepId===n.id&&u.results.length>p;if(c&&!f&&this.currentFrameHandler){let b=o.findIndex(I=>I.testimFrameId===this.currentFrameHandler.testimFrameId);if(b>-1){let I=o.slice(b+1),T=0;for(let v of I)T++,this.currentFrameHandler=await this.locate(v,T,this.currentFrameHandler,i,a,n);return this.currentFrameHandler}}let m=await a.getTopFrameHandler();m.frameOffset={top:0,left:0},await(c&&this.currentFrameHandler===m?this.currentFrameHandler:e.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=m;let g=0,y=m;for(let b of o)g++,y=await this.locate(b,g,y,i,a,n);return y}}return t}});var Go=C((wD,Qh)=>{"use strict";var xP=require("p-retry"),Xh=require("socket.io-client"),ml=(ne(),w(ce)),RP=(M(),w(q)),CP=50,PP=10,kP=5e3,Yh=10*1e3,Wo=(U(),w(H)).getLogger("base socket service"),fl=class{constructor(){this.attempts=0,this.rooms={},this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Wo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Wo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===PP&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=CP)throw new Error(`Can't connect to Testim Servers.
370
- Action required: Please allow opening a websockets connection to ${ml.SERVICES_HOST} 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",()=>{Wo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),this.onConnect&&this.onConnect()})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:Yh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0"};return global.caFileContent&&(r.ca=global.caFileContent),global.proxyUri&&(r.agent=new global.ProxyAgent(global.proxyUri)),new Promise(n=>{this.url=`${ml.SERVICES_HOST}/${t}`,this._socket=Xh.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Yh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0"};global.caFileContent&&(r.ca=global.caFileContent),global.proxyUri&&(r.agent=new global.ProxyAgent(global.proxyUri)),this.url=`${ml.SERVICES_HOST}/${t}`,this._socket=Xh.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>xP(()=>RP.promiseTimeout(n(),kP),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Wo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}};Qh.exports=fl});var eg=C((bD,Zh)=>{"use strict";var AP=Go(),hl=class extends AP{init(e){super.init(e,"testResult"),this.listerers={}}listenToTestResult(e,t,r){this.listerers[e]&&(this._socket.off("testResult:updated",this.listerers[e]),delete this.listerers[e]),this.listerers[e]=n=>{n.resultId===e&&n.testId===t&&r(n.testResult)},this._socket.on("testResult:updated",this.listerers[e])}emitJoinRoom(e,t){return this.emitPromise("testResult:join",{resultId:e,testId:t})}joinToTestResult(e,t){return this.rooms[e]?Promise.resolve():(this.joinRoom(e,t),this.emitJoinRoom(e,t))}emitLeaveRoom(e,t){return this.emitPromise("testResult:leave",{resultId:e,testId:t})}leaveTestResult(e,t){return this.listerers[e]?(this.leaveRoom(e),this._socket.off("testResult:updated",this.listerers[e]),delete this.listerers[e],this.emitLeaveRoom(e,t)):Promise.resolve()}getSocket(){return this._socket}};Zh.exports=new hl});var en={};W(en,{testResultService:()=>yl});var Vo,hs,_P,Hs,Zr,gl,yl,Ks=F(()=>{"use strict";Vo=Br(),hs=eg(),{EventEmitter:_P}=require("events"),{socketEventTypes:Hs}=(ee(),w(fe)),{featureFlagsService:Zr}=(le(),w(me)),gl=class extends _P{init(e){if(Zr.flags.useNewWSCLI.isEnabled()){Vo.onConnect=()=>this.emit("socket-connected");return}hs.init(e),hs.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return Zr.flags.useNewWSCLI.isEnabled()?Vo.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Hs.TEST_RESULT_UPDATED,Hs.TEST_RESULT_CREATED]):(hs.joinRoom(e,t),hs.emitJoinRoom(e,t))}leaveTestResult(e,t){return Zr.flags.useNewWSCLI.isEnabled()?(Vo.removeFilter(`${e}:testResult`,[Hs.TEST_RESULT_UPDATED,Hs.TEST_RESULT_CREATED]),Promise.resolve()):hs.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(Zr.flags.useNewWSCLI.isEnabled()){Vo.listenTo(`${e}:testResult`,[Hs.TEST_RESULT_UPDATED,Hs.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}hs.listenToTestResult(e,t,r)}getSocket(){if(!Zr.flags.useNewWSCLI.isEnabled())return hs.getSocket()}},yl=new gl});var bl=C((TD,tg)=>{"use strict";var wl=class{on(){}};tg.exports=new wl});var El=C((ED,rg)=>{"use strict";var OP=require("lodash"),LP=1e3,sg=["simple-ui-verification","wait-for-simple-ui-verification"],NP=[...sg,"custom-validation","sfdc-recorded-step","sfdc-step-login","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"],Tl=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 r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=NP.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}getStepTimes(){return this.totalStepTimesReport.push(this.currentRetryTimesReport),OP.cloneDeep(this.totalStepTimesReport)}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return sg.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+LP}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 r=2e3;return e.step.isScrollToElement&&(r=4e3),e.step.events.length*r+5e3}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4,o;return r==="sleep"?o=e.step.durationMS+t:r==="android-scroll"?o=Math.max(this.calcAndroidScrollTimeout(e),n):o=Math.max(this.getTotalStepTimeLeftToPlay(e),n),o}setStepPhaseTime(e){let t=Date.now(),r=t-this.lastUpdateTime;this.lastUpdateTime=t,this.currentRetryTimesReport[e]=r}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")}};rg.exports=Tl});var Sl={};W(Sl,{portSelector:()=>DP});var vl,DP,Il=F(()=>{"use strict";vl=class{constructor(){}select(){return console.log(`
369
+ `,h=[],g=new a(m,{eval:!0});return ms.promiseTimeout(new Promise(w=>{g.on("message",b=>{if(b.action==="finish"){let{data:I}=b,T=Object.assign({},I,{tstConsoleLogs:h});Pe.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),w(T)}else b.action==="progress"&&h.push(b.data)}).on("error",b=>{b.message==="malformed data: URI"?Pe.error("Run code worker error",{err:b,transactionId:s,fileDataUrl:i}):Pe.error("Run code worker error",{err:b,transactionId:s}),w({tstConsoleLogs:h,status:"failed",result:{resultValue:b==null?void 0:b.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{Pe.debug("Run code worker has been terminated",{transactionId:s})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o).catch(w=>{if(!(w instanceof ms.TimeoutError))throw w;return Pe.warn("timeout to run code",{transactionId:s,err:w}),{tstConsoleLogs:h,status:"failed",result:{resultValue:w==null?void 0:w.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}).finally(()=>g==null?void 0:g.terminate())}async function zC(s){try{await UC.remove(s)}catch(e){Pe.warn("failed to remove install npm packages folder",{err:e})}}function Ah(s,e,t,r){return`${e}_${t}_${s}_${r}`}function JC(s,e,t,r,n,o){let i=Ah(n,e,s,t);return YC(i,r,o).then(({data:a})=>a)}function XC(s,e,t,r,n,o,i,a,c,l){let u=(t.nodePackageParams||[]).reduce((m,h)=>(m[h.paramName]=h.testimPackageLocalLocation,m),{}),p=Ah(i,n,e,o);return(l?GC(l):Promise.resolve()).then(m=>{m&&(c=m)}).then(()=>{if(typeof ps>"u")try{ps=require("worker_threads")}catch{ps=!1}Buffer.isBuffer(c)&&(Pe.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let m="data:,";return c==="data:"&&(Pe.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=m),ps&&qC.flags.enableWorkerThreadsCliCodeExecution.isEnabled()?KC(p,t,r,s,u,a,c):VC(p,t,r,s,u,a,c)}).then(m=>Object.assign({},m,{nodeVersion:process.version}))}async function YC(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=_h(),o=$o.join(n,`/${s}`),i=global.proxyUri;async function a(){let c="";try{if(c=await Ch.installPackages(o,r,i,t),Pe.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(u=>{let p=Ch.getLocallyInstalledPackageVersion(o,u.packageName),f=`${u.packageName}@${p}`,m=$o.resolve(o,"node_modules",u.packageName);return Object.assign({},u,{packageFullName:f,packageLocalLocation:m})}),installFolder:o}}catch(l){throw Pe.warn("npm package install failed",{transactionId:s,err:l}),l}}try{return await ms.promiseTimeout(a(),t)}catch(c){throw c instanceof BC&&Pe.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function _h(){return $o.join(FC.tmpdir(),"/testim_local_packages")}function QC(){let s=_h();return zC(s)}Oh.exports={runCodeWithPackages:XC,installPackage:JC,cleanLocalPackageInstallFolder:QC}});var Lh=C((dD,Nh)=>{"use strict";var ZC=fs(),{TimeoutError:eP}=(K(),y(Z)),{featureFlagsService:tP}=(le(),y(me));function sP(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=tP.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}Nh.exports.run=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:u,fileDataUrl:p,s3filepath:f}=e.data;try{let m=await ZC.runCodeWithPackages(r,n,o,i,a,c,l,u,p,f);return m&&sP({result:m.result,tstConsoleLogs:m.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:m,success:!0}}catch(m){throw m instanceof eP?new Error("Timeout while running action"):m}}});var nl=C((pD,Dh)=>{"use strict";var rl=(U(),y(H)).getLogger("cookies-utils");Dh.exports=function(s){class e{set(r){let n=r.domain;return r.hostOnly||n&&!n.startsWith(".")&&(n=`.${n}`),s.setCookie(r.name,r.value,n,r.httpOnly,r.secure,r.path,r.expirationDate).catch(o=>{throw rl.error("failed to set cookie",{err:o}),o})}get(r){return s.getCookie(r.name).catch(n=>{throw rl.error("failed to get cookie",{err:n}),n})}remove(r){return s.deleteCookie(r.name).catch(n=>{throw rl.error("failed to remove cookie",{err:n}),n})}}return new e}});var al=C((mD,Fh)=>{"use strict";var Mh=require("p-retry"),{delay:ol}=(M(),y(q)),{PageNotAvailableError:rP}=(K(),y(Z)),nP=(M(),y(q)),oP=(U(),y(H)).getLogger("window-utils"),il=class{constructor(e,t){this.id=e,this.driver=t}getElementFromPoint(e,t){function r(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(r,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(r){var n="scrollBehavior"in document.documentElement.style;return n?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.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 r=this;async function n(o=3){try{await r.driver.url(e)}catch(i){if(i.seleniumStack&&i.message.includes("method IWebBrowser2::Navigate2() failed")&&o>0)return oP.warn("selenium navigation failed. retrying to navigate",{err:i}),await ol(1500),n(o-1);throw i}}return Promise.race([n(),ol(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ol(e)])}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}getFullPageSize(){function e(){var t=document.body,r=document.documentElement,n=Math.max(t.scrollHeight,t.offsetHeight,r.clientHeight,r.scrollHeight,r.offsetHeight),o=Math.max(t.scrollWidth,t.offsetWidth,r.clientWidth,r.scrollWidth,r.offsetWidth);return{height:n,width:o}}return this.driver.executeJS(e).then(t=>t.value)}extractToNewWindow(){return Promise.resolve()}async checkSize(e){await nP.delay(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 r;if(typeof location<"u")r=location;else if(typeof window<"u"&&typeof window.location<"u")r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new rP("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await Mh(()=>this.driver.getBrowserAndOS(),{retries:3});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return Mh(()=>this.driver.getUserAgentInfo(),{retries:3})}};Fh.exports=il});var jh=C((fD,qh)=>{"use strict";var Uh=require("p-retry"),cl=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e,this.driver=t,this.options=r}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await Uh(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,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await Uh(o,{retries:t,minTimeout:r}),c=a?a.value:"";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}};qh.exports=cl});var Gh=C((hD,Wh)=>{"use strict";var iP=require("lodash"),Zr=require("jimp"),aP=(M(),y(q)),cP=(U(),y(H)).getLogger("image-capture-utils"),en=class extends Error{constructor(e){super(e),this.rectIsOutsideOfImageError=!0,Object.setPrototypeOf(this,en.prototype)}};async function $h(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data\:[^;]*\;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return cP.warn("missing elementRect",iP.omit(s,"image")),{};let{elementRect:i}=s,a=await Zr.read(Buffer.from(n[1],"base64")),c=i.left*r+o.left*r,l=i.top*r+o.top*r,u=i.width*r,p=i.height*r;c<0&&(u+=c,u=u<0?0:u,c=0),l<0&&(p+=l,p=p<0?0:p,l=0);let f=a.bitmap.width,m=a.bitmap.height;if(c+u>f&&(u=f-c),l+p>m&&(p=m-l),p<=0||u<=0)throw new en("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,u,p).getBase64Async(Zr.MIME_PNG)}}async function lP(s,e){let t=await Zr.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data\:[^;]*\;base64,(.*)$/),i=await Zr.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,l=>{if(l){c(l);return}a()})})}return await t.getBase64Async(Zr.MIME_PNG)}function uP(s,e){return lP(s,e)}function dP(){return Promise.resolve()}function pP(s){function e(r){return typeof s[r]=="string"&&s[r].startsWith("data")}function t(r){return dP(s[r]).then(n=>({key:r,url:n}))}return Promise.all(Object.keys(s).filter(e).map(t)).then(r=>r.reduce((n,o)=>(n[o.key]=o.url,n),s))}function Bh(s,e){return e=e||1,s=s||{left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var ll=class{constructor(e,t,r){this.windowUtils=t,this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){e.areas&&(e=e.areas);let t=await this.screenshotUtils.takeScreenshot(),r=await $h(e,t);return r.screenImage=t.image,r.absoluteScreenHighlight=Bh(e.elementRect,t.devicePixelRatio),r}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return typeof t=="string"?t:t.image}async takeArea(e){e.areas&&(e=e.areas);let t=await this.screenshotUtils.takeScreenshot();return pP({screenImage:t.image,absoluteScreenHighlight:Bh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>aP.delay(250),o=Boolean(e);async function i(f,m){o?await t.scrollToPositionWithoutAnimation(f):await t.scrollToPosition(f),await n();let h=await r.takeScreenshot(),g=await $h({elementRect:m},h);return{position:{left:f.x+m.left,top:f.y+m.top},size:{width:m.width,height:m.height},image:g.elementImage}}async function a(f){let m=[];for(let h of f){let g=await i(h.scrollPos,h.cropData);m.push(g)}return m}function c(f,m){let h=Math.max(f.width,m.width),g=m.width,w=Math.max(f.height,m.height),b=m.height,I=Array.from({length:Math.ceil(h/g)},(v,x)=>({scrollX:Math.min(x*g,h-g),cropX:x*g-Math.min(x*g,h-g),cropW:g-(x*g-Math.min(x*g,h-g))})),T=Array.from({length:Math.ceil(w/b)},(v,x)=>({scrollY:Math.min(x*b,w-b),cropY:x*b-Math.min(x*b,w-b),cropH:b-(x*b-Math.min(x*b,w-b))}));return I.flatMap(v=>T.map(x=>({scrollPos:{x:v.scrollX,y:x.scrollY},cropData:{top:x.cropY,left:v.cropX,width:v.cropW,height:x.cropH}})))}async function l(f,m){let h=await t.getCurrentScrollPosition(),g=c(f,m),w=await a(g);return await t.scrollToPosition(h),uP(f,w)}let[u,p]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(u,p)}};Wh.exports=ll});var Kh=C((gD,Hh)=>{"use strict";var mP=require("semver"),Vh=(M(),y(q)),fP=al(),hP=jh(),gP=Gh(),{getLogger:yP}=(U(),y(H)),{getSessionPlayer:ul}=(he(),y(Re)),Bo=yP("tab-service"),dl=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(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}addNewTab(e,t,r,n={}){return this.addedTabs[e].has(t)?Promise.resolve():(this.addedTabs[e].add(t),Bo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n))}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=Vh.guid();function c(l){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!l.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new fP(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:()=>Promise.resolve()},windowUtils:a,imageCaptureUtils:new gP(t,a,new hP(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=ul(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),l=n(a),u=r.map(p=>o.urlBreaker(p)).map(p=>n(p)).filter(p=>p===c);return c===l&&u.length===1}isSameTab(e,t,r){let{tabMatcher:n}=ul();if(n){let l=this.getAllTabInfos(e),u=Object.keys(l).map(p=>l[p]);return n.isSameTab(u,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(l=>o[l].url);if(this.exactUrlMatch(t,r,i))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,i,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}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(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;return typeof n=="number"&&n>1||r?this.driver.switchTab(e):Promise.resolve()}getTabDetails(e,t,r={}){return this.switchTab(e,t,r).then(()=>{if(r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");return r.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=>(Bo.error("failed to get url or title",{err:o}),{title:"",url:""}))}).catch(n=>{Bo.error("failed to switch to tab",{tabId:e,err:n})})}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await Vh.delay(500),await this.waitForTabToOpen(e))}async tryToAddTab(e,t){if(this.pendingTabs[e])return;let r=await this.getUnregisteredTabId(e);r&&(await this.addNewTab(e,r),await this.addFrameHandler(r),this.sessionTabs[e].currentTab=null)}addNewPopup(e,t){let r=this.getAllTabInfos(e);return Object.keys(r).find(o=>r[o].openerStepId===t)?Promise.resolve():this.pendingTabs[e]?(Bo.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=mP.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.filter(o=>o.type==="locate").filter(o=>!o.frameLocators).length>0;return t&&(!r||n)}getTabIdByTabInfo(e,t){var i,a;let{tabMatcher:r,commonConstants:n}=ul();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 l=this.getMainTabId(e);if(l)return l;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(r){let l=this.getAllTabIds(e).map(u=>Object.assign({},this.getTabInfo(e,u),{tabId:u})).filter(u=>!u.isClosed);c=r.matchTabs(t,l)}else{let l=t.tabInfo;l?c=this.getAllTabIds(e).find(u=>{let p=this.getTabInfo(e,u);return this.isSameTab(e,p,l)}):c=this.getMainTabId(e)}return c?this.sessionTabs[e].currentTab===c?c:this.switchTab(c,e).then(()=>(this.sessionTabs[e].currentTab=c,c)).catch(l=>{let u=["no such window","no window found","the window could not be found"];if(l.message&&u.some(p=>l.message.toLowerCase().includes(p)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[c].isClosed=!0,this.getTabIdByTabInfo(e,t);throw l}):this.tryToAddTab(e,o).then(()=>{throw new Error("No tab ID found")})})}};Hh.exports=dl});var ml=C((yD,zh)=>{"use strict";var wP=nl(),{getSessionPlayer:bP}=(he(),y(Re)),pl=class{constructor(e,t){this.driver=e,this._abortedSteps=[],this.cookieUtils=t||new wP(this.driver)}get sessionPlayerInit(){return bP()}getTimeStamp(){return Date.now()}getTestimId(e){if(!e)return;let{locatorBuilderUtils:t}=this.sessionPlayerInit,r=t.TESTIM_ID_FIELD_NAME;return t.isEmptyResult(e)?t.EMPTY_RESULT_ID:e.getAttribute(r)}resetAbort(){this._abortedSteps=[]}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}restoreNativeAlerts(){}executeOverloadNativeAlertsInFrame(){}getClickOffset(e,t){let{utils:r}=this.sessionPlayerInit;return e&&r.isWithinBounds(0,t.width,e.x)&&r.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(r=>r.value)}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t,r){return this.driver.markDynamicParent(e,t,r)}getCookie(e){return this.cookieUtils.get({name:e}).then(t=>t?[t]:[])}setCookie(e,t){return this.cookieUtils.set(e).then(r=>[r])}getNextDynamicParent(e,t){let r=`return ${this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t)}`;return this.driver.executeJS(r).then(n=>n.value)}};zh.exports=pl});var Yh=C((wD,Xh)=>{"use strict";var{getLogger:TP}=(U(),y(H)),{featureFlagsService:EP}=(le(),y(me)),{getSessionPlayer:vP}=(he(),y(Re)),SP=TP("frame-locator"),IP="ELEMENT",xP="element-6066-11e4-a52e-4f735466cecf",Jh=s=>s?s[IP]||s[xP]:null;Xh.exports=function(e){class t{constructor(n,o){this.frameManager=n,this.locateElementPlayer=o,this._cache={}}cacheResults(n,o){this._cache[n]=o}getResultsFromCache(n){return this._cache[n]}cacheFrameLocateResults(n){if(n!=null&&n.seleniumFrameElement&&n.frameLocateResultUrl){let o=Jh(n.seleniumFrameElement);o&&this.cacheResults(o,n.frameLocateResultUrl)}}async foundFrameCallback(n,o,i){let{frameOffset:a,locatedElement:c}=n,{locatorBuilderUtils:l}=vP();if(l.isEmptyResult(c)){let m="got empty result in frame result, not rejected from locate element player";throw SP.error(m),new Error(m)}let u=await e.switchToLocatedFrame(c),p=Jh(u.value),f=this.getResultsFromCache(p);return{frameId:-1,frameOffset:a,tabInfo:o.tabInfo,tabId:o.tabId,testimFrameId:i,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${i}`,seleniumFrameElement:u.value,frameLocateResultUrl:f}}locate(n,o,i,a,c,l){let u=new this.locateElementPlayer(a);return n.targetId=`frameLocator_${o}`,u.locate(n,i,n.targetId).then(p=>(p.isVisible=!0,u.handleLocateResult(p,l,n).catch(()=>{throw new Error}))).then(p=>{let{locatedElement:f}=a.data[n.targetId];return e.getElementLocationWithPadding(f).then(m=>{let h=m.value||{top:0,left:0};return p.frameOffset={top:i.frameOffset.top+h.top,left:i.frameOffset.left+h.left},p})}).then(p=>(u.addFrameDataToContext&&u.addFrameDataToContext(p.targetId,p.locateResult),this.foundFrameCallback(p,c,n.testimFrameId))).then(p=>(this.currentFrameHandler=p,p))}async findFrame(n,o,i,a){let c=EP.flags.enableFrameSwitchOptimization.isEnabled(),l=i.playback.resultsHandler.resultsByChronologicOrder,u=l[l.length-1],p=1,f=Boolean(u)&&u.stepId===n.id&&u.results.length>p;if(c&&!f&&this.currentFrameHandler){let b=o.findIndex(I=>I.testimFrameId===this.currentFrameHandler.testimFrameId);if(b>-1){let I=o.slice(b+1),T=0;for(let v of I)T++,this.currentFrameHandler=await this.locate(v,T,this.currentFrameHandler,i,a,n);return this.currentFrameHandler}}let m=await a.getTopFrameHandler();m.frameOffset={top:0,left:0},await(c&&this.currentFrameHandler===m?this.currentFrameHandler:e.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=m;let g=0,w=m;for(let b of o)g++,w=await this.locate(b,g,w,i,a,n);return w}}return t}});var Go=C((bD,eg)=>{"use strict";var RP=require("p-retry"),Qh=require("socket.io-client"),fl=(ne(),y(ce)),CP=(M(),y(q)),PP=50,kP=10,AP=5e3,Zh=10*1e3,Wo=(U(),y(H)).getLogger("base socket service"),hl=class{constructor(){this.attempts=0,this.rooms={},this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Wo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Wo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===kP&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=PP)throw new Error(`Can't connect to Testim Servers.
370
+ Action required: Please allow opening a websockets connection to ${fl.SERVICES_HOST} 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",()=>{Wo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),this.onConnect&&this.onConnect()})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:Zh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0"};return global.caFileContent&&(r.ca=global.caFileContent),global.proxyUri&&(r.agent=new global.ProxyAgent(global.proxyUri)),new Promise(n=>{this.url=`${fl.SERVICES_HOST}/${t}`,this._socket=Qh.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Zh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0"};global.caFileContent&&(r.ca=global.caFileContent),global.proxyUri&&(r.agent=new global.ProxyAgent(global.proxyUri)),this.url=`${fl.SERVICES_HOST}/${t}`,this._socket=Qh.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>RP(()=>CP.promiseTimeout(n(),AP),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Wo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}};eg.exports=hl});var sg=C((TD,tg)=>{"use strict";var _P=Go(),gl=class extends _P{init(e){super.init(e,"testResult"),this.listerers={}}listenToTestResult(e,t,r){this.listerers[e]&&(this._socket.off("testResult:updated",this.listerers[e]),delete this.listerers[e]),this.listerers[e]=n=>{n.resultId===e&&n.testId===t&&r(n.testResult)},this._socket.on("testResult:updated",this.listerers[e])}emitJoinRoom(e,t){return this.emitPromise("testResult:join",{resultId:e,testId:t})}joinToTestResult(e,t){return this.rooms[e]?Promise.resolve():(this.joinRoom(e,t),this.emitJoinRoom(e,t))}emitLeaveRoom(e,t){return this.emitPromise("testResult:leave",{resultId:e,testId:t})}leaveTestResult(e,t){return this.listerers[e]?(this.leaveRoom(e),this._socket.off("testResult:updated",this.listerers[e]),delete this.listerers[e],this.emitLeaveRoom(e,t)):Promise.resolve()}getSocket(){return this._socket}};tg.exports=new gl});var sn={};W(sn,{testResultService:()=>wl});var Vo,hs,OP,Ks,tn,yl,wl,zs=F(()=>{"use strict";Vo=Wr(),hs=sg(),{EventEmitter:OP}=require("events"),{socketEventTypes:Ks}=(ee(),y(fe)),{featureFlagsService:tn}=(le(),y(me)),yl=class extends OP{init(e){if(tn.flags.useNewWSCLI.isEnabled()){Vo.onConnect=()=>this.emit("socket-connected");return}hs.init(e),hs.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return tn.flags.useNewWSCLI.isEnabled()?Vo.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Ks.TEST_RESULT_UPDATED,Ks.TEST_RESULT_CREATED]):(hs.joinRoom(e,t),hs.emitJoinRoom(e,t))}leaveTestResult(e,t){return tn.flags.useNewWSCLI.isEnabled()?(Vo.removeFilter(`${e}:testResult`,[Ks.TEST_RESULT_UPDATED,Ks.TEST_RESULT_CREATED]),Promise.resolve()):hs.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(tn.flags.useNewWSCLI.isEnabled()){Vo.listenTo(`${e}:testResult`,[Ks.TEST_RESULT_UPDATED,Ks.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}hs.listenToTestResult(e,t,r)}getSocket(){if(!tn.flags.useNewWSCLI.isEnabled())return hs.getSocket()}},wl=new yl});var Tl=C((ED,rg)=>{"use strict";var bl=class{on(){}};rg.exports=new bl});var vl=C((vD,og)=>{"use strict";var NP=require("lodash"),LP=1e3,ng=["simple-ui-verification","wait-for-simple-ui-verification"],DP=[...ng,"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"],El=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 r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=DP.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}getStepTimes(){return this.totalStepTimesReport.push(this.currentRetryTimesReport),NP.cloneDeep(this.totalStepTimesReport)}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return ng.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+LP}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 r=2e3;return e.step.isScrollToElement&&(r=4e3),e.step.events.length*r+5e3}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4,o;return r==="sleep"?o=e.step.durationMS+t:r==="android-scroll"?o=Math.max(this.calcAndroidScrollTimeout(e),n):o=Math.max(this.getTotalStepTimeLeftToPlay(e),n),o}setStepPhaseTime(e){let t=Date.now(),r=t-this.lastUpdateTime;this.lastUpdateTime=t,this.currentRetryTimesReport[e]=r}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")}};og.exports=El});var Il={};W(Il,{portSelector:()=>MP});var Sl,MP,xl=F(()=>{"use strict";Sl=class{constructor(){}select(){return console.log(`
371
371
  internal error - cant use port selector in selenium!!!!
372
- `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},DP=new vl});var xl={};W(xl,{isDebuggerConnected:()=>MP});var MP,Rl=F(()=>{"use strict";ne();MP=()=>{try{if(bi)return!1;if(require("inspector").url())return!0}catch{}return!1}});var re=C((SD,ng)=>{"use strict";var{getSessionPlayer:FP}=(he(),w(Re)),Cl=class{constructor(e,t,r,n={},o=void 0,i=void 0,a={}){this.step=e,this.context=t,this.frameHandler=r,this.frameId=0,this.stepActionUtils=o,this.locateElementPlayer=i,this.exportsGlobal=n,this.exportsTest=a}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return FP()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(e,t){var r;try{return{success:!0,...await this.performAction(e,t)}}catch(n){let o=(n==null?void 0:n.message)||((r=n==null?void 0:n.seleniumStack)==null?void 0:r.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}}}}};ng.exports=Cl});var cg=C((ID,ag)=>{"use strict";var UP=re(),{JSDOM:qP,VirtualConsole:jP}=require("jsdom"),{getLogger:$P}=(U(),w(H)),{featureFlagsService:og}=(le(),w(me)),{getSessionPlayer:ig}=(he(),w(Re)),gs=$P("locate-step-action"),BP={opacity:1,clientRects:{}};function WP(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},getOffsets(e){return Promise.resolve([e.frameOffset||{}])},htmlStringToDom(e,t,r,n,o=!0){let i=new jP,a=new qP(e,{virtualConsole:i}),{window:c}=a;return o&&setTimeout(()=>{c.close()},1e3*60),Object.assign(c.document,{TESTIM_URL:t})},shouldUseNativeVisibilityCheck(e,t,r,n){return e.opacity===0||e.isShadowed?!1:r===void 0||n===void 0?!0:og.flags.useClickimVisibilityChecks.isEnabled()?!1:t.isSafari()?og.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0},async isVisible(e,t,r,n,o,i,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:u,positionUtils:p}=ig();if(this.shouldUseNativeVisibilityCheck(n,s,u,p))return s.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[p.calculateElementMiddlePoint(r),p.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(x){throw gs.error("failed to execute getVisibilityCode",{err:x}),x}let{value:b}=y||{},I=b.elementVisibilityInfo||BP,[T,v]=b.elementsFromPointResults||[null,null];return u.checkElementVisibility(I,n,v,T,a,t)},scrollToElement(e,t){let{codeSnippets:r}=ig(),n=r.scrollToElement;return s.execute(n(t))}}}var Pl=class extends UP{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return Object.assign(WP(e),{useLocatedElement:!0})}static getFrameIdByTestimFrameId(...e){throw gs.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(...e){throw gs.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(...e){throw gs.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(...e){throw gs.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(...e){throw gs.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(...e){throw gs.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}};ag.exports=Pl});var ug=C((xD,lg)=>{"use strict";var GP=function(s,e,t,r,n,o,i,a){function c(b,I){if(!I)return{success:!1};elementScrollTo(I,b.x,b.y);let T=I.scrollLeft,v=I.scrollTop;return{success:Math.abs(v-b.y)<1&&Math.abs(T-b.x)<1,actualX:T,actualY:v}}function l(b,I,T,v,x,A,N){if(!T)return{x:v,y:x};let B=getLocatedElement(I);if(r&&!B)return{x:b.scrollWidth,y:b.scrollHeight};if(!B)throw new Error("could not find target element");let $=B.getBoundingClientRect(),k=0,E=0,P=Math.max(window.innerHeight-($.height+10),0),j=Math.max(window.innerWidth-($.width+10),0);return k=N?b.scrollTop+$.top-Math.min(x,P):b.scrollTop,E=A?b.scrollLeft+$.left-Math.min(v,j):b.scrollLeft,{x:Math.round(E),y:Math.round(k)}}let u=!s;if(s=u?document.scrollingElement||document.documentElement:getLocatedElement(s),!s)throw new Error("could not find target to scroll on");let p={top:s.scrollTop,left:s.scrollLeft},f=l(s,e,t,n,o,i,a),m=c(f,s);u&&!document.scrollingElement&&!m.success&&p.top===s.scrollTop&&p.left===s.scrollLeft&&(s=document.body,f=l(s,e,t,n,o,i,a),m=c(f,s));let h=m.actualX,g=m.actualY,y=getLocatedElement(e);if(t&&r&&!y)return{success:!1,expectedPosition:f};if(t){if(!y)throw new Error("could not find target to scroll to");let b=y.getBoundingClientRect();h=b.left,g=b.top}return{success:m.success,actualX:h,actualY:g}};lg.exports=GP});var pg=C((RD,dg)=>{"use strict";var VP=ug(),HP=re(),kl=class extends HP{getFailureString(e,t,r,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${r}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:o}}=this.sessionPlayerInit,i=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(u,p,f){u.scrollTo(p,f)}:function(u,p,f){u.scrollTop=f,u.scrollLeft=p},l=`
372
+ `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},MP=new Sl});var Rl={};W(Rl,{isDebuggerConnected:()=>FP});var FP,Cl=F(()=>{"use strict";ne();FP=()=>{try{if(Ti)return!1;if(require("inspector").url())return!0}catch{}return!1}});var re=C((ID,ig)=>{"use strict";var{getSessionPlayer:UP}=(he(),y(Re)),Pl=class{constructor(e,t,r,n={},o=void 0,i=void 0,a={}){this.step=e,this.context=t,this.frameHandler=r,this.frameId=0,this.stepActionUtils=o,this.locateElementPlayer=i,this.exportsGlobal=n,this.exportsTest=a}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return UP()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(e,t){var r;try{return{success:!0,...await this.performAction(e,t)}}catch(n){let o=(n==null?void 0:n.message)||((r=n==null?void 0:n.seleniumStack)==null?void 0:r.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}}}}};ig.exports=Pl});var ug=C((xD,lg)=>{"use strict";var qP=re(),{JSDOM:jP,VirtualConsole:$P}=require("jsdom"),{getLogger:BP}=(U(),y(H)),{featureFlagsService:ag}=(le(),y(me)),{getSessionPlayer:cg}=(he(),y(Re)),gs=BP("locate-step-action"),WP={opacity:1,clientRects:{}};function GP(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},getOffsets(e){return Promise.resolve([e.frameOffset||{}])},htmlStringToDom(e,t,r,n,o=!0){let i=new $P,a=new jP(e,{virtualConsole:i}),{window:c}=a;return o&&setTimeout(()=>{c.close()},1e3*60),Object.assign(c.document,{TESTIM_URL:t})},shouldUseNativeVisibilityCheck(e,t,r,n){return e.opacity===0||e.isShadowed?!1:r===void 0||n===void 0?!0:ag.flags.useClickimVisibilityChecks.isEnabled()?!1:t.isSafari()?ag.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0},async isVisible(e,t,r,n,o,i,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:u,positionUtils:p}=cg();if(this.shouldUseNativeVisibilityCheck(n,s,u,p))return s.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[p.calculateElementMiddlePoint(r),p.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),w;try{w=await s.execute(`return ${g}`)}catch(x){throw gs.error("failed to execute getVisibilityCode",{err:x}),x}let{value:b}=w||{},I=b.elementVisibilityInfo||WP,[T,v]=b.elementsFromPointResults||[null,null];return u.checkElementVisibility(I,n,v,T,a,t)},scrollToElement(e,t){let{codeSnippets:r}=cg(),n=r.scrollToElement;return s.execute(n(t))}}}var kl=class extends qP{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return Object.assign(GP(e),{useLocatedElement:!0})}static getFrameIdByTestimFrameId(...e){throw gs.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(...e){throw gs.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(...e){throw gs.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(...e){throw gs.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(...e){throw gs.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(...e){throw gs.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}};lg.exports=kl});var pg=C((RD,dg)=>{"use strict";var VP=function(s,e,t,r,n,o,i,a){function c(b,I){if(!I)return{success:!1};elementScrollTo(I,b.x,b.y);let T=I.scrollLeft,v=I.scrollTop;return{success:Math.abs(v-b.y)<1&&Math.abs(T-b.x)<1,actualX:T,actualY:v}}function l(b,I,T,v,x,A,L){if(!T)return{x:v,y:x};let B=getLocatedElement(I);if(r&&!B)return{x:b.scrollWidth,y:b.scrollHeight};if(!B)throw new Error("could not find target element");let $=B.getBoundingClientRect(),k=0,E=0,P=Math.max(window.innerHeight-($.height+10),0),j=Math.max(window.innerWidth-($.width+10),0);return k=L?b.scrollTop+$.top-Math.min(x,P):b.scrollTop,E=A?b.scrollLeft+$.left-Math.min(v,j):b.scrollLeft,{x:Math.round(E),y:Math.round(k)}}let u=!s;if(s=u?document.scrollingElement||document.documentElement:getLocatedElement(s),!s)throw new Error("could not find target to scroll on");let p={top:s.scrollTop,left:s.scrollLeft},f=l(s,e,t,n,o,i,a),m=c(f,s);u&&!document.scrollingElement&&!m.success&&p.top===s.scrollTop&&p.left===s.scrollLeft&&(s=document.body,f=l(s,e,t,n,o,i,a),m=c(f,s));let h=m.actualX,g=m.actualY,w=getLocatedElement(e);if(t&&r&&!w)return{success:!1,expectedPosition:f};if(t){if(!w)throw new Error("could not find target to scroll to");let b=w.getBoundingClientRect();h=b.left,g=b.top}return{success:m.success,actualX:h,actualY:g}};dg.exports=VP});var fg=C((CD,mg)=>{"use strict";var HP=pg(),KP=re(),Al=class extends KP{getFailureString(e,t,r,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${r}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:o}}=this.sessionPlayerInit,i=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(u,p,f){u.scrollTo(p,f)}:function(u,p,f){u.scrollTop=f,u.scrollLeft=p},l=`
373
373
  var getLocatedElement = ${n.getLocatedElementCode};
374
374
  var elementScrollTo = ${c.toString()};
375
- var scroll = ${VP.toString()};
375
+ var scroll = ${HP.toString()};
376
376
  return scroll.apply(null, arguments)
377
- `;try{let u=await this.driver.executeJSWithArray(l,[r,e,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop]);if(!(u!=null&&u.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:f,actualY:m}=u.value;return p?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,f,m)}}}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,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}};dg.exports=kl});var fg=C((CD,mg)=>{"use strict";var KP=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(T,v){var N;function x(B){function $(P){return o(P).find(j=>Array.apply(null,j.classList||[]).includes("Select-control"))}function k(P){let j=$(P);return j?j.querySelector("INPUT"):null}let E=k(B);E&&E.focus()}let A=(N=T.quirks)==null?void 0:N.isReactSelect;v.type==="mousedown"&&A&&x(T.element)}function n(T,v){var A;let x=(A=T.quirks)==null?void 0:A.isCKEditorFrame;v.type==="click"&&x&&document.body.focus()}function o(T){return T?[T].concat(o(T.parentNode)):[]}function i(T){let v={status:"done",result:T,success:!0};I.isNonTextableElemnet&&(v.reason="Set text on non input element"),e(v)}function a(T){T=T||{},e({status:"failed",result:T,success:!1})}function c(T){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),T.dispatchEvent(v)}function l(T){let v={},x=T.getBoundingClientRect(),A=x.left+x.width/2,N=x.top+x.height/2,k=m("mousemove",v,A,N,0);T.dispatchEvent(k)}function u(T,v){function x(k,E,P){return P>k&&P<E}let A=T.pointerPosition||{},N=v.getBoundingClientRect(),B=A.originX&&x(N.left,N.left+N.width,A.originX)?A.originX:N.left+N.width/2,$=A.originY&&x(N.top,N.top+N.height,A.originY)?A.originY:N.top+N.height/2;return{x:B,y:$}}function p(T,v,x){return{screenX:0,screenY:0,clientX:v,clientY:x,ctrlKey:Boolean(T.ctrl),altKey:Boolean(T.alt),shiftKey:Boolean(T.shift),metaKey:Boolean(T.meta),bubbles:!0,cancelable:!0,composed:!0}}function f(T,v,x,A){if(!window.PointerEvent)return;let N=p(v,x,A);return N.pointerType="mouse",N.isPrimary=!0,new window.PointerEvent(T,N)}function m(T,v,x,A,N){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(T,!0,!0,document.defaultView,1,0,0,x,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),N,document.body?document.body.parentNode:document.documentElement),B}function h(T,v){let x=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},N=u(T,v.element),B=v.button||0,$=T.event;return x.includes($)?f($,A,N.x,N.y):m($,A,N.x,N.y,B)}function g(){var v;let T=document.activeElement;for(;(v=T.shadowRoot)!=null&&v.activeElement;)T=T.shadowRoot.activeElement;return T}function y(T){T.events.map(v=>{try{return h(v,T)}catch{return}}).filter(Boolean).forEach(v=>{T.element.dispatchEvent(v),r(T,v),n(T,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}var I={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!I.element){a("element not found");return}c(I.element),l(I.element);try{y(I);let T=g(),v=I.quirks,x=v==null?void 0:v.isReactSelect,A=v==null?void 0:v.isCKEditorFrame;!x&&!A&&dispatchFocus(s.elementToFocusLocatedElement,T),i()}catch(T){a(T.toString())}};mg.exports=KP});var gg=C((PD,hg)=>{"use strict";var zP=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(T){e({status:"done",result:T,success:!0})}function i(T){T=T||{},e({status:"failed",result:T,success:!1})}function a(T){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),T.dispatchEvent(v)}function c(T){let v={},x=T.getBoundingClientRect(),A=x.left+x.width/2,N=x.top+x.height/2,k=f("mousemove",v,A,N,0);T.dispatchEvent(k)}function l(T,v){function x(k,E,P){return P>k&&P<E}let A=T.pointerPosition||{};if(I.isDrag)return{x:A.originX||0,y:A.originY||0};let N=v.getBoundingClientRect(),B=A.originX&&x(N.left,N.left+N.width,A.originX)?A.originX:N.left+N.width/2,$=A.originY&&x(N.top,N.top+N.height,A.originY)?A.originY:N.top+N.height/2;return{x:B,y:$}}function u(T,v,x){return{screenX:0,screenY:0,clientX:v,clientY:x,ctrlKey:Boolean(T.ctrl),altKey:Boolean(T.alt),shiftKey:Boolean(T.shift),metaKey:Boolean(T.meta),bubbles:!0,cancelable:!0,composed:!0}}function p(T,v,x,A,N){if(r){let $=u(v,x,A);return $.pointerType="mouse",$.isPrimary=!0,new window.PointerEvent(T,$)}let B=document.createEvent("PointerEvent");return B.initPointerEvent(T,!0,!0,document.defaultView,1,0,0,x,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),N,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),B}function f(T,v,x,A,N){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(T,!0,!0,document.defaultView,1,0,0,x,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),N,document.body?document.body.parentNode:document.documentElement),B}function m(T,v){let x=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},N=l(T,v.element),B=v.button||0,$=T.event;return x.includes($)?p($,A,N.x,N.y,B):f($,A,N.x,N.y,B)}function h(T,v){function x(){return T.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return x()}function g(T,v,x){try{let A=m(v.events[T],v);h(A,v)||v.element.dispatchEvent(A)}catch{}if(T+1===v.events.length)x();else{let A=Math.min(v.events[T+1].timeStamp-v.events[T].timeStamp,n);setTimeout(()=>{g(T+1,v,x)},A)}}function y(T,v){g(0,T,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let I={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!I.element){i("element not found");return}a(I.element),c(I.element),y(I,()=>{o()})};hg.exports=zP});var wg=C((kD,yg)=>{"use strict";var JP=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),o=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),l.dataTransfer=r,a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")};yg.exports=JP});var Tg=C((AD,bg)=>{"use strict";var XP=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(k){e({status:"done",result:k,success:!0})}function a(k){k=k||{},e({status:"failed",result:k,success:!1,keep:!0})}function c(k){return k!=null&&k.toLowerCase?(k=k.toLowerCase(),k==="text"?"text/plain":k==="url"?"text/uri-list":k):k}function l(){try{return new DataTransfer}catch{return{data:{},setData(E,P){o[c(E)]=P},getData(E){return o[c(E)]}}}}let u=["drag","dragstart","dragend"],p=["pointerup","pointerdown","pointermove"],f=u.concat(["drop","dragenter","dragover"]);function m(k){let E=k;for(;E&&E!==document.documentElement;){if(E.draggable)return E;E=E.parentElement}return null}function h(k,E,P){let j=E.element,z=P.dispatchDragEventsOnClosestDraggable;if(u.includes(k.type)&&z){if(!j&&E.lastDraggedElement)return E.lastDraggedElement;let X=m(j);if(X)return E.lastDraggedElement=X,X}return j}function g(k,E,P){function j(Bt,R,O){return O>Bt&&O<R}let z=k.pointerPosition||{};if(E)return{x:z.originX||0,y:z.originY||0};let X=P.getBoundingClientRect(),oe=z.originX&&j(X.left,X.left+X.width,z.originX)?z.originX:X.left+X.width/2,Me=z.originY&&j(X.top,X.top+X.height,z.originY)?z.originY:X.top+X.height/2;return{x:oe,y:Me}}function y(k,E,P){let j=(E==null?void 0:E.modifiers)||{},z=g(k,P.isDrag,P.element),X=(E==null?void 0:E.button)||0,oe=k.event;return p.includes(oe)?I(oe,j,z.x,z.y,X):f.includes(oe)?v(oe,j,z.x,z.y,X):T(oe,j,z.x,z.y,X)}function b(k,E,P){return{screenX:0,screenY:0,clientX:E,clientY:P,ctrlKey:Boolean(k.ctrl),altKey:Boolean(k.alt),shiftKey:Boolean(k.shift),metaKey:Boolean(k.meta),bubbles:!0,cancelable:!0,composed:!0}}function I(k,E,P,j,z){if(n){let oe=b(E,P,j);return oe.pointerType="mouse",oe.isPrimary=!0,new window.PointerEvent(k,oe)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(k,!0,!0,document.defaultView,1,0,0,P,j,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function T(k,E,P,j,z){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(k,!0,!0,document.defaultView,1,0,0,P,j,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),z,document.body?document.body.parentNode:document.documentElement),X}function v(k,E,P,j){if(k==="dragstart"&&(window.TSTA||(window.TSTA={}),window.TSTA.dataTransfer=l()),!r){let oe=document.createEvent("CustomEvent");return oe.initCustomEvent(k,!0,!0,null),oe.dataTransfer=window.TSTA.dataTransfer,oe}let z=b(E,P,j),X=new window.DragEvent(k,z);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function x(k,E,P){let j=h(k,E,P);j&&j.dispatchEvent(k)}function A(k,E){function P(){return k.event==="click"&&E.isDrag&&!E.allEventsOnSameElement}return P()}function N(k,E,P){if(P){let j=Math.min(P.timeStamp-E.timeStamp,40);setTimeout(()=>{B(k)},j)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function B(k){let E,P=k.events[k.eventIndex],j=k.events[++k.eventIndex];try{k.element=getLocatedElement(P.locatedElement),E=y(P,s,k)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(A(P,k))return N(k,P,j);if(E)try{x(E,k,P)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${P.event}`);N(k,P,j)}let $={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{B($)}catch(k){a(k)}},0)};bg.exports=XP});var Ig=C((_D,Sg)=>{"use strict";var Al=require("lodash"),YP=re(),QP=fg(),Eg=qo(),ZP=gg(),ek=wg(),tk=Tg(),{featureFlagsService:vg}=(le(),w(me)),_l=class extends YP{getDnDRectsAndOffsets(e,t,r,n){let o=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.xOffset,fromY:o.yOffset,toRect:t.rectWithoutFrameOffset,toX:i.xOffset,toY:i.yOffset}}async clickJs(){var c;let e=this.step,t=this.context,r=t.data[e.targetId||"targetId"],n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return;let i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},a=`
377
+ `;try{let u=await this.driver.executeJSWithArray(l,[r,e,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop]);if(!(u!=null&&u.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:f,actualY:m}=u.value;return p?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,f,m)}}}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,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}};mg.exports=Al});var gg=C((PD,hg)=>{"use strict";var zP=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(T,v){var L;function x(B){function $(P){return o(P).find(j=>Array.apply(null,j.classList||[]).includes("Select-control"))}function k(P){let j=$(P);return j?j.querySelector("INPUT"):null}let E=k(B);E&&E.focus()}let A=(L=T.quirks)==null?void 0:L.isReactSelect;v.type==="mousedown"&&A&&x(T.element)}function n(T,v){var A;let x=(A=T.quirks)==null?void 0:A.isCKEditorFrame;v.type==="click"&&x&&document.body.focus()}function o(T){return T?[T].concat(o(T.parentNode)):[]}function i(T){let v={status:"done",result:T,success:!0};I.isNonTextableElemnet&&(v.reason="Set text on non input element"),e(v)}function a(T){T=T||{},e({status:"failed",result:T,success:!1})}function c(T){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),T.dispatchEvent(v)}function l(T){let v={},x=T.getBoundingClientRect(),A=x.left+x.width/2,L=x.top+x.height/2,k=m("mousemove",v,A,L,0);T.dispatchEvent(k)}function u(T,v){function x(k,E,P){return P>k&&P<E}let A=T.pointerPosition||{},L=v.getBoundingClientRect(),B=A.originX&&x(L.left,L.left+L.width,A.originX)?A.originX:L.left+L.width/2,$=A.originY&&x(L.top,L.top+L.height,A.originY)?A.originY:L.top+L.height/2;return{x:B,y:$}}function p(T,v,x){return{screenX:0,screenY:0,clientX:v,clientY:x,ctrlKey:Boolean(T.ctrl),altKey:Boolean(T.alt),shiftKey:Boolean(T.shift),metaKey:Boolean(T.meta),bubbles:!0,cancelable:!0,composed:!0}}function f(T,v,x,A){if(!window.PointerEvent)return;let L=p(v,x,A);return L.pointerType="mouse",L.isPrimary=!0,new window.PointerEvent(T,L)}function m(T,v,x,A,L){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(T,!0,!0,document.defaultView,1,0,0,x,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),B}function h(T,v){let x=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},L=u(T,v.element),B=v.button||0,$=T.event;return x.includes($)?f($,A,L.x,L.y):m($,A,L.x,L.y,B)}function g(){var v;let T=document.activeElement;for(;(v=T.shadowRoot)!=null&&v.activeElement;)T=T.shadowRoot.activeElement;return T}function w(T){T.events.map(v=>{try{return h(v,T)}catch{return}}).filter(Boolean).forEach(v=>{T.element.dispatchEvent(v),r(T,v),n(T,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}var I={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!I.element){a("element not found");return}c(I.element),l(I.element);try{w(I);let T=g(),v=I.quirks,x=v==null?void 0:v.isReactSelect,A=v==null?void 0:v.isCKEditorFrame;!x&&!A&&dispatchFocus(s.elementToFocusLocatedElement,T),i()}catch(T){a(T.toString())}};hg.exports=zP});var wg=C((kD,yg)=>{"use strict";var JP=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(T){e({status:"done",result:T,success:!0})}function i(T){T=T||{},e({status:"failed",result:T,success:!1})}function a(T){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),T.dispatchEvent(v)}function c(T){let v={},x=T.getBoundingClientRect(),A=x.left+x.width/2,L=x.top+x.height/2,k=f("mousemove",v,A,L,0);T.dispatchEvent(k)}function l(T,v){function x(k,E,P){return P>k&&P<E}let A=T.pointerPosition||{};if(I.isDrag)return{x:A.originX||0,y:A.originY||0};let L=v.getBoundingClientRect(),B=A.originX&&x(L.left,L.left+L.width,A.originX)?A.originX:L.left+L.width/2,$=A.originY&&x(L.top,L.top+L.height,A.originY)?A.originY:L.top+L.height/2;return{x:B,y:$}}function u(T,v,x){return{screenX:0,screenY:0,clientX:v,clientY:x,ctrlKey:Boolean(T.ctrl),altKey:Boolean(T.alt),shiftKey:Boolean(T.shift),metaKey:Boolean(T.meta),bubbles:!0,cancelable:!0,composed:!0}}function p(T,v,x,A,L){if(r){let $=u(v,x,A);return $.pointerType="mouse",$.isPrimary=!0,new window.PointerEvent(T,$)}let B=document.createEvent("PointerEvent");return B.initPointerEvent(T,!0,!0,document.defaultView,1,0,0,x,A,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),B}function f(T,v,x,A,L){let B=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return B.initMouseEvent(T,!0,!0,document.defaultView,1,0,0,x,A,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),L,document.body?document.body.parentNode:document.documentElement),B}function m(T,v){let x=["pointerup","pointerdown","pointermove"],A=v.modifiers||{},L=l(T,v.element),B=v.button||0,$=T.event;return x.includes($)?p($,A,L.x,L.y,B):f($,A,L.x,L.y,B)}function h(T,v){function x(){return T.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return x()}function g(T,v,x){try{let A=m(v.events[T],v);h(A,v)||v.element.dispatchEvent(A)}catch{}if(T+1===v.events.length)x();else{let A=Math.min(v.events[T+1].timeStamp-v.events[T].timeStamp,n);setTimeout(()=>{g(T+1,v,x)},A)}}function w(T,v){g(0,T,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let I={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!I.element){i("element not found");return}a(I.element),c(I.element),w(I,()=>{o()})};yg.exports=JP});var Tg=C((AD,bg)=>{"use strict";var XP=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),o=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),l.dataTransfer=r,a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")};bg.exports=XP});var vg=C((_D,Eg)=>{"use strict";var YP=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(k){e({status:"done",result:k,success:!0})}function a(k){k=k||{},e({status:"failed",result:k,success:!1,keep:!0})}function c(k){return k!=null&&k.toLowerCase?(k=k.toLowerCase(),k==="text"?"text/plain":k==="url"?"text/uri-list":k):k}function l(){try{return new DataTransfer}catch{return{data:{},setData(E,P){o[c(E)]=P},getData(E){return o[c(E)]}}}}let u=["drag","dragstart","dragend"],p=["pointerup","pointerdown","pointermove"],f=u.concat(["drop","dragenter","dragover"]);function m(k){let E=k;for(;E&&E!==document.documentElement;){if(E.draggable)return E;E=E.parentElement}return null}function h(k,E,P){let j=E.element,z=P.dispatchDragEventsOnClosestDraggable;if(u.includes(k.type)&&z){if(!j&&E.lastDraggedElement)return E.lastDraggedElement;let X=m(j);if(X)return E.lastDraggedElement=X,X}return j}function g(k,E,P){function j(Bt,R,O){return O>Bt&&O<R}let z=k.pointerPosition||{};if(E)return{x:z.originX||0,y:z.originY||0};let X=P.getBoundingClientRect(),oe=z.originX&&j(X.left,X.left+X.width,z.originX)?z.originX:X.left+X.width/2,Me=z.originY&&j(X.top,X.top+X.height,z.originY)?z.originY:X.top+X.height/2;return{x:oe,y:Me}}function w(k,E,P){let j=(E==null?void 0:E.modifiers)||{},z=g(k,P.isDrag,P.element),X=(E==null?void 0:E.button)||0,oe=k.event;return p.includes(oe)?I(oe,j,z.x,z.y,X):f.includes(oe)?v(oe,j,z.x,z.y,X):T(oe,j,z.x,z.y,X)}function b(k,E,P){return{screenX:0,screenY:0,clientX:E,clientY:P,ctrlKey:Boolean(k.ctrl),altKey:Boolean(k.alt),shiftKey:Boolean(k.shift),metaKey:Boolean(k.meta),bubbles:!0,cancelable:!0,composed:!0}}function I(k,E,P,j,z){if(n){let oe=b(E,P,j);return oe.pointerType="mouse",oe.isPrimary=!0,new window.PointerEvent(k,oe)}let X=document.createEvent("PointerEvent");return X.initPointerEvent(k,!0,!0,document.defaultView,1,0,0,P,j,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),z,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),X}function T(k,E,P,j,z){let X=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return X.initMouseEvent(k,!0,!0,document.defaultView,1,0,0,P,j,Boolean(E.ctrl),Boolean(E.alt),Boolean(E.shift),Boolean(E.meta),z,document.body?document.body.parentNode:document.documentElement),X}function v(k,E,P,j){if(k==="dragstart"&&(window.TSTA||(window.TSTA={}),window.TSTA.dataTransfer=l()),!r){let oe=document.createEvent("CustomEvent");return oe.initCustomEvent(k,!0,!0,null),oe.dataTransfer=window.TSTA.dataTransfer,oe}let z=b(E,P,j),X=new window.DragEvent(k,z);return Object.defineProperties(X,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),X}function x(k,E,P){let j=h(k,E,P);j&&j.dispatchEvent(k)}function A(k,E){function P(){return k.event==="click"&&E.isDrag&&!E.allEventsOnSameElement}return P()}function L(k,E,P){if(P){let j=Math.min(P.timeStamp-E.timeStamp,40);setTimeout(()=>{B(k)},j)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function B(k){let E,P=k.events[k.eventIndex],j=k.events[++k.eventIndex];try{k.element=getLocatedElement(P.locatedElement),E=w(P,s,k)}catch(z){return a(`exception in get event in drag step:${z.message}`)}if(A(P,k))return L(k,P,j);if(E)try{x(E,k,P)}catch(z){return a(`exception in executeEvent in drag step:${z.message}`)}else return a(`cannot execute event ${P.event}`);L(k,P,j)}let $={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{B($)}catch(k){a(k)}},0)};Eg.exports=YP});var Rg=C((OD,xg)=>{"use strict";var _l=require("lodash"),QP=re(),ZP=gg(),Sg=qo(),ek=wg(),tk=Tg(),sk=vg(),{featureFlagsService:Ig}=(le(),y(me)),Ol=class extends QP{getDnDRectsAndOffsets(e,t,r,n){let o=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.xOffset,fromY:o.yOffset,toRect:t.rectWithoutFrameOffset,toX:i.xOffset,toY:i.yOffset}}async clickJs(){var c;let e=this.step,t=this.context,r=t.data[e.targetId||"targetId"],n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return;let i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},a=`
378
378
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
379
- var dispatchFocus = ${Eg.toString()};
380
- var doClick = ${QP.toString()};
379
+ var dispatchFocus = ${Sg.toString()};
380
+ var doClick = ${ZP.toString()};
381
381
  var eventData = arguments[0];
382
382
  var done = arguments[1];
383
383
  return doClick.call(null, eventData, done);
384
- `;try{return(c=(await this.driver.executeCodeAsync(a,n,i)).value)!=null&&c.success?{success:!0}:{success:!1}}catch(l){return{success:!1,reason:l.message,exception:l}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.context.data[this.step.targetId||"targetId"].rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),o=this.isWithinBounds(r.top,r.top+r.height,e.originY),i=n?0:r.left+r.width/2-e.originX,a=o?0:r.top+r.height/2-e.originY;return{xOffset:i,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=Al.cloneDeep(e);return r.event=t,r}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||{},r=this.step.events.find(o=>o.event==="mouseup")||t&&this.step.events.find(o=>o.event==="pointerup"),n=Al.findLastIndex(this.step.events,o=>o.event==="mousemove")||t&&Al.findLastIndex(this.step.events,o=>o.event==="pointermove");r&&n>0&&!this.step.allEventsOnSameElement&&this.step.events.splice(n+1,0,this.generateEventOfType(r,"mouseover")),this.step.isHTML5Drag&&!this.step.toElement&&(this.step.events=this.addDragendIfNeeded(this.step.events)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var c,l;let e=this.step,t=this.context,r=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:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button,isDrag:!0,allEventsOnSameElement:e.allEventsOnSameElement},a=`
384
+ `;try{return(c=(await this.driver.executeCodeAsync(a,n,i)).value)!=null&&c.success?{success:!0}:{success:!1}}catch(l){return{success:!1,reason:l.message,exception:l}}}isWithinBounds(e,t,r){return r>e&&r<t}getEventSequenceOffset(){var c;let e=(c=this.step.events[0])==null?void 0:c.pointerPosition;if(!e)return{xOffset:0,yOffset:0};let r=this.context.data[this.step.targetId||"targetId"].rectWithoutFrameOffset,n=this.isWithinBounds(r.left,r.left+r.width,e.originX),o=this.isWithinBounds(r.top,r.top+r.height,e.originY),i=n?0:r.left+r.width/2-e.originX,a=o?0:r.top+r.height/2-e.originY;return{xOffset:i,yOffset:a}}addOffsetToEvents(e){this.step.events.forEach(t=>{t!=null&&t.pointerPosition&&(t.pointerPosition.originX+=e.xOffset,t.pointerPosition.originY+=e.yOffset)})}generateEventOfType(e,t){let r=_l.cloneDeep(e);return r.event=t,r}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||{},r=this.step.events.find(o=>o.event==="mouseup")||t&&this.step.events.find(o=>o.event==="pointerup"),n=_l.findLastIndex(this.step.events,o=>o.event==="mousemove")||t&&_l.findLastIndex(this.step.events,o=>o.event==="pointermove");r&&n>0&&!this.step.allEventsOnSameElement&&this.step.events.splice(n+1,0,this.generateEventOfType(r,"mouseover")),this.step.isHTML5Drag&&!this.step.toElement&&(this.step.events=this.addDragendIfNeeded(this.step.events)),this.addOffsetToEvents(this.getEventSequenceOffset())}async dragPathJs(){var c,l;let e=this.step,t=this.context,r=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:r.isRoot,locatedElement:r.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 = ${Eg.toString()};
387
- var doDragPath = ${ZP.toString()};
386
+ var dispatchFocus = ${Sg.toString()};
387
+ var doDragPath = ${ek.toString()};
388
388
  return doDragPath.apply(null, arguments);
389
- `;try{return(l=(await this.driver.executeCodeAsync(a,n,i)).value)!=null&&l.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,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(vg.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 f={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,f,c)}if(this.step.isDrag){if(this.step.toElement){let f=this.context.data.toElement;if(this.step.isHTML5Drag){if(vg.flags.usePortedHtml5DragDrop.isEnabled()){let y=this.generateHTML5DragEventSequence(),b=this.context.data.timeToPlayStep+3e3,I=this.context.data[this.step.targetId||"targetId"],T={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=`
389
+ `;try{return(l=(await this.driver.executeCodeAsync(a,n,i)).value)!=null&&l.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,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(Ig.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 f={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,f,c)}if(this.step.isDrag){if(this.step.toElement){let f=this.context.data.toElement;if(this.step.isHTML5Drag){if(Ig.flags.usePortedHtml5DragDrop.isEnabled()){let w=this.generateHTML5DragEventSequence(),b=this.context.data.timeToPlayStep+3e3,I=this.context.data[this.step.targetId||"targetId"],T={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:w,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 = ${tk.toString()};
391
+ var dnd = ${sk.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,T)}let h=`
396
396
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
397
- var dnd = ${ek.toString()};
397
+ var dnd = ${tk.toString()};
398
398
  var eventData = arguments[0];
399
399
  return dnd.call(null, eventData);
400
- `,g={fromLocatedElement:t,toLocatedElement:f.locatedElement};return this.driver.executeJS(h,g)}let m=this.getDnDRectsAndOffsets(e,f,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,f.seleniumElement,m)}return this.dragPathJs()}let u=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||u)?this.clickJs():this.step.button===2?this.driver.rightClick(r,c):this.driver.leftClick(r,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(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else r.fireOnTarget=!0;return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>o.locatedElement=n(o)?r:t),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>n.dispatchDragEventsOnClosestDraggable=!0),r}};Sg.exports=_l});var Rg=C((OD,xg)=>{"use strict";var sk=re(),Ol=class extends sk{async performAction(e){let{step:t,context:r,frameHandler:n,sessionPlayerInit:{paramEvaluator:o,utils:i,commonConstants:a}}=this,c=this.getTarget();try{let l=await this.stepActionUtils.extractTargetText(c),u,p;if(o){let f=o.computeExpression(t.expression2,r,this.exportsGlobal,this.exportsTest);u=l,p=f.evaluatedText}else{let f=await e.executeStep(t.expression2,r,n,this.exportsGlobal,this.locateElementPlayer,this.exportsTest);u=l,p=f.evaluatedText}try{return i.compareOrMatch(p,u)?{success:!0}:{success:!1,errorType:a.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(p),actual:u}}}catch{return{success:!1,errorType:a.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:p.toString(),actual:u}}}}catch(l){return{success:!1,reason:l.message,exception:l,shouldRetry:!0}}}};xg.exports=Ol});var Pg=C((LD,Cg)=>{"use strict";var rk=require("lodash"),nk=re(),{getLogger:ok}=(U(),w(H)),ik=ok("evaluate-expression-step-action"),Ll=class extends nk{async execute(){let e=this.step,t=this.context,r=this.exportsGlobal,n=this.exportsTest;try{ik.info("runner running incoming params evaluation");let o=t.incomingParams||{};rk.isEmpty(o)&&(o=this.sessionPlayerInit.stepParamBuilder.getStepInputs(e,t,r,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),p=Function.apply(Function,i.concat([l])).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}}}};Cg.exports=Ll});var Ag=C((ND,kg)=>{"use strict";var ak=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){oe()},window.addEventListener("unload",window.__unloadNavigator);let o=["keydown","keyup","keypress"],i=15;function a(R){try{if(!t)return;let O=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return R.eventData&&(O.data=R.eventData.data),O}catch{}}function c(R){try{let O=document.createEvent("TextEvent");O.data=R.eventData.data;let D=1,V=R.eventData.locale||"en-US";return O.initTextEvent("textInput",!0,!0,window,R.eventData.data,D,V),O}catch{}}function l(R){return a(R)||c()}function u(R,O,D){try{return new KeyboardEvent(R,{bubbles:!0,cancelable:!0,location:O.location||0,key:O.key||"",ctrlKey:Boolean(D.ctrl),shiftKey:Boolean(D.shift),altKey:Boolean(D.alt),metaKey:Boolean(D.meta)})}catch{}}function p(R,O,D){try{let V=document.createEvent("KeyboardEvent");return V.initKeyEvent(R,!0,!0,null,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),O.key||"",0),V}catch{}}function f(R,O,D){try{let V=document.createEvent("Events");return V.initEvent(R,!0,!0),V.altKey=Boolean(D.alt),V.ctrlKey=Boolean(D.ctrl),V.metaKey=Boolean(D.meta),V.shiftKey=Boolean(D.shift),V.keyCode=O.key||"",V}catch{}}function m(R,O,D){return u(R,O,D)||p(R,O,D)||f(R,O,D)}function h(R){let O=o.indexOf(R.event);if(typeof O!="number"||O<0)return null;let D=R.eventData,V=D.modifiers||{},ie=m(R.event,D,V);return Object.defineProperties(ie,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),ie._keyCode_=D.keyCode,ie._charCode_=D.charCode||0,ie}function g(R){return R.event==="textInput"?l(R):h(R)}function y(R,O){return function(){var V;return R.event==="textInput"&&!((V=O.quirks)!=null&&V.isAuth0Form)}()}function b(R,O){return R.event==="keyup"&&O.event==="keydown"?i:0}function I(R,O,D){let V=b(O,D);return Math.min(D.timeStamp-O.timeStamp,V)}function T(R){let O=Object.getOwnPropertyDescriptor(R,"value");if(!O)return;let D=R.value;R.value=`${D}#`,O.configurable&&delete R.value,R.value=D;let V=document.createEvent("HTMLEvents");V.initEvent("input",!0,!1),R.dispatchEvent(V),Object.defineProperty(R,"value",O)}function v(R){if(R.isInput)try{if(T(R.element),t)R.element.dispatchEvent(new Event("change"));else{let O=document.createEvent("HTMLEvents");O.initEvent("change",!1,!0),R.element.dispatchEvent(O)}}catch{}}function x(R,O,D){D?setTimeout(()=>{E(R)},I(R,O,D)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(R),oe())}function A(R,O){return(R==="change"||R==="blur")&&O.element.tagName==="OPTION"}function N(R,O,D){return A(R.type,O)?O.element.parentElement:D.locatedElement?getLocatedElement(D.locatedElement):O.element}function B(R,O){let D=R.firstChild,V;for(;D;){if(D.nodeType===3){if(O.offset--<=0)return D}else if(D.nodeType===1&&(V=B(D,O),V))return V;D=D.nextSibling}return null}function $(R,O){if(!(!R||!O)){if(!isNaN(O.start))R.selectionStart=O.start,R.selectionEnd=O.end;else if(!isNaN(O.nodeOffset)){let D;if(R.firstChild?D=B(R,{offset:O.nodeOffset}):D=R,D){let V=window.getSelection(),ie=document.createRange();try{V.removeAllRanges(),ie.setStart(D,O.textOffset),ie.setEnd(D,O.textOffset),V.addRange(ie)}catch{}}}}}function k(R,O,D){if(O.isFocusable&&O.isSelectable(R)&&R.type!=="submit")try{$(O.element,D.eventData.selection)}catch{}let V=N(R,O,D);if(!V)throw new Error("could not find element");R.type==="submit"&&V.action?V.submit():V.dispatchEvent(R)}function E(R){let O,D=R.events[R.eventIndex],V=R.events[++R.eventIndex];try{O=g(D)}catch(ie){return Me(`exception in get event in text step:${ie.message}`)}if(y(D,R))return x(R,D,V);if(O)try{k(O,R,D)}catch(ie){return Me(`exception in executeEvent in text step:${ie.message}`)}else if(R.noEventExecuter)R.noEventExecuter(R,D);else return Me(`cannot execute event ${D.event}`);x(R,D,V)}function P(R){let O=R.tagName;return O==="INPUT"||O==="TEXTAREA"}function j(R){return R.getAttribute?Boolean(R.getAttribute("contenteditable")==="true"):!1}function z(R,O){if(R.isInput){R.element.value=O.eventData.text;let D=document.createEvent("Event");D.initEvent("input",!0,!1),R.element.dispatchEvent(D)}else R.isContentEditable&&(R.element.innerHTML=O.eventData.text)}function X(){var O;let R=document.activeElement;for(;(O=R.shadowRoot)!=null&&O.activeElement;)R=R.shadowRoot.activeElement;return R}function oe(R){let O={status:"done",result:R,success:!0};n.isNonTextableElemnet&&(O.reason="Set text on non input element"),e(O)}function Me(R){R=R||{};let O={status:"failed",result:R,success:!1};n.isNonTextableElemnet&&(O.reason="Set text on non input element"),e(O)}try{n.isInput=P(n.element),n.isContentEditable=j(n.element),!n.isInput&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=n.isInput||n.isContentEditable,n.isSelectable=function(R){return R.type!=="keyup"},n.noEventExecuter=z}catch(R){Me(`exception in set text step:${R.message}`);return}let Bt=X();dispatchFocus(s.elementToFocusLocatedElement,Bt),E(n)};kg.exports=ak});var Og=C((DD,_g)=>{"use strict";var ck=re(),lk=Ag(),uk=qo(),{extractElementId:Nl,delay:dk}=(M(),w(q)),Dl=class extends ck{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Nl(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var u;let e=this.step,t=this.context,r=t.data[e.targetId||"targetId"],n=t.data.timeToPlayStep+3e3,o=e.events,{setTextDraftJs:i}=this.sessionPlayerInit.codeSnippets;if(r.isDraftEditor&&i)return this.driver.executeJS(i(r.locatedElement,t.stepText));if(!(o!=null&&o.length))return;let a={eventType:e.type,events:o,quirks:e.quirks,locatedElement:r.locatedElement,isRoot:r.isRoot,elementToFocusLocatedElement:r.elementToFocusLocatedElement},c=`
400
+ `,g={fromLocatedElement:t,toLocatedElement:f.locatedElement};return this.driver.executeJS(h,g)}let m=this.getDnDRectsAndOffsets(e,f,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,f.seleniumElement,m)}return this.dragPathJs()}let u=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||u)?this.clickJs():this.step.button===2?this.driver.rightClick(r,c):this.driver.leftClick(r,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(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else r.fireOnTarget=!0;return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>o.locatedElement=n(o)?r:t),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>n.dispatchDragEventsOnClosestDraggable=!0),r}};xg.exports=Ol});var Pg=C((ND,Cg)=>{"use strict";var rk=re(),Nl=class extends rk{async performAction(e){let{step:t,context:r,frameHandler:n,sessionPlayerInit:{paramEvaluator:o,utils:i,commonConstants:a}}=this,c=this.getTarget();try{let l=await this.stepActionUtils.extractTargetText(c),u,p;if(o){let f=o.computeExpression(t.expression2,r,this.exportsGlobal,this.exportsTest);u=l,p=f.evaluatedText}else{let f=await e.executeStep(t.expression2,r,n,this.exportsGlobal,this.locateElementPlayer,this.exportsTest);u=l,p=f.evaluatedText}try{return i.compareOrMatch(p,u)?{success:!0}:{success:!1,errorType:a.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(p),actual:u}}}catch{return{success:!1,errorType:a.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:p.toString(),actual:u}}}}catch(l){return{success:!1,reason:l.message,exception:l,shouldRetry:!0}}}};Cg.exports=Nl});var Ag=C((LD,kg)=>{"use strict";var nk=require("lodash"),ok=re(),{getLogger:ik}=(U(),y(H)),ak=ik("evaluate-expression-step-action"),Ll=class extends ok{async execute(){let e=this.step,t=this.context,r=this.exportsGlobal,n=this.exportsTest;try{ak.info("runner running incoming params evaluation");let o=t.incomingParams||{};nk.isEmpty(o)&&(o=this.sessionPlayerInit.stepParamBuilder.getStepInputs(e,t,r,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),p=Function.apply(Function,i.concat([l])).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}}}};kg.exports=Ll});var Og=C((DD,_g)=>{"use strict";var ck=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){oe()},window.addEventListener("unload",window.__unloadNavigator);let o=["keydown","keyup","keypress"],i=15;function a(R){try{if(!t)return;let O=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return R.eventData&&(O.data=R.eventData.data),O}catch{}}function c(R){try{let O=document.createEvent("TextEvent");O.data=R.eventData.data;let D=1,V=R.eventData.locale||"en-US";return O.initTextEvent("textInput",!0,!0,window,R.eventData.data,D,V),O}catch{}}function l(R){return a(R)||c()}function u(R,O,D){try{return new KeyboardEvent(R,{bubbles:!0,cancelable:!0,location:O.location||0,key:O.key||"",ctrlKey:Boolean(D.ctrl),shiftKey:Boolean(D.shift),altKey:Boolean(D.alt),metaKey:Boolean(D.meta)})}catch{}}function p(R,O,D){try{let V=document.createEvent("KeyboardEvent");return V.initKeyEvent(R,!0,!0,null,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),O.key||"",0),V}catch{}}function f(R,O,D){try{let V=document.createEvent("Events");return V.initEvent(R,!0,!0),V.altKey=Boolean(D.alt),V.ctrlKey=Boolean(D.ctrl),V.metaKey=Boolean(D.meta),V.shiftKey=Boolean(D.shift),V.keyCode=O.key||"",V}catch{}}function m(R,O,D){return u(R,O,D)||p(R,O,D)||f(R,O,D)}function h(R){let O=o.indexOf(R.event);if(typeof O!="number"||O<0)return null;let D=R.eventData,V=D.modifiers||{},ie=m(R.event,D,V);return Object.defineProperties(ie,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),ie._keyCode_=D.keyCode,ie._charCode_=D.charCode||0,ie}function g(R){return R.event==="textInput"?l(R):h(R)}function w(R,O){return function(){var V;return R.event==="textInput"&&!((V=O.quirks)!=null&&V.isAuth0Form)}()}function b(R,O){return R.event==="keyup"&&O.event==="keydown"?i:0}function I(R,O,D){let V=b(O,D);return Math.min(D.timeStamp-O.timeStamp,V)}function T(R){let O=Object.getOwnPropertyDescriptor(R,"value");if(!O)return;let D=R.value;R.value=`${D}#`,O.configurable&&delete R.value,R.value=D;let V=document.createEvent("HTMLEvents");V.initEvent("input",!0,!1),R.dispatchEvent(V),Object.defineProperty(R,"value",O)}function v(R){if(R.isInput)try{if(T(R.element),t)R.element.dispatchEvent(new Event("change"));else{let O=document.createEvent("HTMLEvents");O.initEvent("change",!1,!0),R.element.dispatchEvent(O)}}catch{}}function x(R,O,D){D?setTimeout(()=>{E(R)},I(R,O,D)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(R),oe())}function A(R,O){return(R==="change"||R==="blur")&&O.element.tagName==="OPTION"}function L(R,O,D){return A(R.type,O)?O.element.parentElement:D.locatedElement?getLocatedElement(D.locatedElement):O.element}function B(R,O){let D=R.firstChild,V;for(;D;){if(D.nodeType===3){if(O.offset--<=0)return D}else if(D.nodeType===1&&(V=B(D,O),V))return V;D=D.nextSibling}return null}function $(R,O){if(!(!R||!O)){if(!isNaN(O.start))R.selectionStart=O.start,R.selectionEnd=O.end;else if(!isNaN(O.nodeOffset)){let D;if(R.firstChild?D=B(R,{offset:O.nodeOffset}):D=R,D){let V=window.getSelection(),ie=document.createRange();try{V.removeAllRanges(),ie.setStart(D,O.textOffset),ie.setEnd(D,O.textOffset),V.addRange(ie)}catch{}}}}}function k(R,O,D){if(O.isFocusable&&O.isSelectable(R)&&R.type!=="submit")try{$(O.element,D.eventData.selection)}catch{}let V=L(R,O,D);if(!V)throw new Error("could not find element");R.type==="submit"&&V.action?V.submit():V.dispatchEvent(R)}function E(R){let O,D=R.events[R.eventIndex],V=R.events[++R.eventIndex];try{O=g(D)}catch(ie){return Me(`exception in get event in text step:${ie.message}`)}if(w(D,R))return x(R,D,V);if(O)try{k(O,R,D)}catch(ie){return Me(`exception in executeEvent in text step:${ie.message}`)}else if(R.noEventExecuter)R.noEventExecuter(R,D);else return Me(`cannot execute event ${D.event}`);x(R,D,V)}function P(R){let O=R.tagName;return O==="INPUT"||O==="TEXTAREA"}function j(R){return R.getAttribute?Boolean(R.getAttribute("contenteditable")==="true"):!1}function z(R,O){if(R.isInput){R.element.value=O.eventData.text;let D=document.createEvent("Event");D.initEvent("input",!0,!1),R.element.dispatchEvent(D)}else R.isContentEditable&&(R.element.innerHTML=O.eventData.text)}function X(){var O;let R=document.activeElement;for(;(O=R.shadowRoot)!=null&&O.activeElement;)R=R.shadowRoot.activeElement;return R}function oe(R){let O={status:"done",result:R,success:!0};n.isNonTextableElemnet&&(O.reason="Set text on non input element"),e(O)}function Me(R){R=R||{};let O={status:"failed",result:R,success:!1};n.isNonTextableElemnet&&(O.reason="Set text on non input element"),e(O)}try{n.isInput=P(n.element),n.isContentEditable=j(n.element),!n.isInput&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=n.isInput||n.isContentEditable,n.isSelectable=function(R){return R.type!=="keyup"},n.noEventExecuter=z}catch(R){Me(`exception in set text step:${R.message}`);return}let Bt=X();dispatchFocus(s.elementToFocusLocatedElement,Bt),E(n)};_g.exports=ck});var Lg=C((MD,Ng)=>{"use strict";var lk=re(),uk=Og(),dk=qo(),{extractElementId:Dl,delay:pk}=(M(),y(q)),Ml=class extends lk{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Dl(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var u;let e=this.step,t=this.context,r=t.data[e.targetId||"targetId"],n=t.data.timeToPlayStep+3e3,o=e.events,{setTextDraftJs:i}=this.sessionPlayerInit.codeSnippets;if(r.isDraftEditor&&i)return this.driver.executeJS(i(r.locatedElement,t.stepText));if(!(o!=null&&o.length))return;let a={eventType:e.type,events:o,quirks:e.quirks,locatedElement:r.locatedElement,isRoot:r.isRoot,elementToFocusLocatedElement:r.elementToFocusLocatedElement},c=`
401
401
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
402
- var dispatchFocus = ${uk};
403
- var setText = ${lk.toString()};
402
+ var dispatchFocus = ${dk};
403
+ var setText = ${uk.toString()};
404
404
  var eventData = arguments[0];
405
405
  var done = arguments[1];
406
406
  return setText.call(null, eventData, done);
407
- `,l=await this.driver.executeCodeAsync(c,n,a);return{success:Boolean((u=l.value)==null?void 0:u.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Nl(t.seleniumElement),e[r]),r<e.length-1&&await dk(this.step.delayBetweenChars)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Nl(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;if(this.step.appendText){if(this.step.nativeEvents)return this.setValueAppendNative();let{stepResult:r}=this.sessionPlayerInit.commonConstants;return{success:!1,errorType:r.TEXT_ACTION_FAILURE,resultInfo:{error:"'Append Text' is only supported in Native Mode"}}}return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}};_g.exports=Dl});var Ng=C((MD,Lg)=>{"use strict";var pk=function(s,e){var u;function t(p,f){let m=`data-testim-${p}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let y=JSON.parse(window.sessionStorage.getItem(m)||"{}"),b=Object.assign({},y,f);window.sessionStorage.setItem(m,JSON.stringify(b))}catch(y){let b=y.message.toLowerCase().includes("quota"),I=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||b||I){let T=document.head.querySelector("#testim-storage-backup");T||(T=document.createElement("meta"),T.id="testim-storage-backup",document.head.append(T));let v=JSON.parse(T.getAttribute(m)||"{}"),x=Object.assign({},v,f);if(T.setAttribute(m,JSON.stringify(x)),b||I){try{window.sessionStorage.removeItem(m)}catch{}(window.TSTA=window.TSTA||{}).useFallbackStorage=!0}return}throw y}}function r(p){return p.function?p.function.args.map(f=>f!=null&&f.locatedElement?getLocatedElement(f.locatedElement):f):p.directParams.map(f=>f.selector?document.querySelector(f.selector):f.value).concat(p.otherParams)}function n(p,f){function m(){return p.apply(this,f)}return m.prototype=p.prototype,new m}let o={},i={},a={},c=s.functionParams,l=s.transactionId;try{let p=r(s);p.push(o,i,a);let f=((u=s.function)==null?void 0:u.params)||c,h=(e||n(Function,f)).apply(null,p);typeof Promise<"u"&&h instanceof Promise?(t(l,{type:"promise"}),h.then(g=>{t(l,{status:"done",success:!0,result:{resultValue:g,exports:o,exportsTest:i,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})}catch(p){t(l,{status:"failed",success:!1,result:{resultValue:p.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}};Lg.exports=pk});var Ho=C((FD,Mg)=>{"use strict";var Dg=require("lodash"),mk=(M(),w(q)),fk=re(),hk=(M(),w(q)),gk=Ng(),{getLogger:yk}=(U(),w(H)),{featureFlagsService:Ml}=(le(),w(me)),Fl=yk("base-js-step-action"),Ul=class extends fk{isExceedingMaxResultSize(e,t){try{let r=t.project.defaults.enforceMaximumJsResultSize,n=Ml.flags.maximumJsResultSize.getValue(),o=JSON.stringify(e).length>n;return r?o:(o&&Fl.warn(`js result size exceeded ${n}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(e){return this.driver.executeJS(t=>{let r=`data-testim-${t}`;try{return window.sessionStorage.getItem(r)}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(r):"{}"}throw n}},e)}constructJSFunParams(e){let t=e.incomingParams,r=["context",...t.as.functionParameters,"exports","exportsTest","exportsGlobal"],n=[e.context,...t.as.functionArguments];return r.push(e.code),n.forEach(o=>{Dg.isObject(o)&&hk.removePropertyFromObject(o,"seleniumElement",Dg.isEqual)}),{function:{params:r,args:n},transactionId:e.transactionId,browser:e.browser,browserMajor:e.browserMajor}}checkStatus(e){let t=this,r=t.context.config.retryTimeout,n=t.context.data.timeToPlayStep-r;async function o(){let i;try{i=await t.executeGetStatus(e)}catch(l){Fl.warn("failed to get js status",{err:l}),i={value:{status:"exception"}}}let a;try{a=JSON.parse(i?i.value:"{}")}catch{Fl.warn("non object value",{selRes:i}),a={status:"exception"}}let c=t.stepActionUtils.abortedSteps.find(l=>l.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-r<=0?Object.assign(a,{success:!1,shouldRetry:!0}):(n-=r,await mk.delay(r),o()):{success:!0})}return o()}executeInAut(e){let t=Ml.flags.experimentalPreCodeCompilation.isEnabled(),r=Ml.flags.experimentalAsyncCustomCode.isEnabled(),n=this.constructJSFunParams(e),o=n.function.args.some(l=>Boolean(l==null?void 0:l.locatedElement)),i="undefined";if(t){let l=n.function.params.slice(0,-1);i=r?`async function(${l.join(",")}) {
407
+ `,l=await this.driver.executeCodeAsync(c,n,a);return{success:Boolean((u=l.value)==null?void 0:u.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Dl(t.seleniumElement),e[r]),r<e.length-1&&await pk(this.step.delayBetweenChars)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Dl(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;if(this.step.appendText){if(this.step.nativeEvents)return this.setValueAppendNative();let{stepResult:r}=this.sessionPlayerInit.commonConstants;return{success:!1,errorType:r.TEXT_ACTION_FAILURE,resultInfo:{error:"'Append Text' is only supported in Native Mode"}}}return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}};Ng.exports=Ml});var Mg=C((FD,Dg)=>{"use strict";var mk=function(s,e){var u;function t(p,f){let m=`data-testim-${p}`,h="Native sessionStorage is not available";function g(w){return w!=null&&w.toString?w.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let w=JSON.parse(window.sessionStorage.getItem(m)||"{}"),b=Object.assign({},w,f);window.sessionStorage.setItem(m,JSON.stringify(b))}catch(w){let b=w.message.toLowerCase().includes("quota"),I=w.message===h;if(w.message.includes("sessionStorage")||w.message.includes("The operation is insecure")||b||I){let T=document.head.querySelector("#testim-storage-backup");T||(T=document.createElement("meta"),T.id="testim-storage-backup",document.head.append(T));let v=JSON.parse(T.getAttribute(m)||"{}"),x=Object.assign({},v,f);if(T.setAttribute(m,JSON.stringify(x)),b||I){try{window.sessionStorage.removeItem(m)}catch{}(window.TSTA=window.TSTA||{}).useFallbackStorage=!0}return}throw w}}function r(p){return p.function?p.function.args.map(f=>f!=null&&f.locatedElement?getLocatedElement(f.locatedElement):f):p.directParams.map(f=>f.selector?document.querySelector(f.selector):f.value).concat(p.otherParams)}function n(p,f){function m(){return p.apply(this,f)}return m.prototype=p.prototype,new m}let o={},i={},a={},c=s.functionParams,l=s.transactionId;try{let p=r(s);p.push(o,i,a);let f=((u=s.function)==null?void 0:u.params)||c,h=(e||n(Function,f)).apply(null,p);typeof Promise<"u"&&h instanceof Promise?(t(l,{type:"promise"}),h.then(g=>{t(l,{status:"done",success:!0,result:{resultValue:g,exports:o,exportsTest:i,exportsGlobal:a}})},g=>{t(l,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})}catch(p){t(l,{status:"failed",success:!1,result:{resultValue:p.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}};Dg.exports=mk});var Ho=C((UD,Ug)=>{"use strict";var Fg=require("lodash"),fk=(M(),y(q)),hk=re(),gk=(M(),y(q)),yk=Mg(),{getLogger:wk}=(U(),y(H)),{featureFlagsService:Fl}=(le(),y(me)),Ul=wk("base-js-step-action"),ql=class extends hk{isExceedingMaxResultSize(e,t){try{let r=t.project.defaults.enforceMaximumJsResultSize,n=Fl.flags.maximumJsResultSize.getValue(),o=JSON.stringify(e).length>n;return r?o:(o&&Ul.warn(`js result size exceeded ${n}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(e){return this.driver.executeJS(t=>{let r=`data-testim-${t}`;try{return window.sessionStorage.getItem(r)}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(r):"{}"}throw n}},e)}constructJSFunParams(e){let t=e.incomingParams,r=["context",...t.as.functionParameters,"exports","exportsTest","exportsGlobal"],n=[e.context,...t.as.functionArguments];return r.push(e.code),n.forEach(o=>{Fg.isObject(o)&&gk.removePropertyFromObject(o,"seleniumElement",Fg.isEqual)}),{function:{params:r,args:n},transactionId:e.transactionId,browser:e.browser,browserMajor:e.browserMajor}}checkStatus(e){let t=this,r=t.context.config.retryTimeout,n=t.context.data.timeToPlayStep-r;async function o(){let i;try{i=await t.executeGetStatus(e)}catch(l){Ul.warn("failed to get js status",{err:l}),i={value:{status:"exception"}}}let a;try{a=JSON.parse(i?i.value:"{}")}catch{Ul.warn("non object value",{selRes:i}),a={status:"exception"}}let c=t.stepActionUtils.abortedSteps.find(l=>l.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-r<=0?Object.assign(a,{success:!1,shouldRetry:!0}):(n-=r,await fk.delay(r),o()):{success:!0})}return o()}executeInAut(e){let t=Fl.flags.experimentalPreCodeCompilation.isEnabled(),r=Fl.flags.experimentalAsyncCustomCode.isEnabled(),n=this.constructJSFunParams(e),o=n.function.args.some(l=>Boolean(l==null?void 0:l.locatedElement)),i="undefined";if(t){let l=n.function.params.slice(0,-1);i=r?`async function(${l.join(",")}) {
408
408
  ${e.code}
409
409
  };`:`function(${l.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 = ${gk.toString()};
413
+ var runCode = ${yk.toString()};
414
414
  var eventData = arguments[0];
415
415
  var funcToRun = ${i};
416
416
  return runCode.call(null, eventData, funcToRun);
417
417
  `;return t?this.driver.executeJS(c,n).catch(l=>this.handleExecutionError(l)):this.driver.executeJS(c,n)}codeExecDone(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants,{context:r}=this,{result:n={},tstConsoleLogs:o,nodeVersion:i,navigateToDifferentDomain:a}=e;n.exports&&(r.data.exports=n.exports);let c={nodeVersion:i,tstConsoleLogs:o,data:r.data};return this.isFailedResult(n.resultValue)?Object.assign(c,{success:!1,errorType:t.JS_ASSERTION_FAILED}):this.isExceedingMaxResultSize({result:n,tstConsoleLogs:o},r)?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:r}=this;if(e.type==="promise")return Promise.resolve({data:r.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:r.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 r={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(r,{browser:n.browser,browserMajor:n.browserMajor}),this.context.isPendingPromise||await this.executeInAut(r);let o=await this.checkStatus(r.transactionId);return await this.checkCodeResponse(o)}handleExecutionError(e){if((e==null?void 0:e.seleniumStack)&&e.seleniumStack.type==="JavaScriptError"&&e.seleniumStack.orgStatusMessage){let r=e.seleniumStack.orgStatusMessage.indexOf(`
418
- Build info`),n=e.seleniumStack.orgStatusMessage.slice(0,r===-1?void 0:r);throw new Error(n)}throw e}};Mg.exports=Ul});var Ug=C((UD,Fg)=>{"use strict";var wk=Ho(),ql=class extends wk{isFailedResult(e){return e===!1}};Fg.exports=ql});var jg=C((qD,qg)=>{"use strict";var bk=Ho(),jl=class extends bk{isFailedResult(e){return!e}};qg.exports=jl});var Bg=C((jD,$g)=>{"use strict";var{extractElementId:Tk}=(M(),w(q)),Ek=re(),vk={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"},$l=class extends Ek{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Tk(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(vk[t]),this.setWithValueApi(e)}};$g.exports=$l});var Gg=C(($D,Wg)=>{"use strict";Wg.exports=function(s,e){function t(r,n){let o=Element.prototype.matches,i=o&&isNativeFunction(o)?o:document.createElement(r.tagName).__proto__.matches;do{if(i.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(i=>{let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}).forEach(i=>{if(e){n.dispatchEvent(i);return}r.dispatchEvent(i)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}});var Hg=C((BD,Vg)=>{"use strict";var Sk=re(),Ik=Gg(),{extractElementId:xk}=(M(),w(q)),{featureFlagsService:Rk}=(le(),w(me)),Bl=class extends Sk{async performAction(){var p,f;let e=this.context.data[this.step.targetId||"targetId"],{seleniumElement:t,locatedElement:r}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((p=this.step.element)==null?void 0:p.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(xk(t))}catch(m){if(!m.message.includes("Cannot check the displayedness of a non-Element argument"))throw m}let c=Rk.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),l=`
418
+ Build info`),n=e.seleniumStack.orgStatusMessage.slice(0,r===-1?void 0:r);throw new Error(n)}throw e}};Ug.exports=ql});var jg=C((qD,qg)=>{"use strict";var bk=Ho(),jl=class extends bk{isFailedResult(e){return e===!1}};qg.exports=jl});var Bg=C((jD,$g)=>{"use strict";var Tk=Ho(),$l=class extends Tk{isFailedResult(e){return!e}};$g.exports=$l});var Gg=C(($D,Wg)=>{"use strict";var{extractElementId:Ek}=(M(),y(q)),vk=re(),Sk={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"},Bl=class extends vk{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Ek(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(Sk[t]),this.setWithValueApi(e)}};Wg.exports=Bl});var Hg=C((BD,Vg)=>{"use strict";Vg.exports=function(s,e){function t(r,n){let o=Element.prototype.matches,i=o&&isNativeFunction(o)?o:document.createElement(r.tagName).__proto__.matches;do{if(i.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(i=>{let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}).forEach(i=>{if(e){n.dispatchEvent(i);return}r.dispatchEvent(i)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}});var zg=C((WD,Kg)=>{"use strict";var Ik=re(),xk=Hg(),{extractElementId:Rk}=(M(),y(q)),{featureFlagsService:Ck}=(le(),y(me)),Wl=class extends Ik{async performAction(){var p,f;let e=this.context.data[this.step.targetId||"targetId"],{seleniumElement:t,locatedElement:r}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((p=this.step.element)==null?void 0:p.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(Rk(t))}catch(m){if(!m.message.includes("Cannot check the displayedness of a non-Element argument"))throw m}let c=Ck.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),l=`
419
419
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
420
420
  var isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
421
- var selectOption = ${Ik.toString()};
421
+ var selectOption = ${xk.toString()};
422
422
  return selectOption.apply(null, arguments);
423
- `;return(f=(await this.driver.executeJSWithArray(l,[r,c])).value)!=null&&f.success?{success:!0}:{success:!1}}};Vg.exports=Bl});var zg=C((WD,Kg)=>{"use strict";var Ck=re(),Wl=class extends Ck{async performAction(){await this.driver.submitForm(this.getTarget().seleniumElement)}};Kg.exports=Wl});var Xg=C((GD,Jg)=>{"use strict";var Pk=re(),kk=(s,e,t,r)=>({x:t,y:r,width:e,height:s,get top(){return this.y},get left(){return this.x},get right(){return this.x+this.width},get bottom(){return this.y+this.height},toJSON(){}}),Gl=class extends Pk{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:o,height:i}=n,a=o/2,c=i/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:p,y:f}=l;this.sessionPlayerInit.utils.isWithinTargetRect(kk(i,o,0,0),p,f)&&(a=p,c=f)}let u={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,u),{success:!0}}};Jg.exports=Gl});var Qg=C((VD,Yg)=>{"use strict";var Ak=function(s,e){function r(a,c){function l(h,g,y){return y>h&&y<g}let u=a.pointerPosition||{},p=c.getBoundingClientRect(),f=u.originX&&l(p.left,p.left+p.width,u.originX)?u.originX:p.left+p.width/2,m=u.originY&&l(p.top,p.top+p.height,u.originY)?u.originY:p.top+p.height/2;return{x:f,y:m}}function n(a,c,l){let u=r(a,l),p=(c==null?void 0:c.modifiers)||{},f={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:u.x,clientY:u.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",f)}function o(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),u=n(l,s.eventData,c),p=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(u),setTimeout(()=>{o(a,c)},p)}let i=getLocatedElement(s.locatedElement);o(s.events,i)};Yg.exports=Ak});var ey=C((HD,Zg)=>{"use strict";var _k=re(),Ok=Qg(),Vl=class extends _k{async performAction(){var c;let e=this.step,t=this.context,r=e.events;if(!(r!=null&&r.length))return;let n={events:r,eventData:{modifiers:e.modifiers,button:e.button},locatedElement:this.getTarget().locatedElement},o=t.data.timeToPlayStep+3e3,i=`
423
+ `;return(f=(await this.driver.executeJSWithArray(l,[r,c])).value)!=null&&f.success?{success:!0}:{success:!1}}};Kg.exports=Wl});var Xg=C((GD,Jg)=>{"use strict";var Pk=re(),Gl=class extends Pk{async performAction(){await this.driver.submitForm(this.getTarget().seleniumElement)}};Jg.exports=Gl});var Qg=C((VD,Yg)=>{"use strict";var kk=re(),Ak=(s,e,t,r)=>({x:t,y:r,width:e,height:s,get top(){return this.y},get left(){return this.x},get right(){return this.x+this.width},get bottom(){return this.y+this.height},toJSON(){}}),Vl=class extends kk{getRect(){return this.driver.isFirefox()?this.getTarget().rectWithoutFrameOffset:this.getTarget().rect}async performAction(){let e=this.getTarget(),{seleniumElement:t,rectWithoutFrameOffset:r,rect:n}=e,{width:o,height:i}=n,a=o/2,c=i/2,l=this.step.element.clickOffset;if(l&&this.step.shouldAccountForMouseOffsetInHover){let{x:p,y:f}=l;this.sessionPlayerInit.utils.isWithinTargetRect(Ak(i,o,0,0),p,f)&&(a=p,c=f)}let u={frameOffset:{x:n.left-r.left,y:n.top-r.top},rect:r,clickOffset:{x:Math.floor(a),y:Math.floor(c)}};return await this.driver.hover(t,u),{success:!0}}};Yg.exports=Vl});var ey=C((HD,Zg)=>{"use strict";var _k=function(s,e){function r(a,c){function l(h,g,w){return w>h&&w<g}let u=a.pointerPosition||{},p=c.getBoundingClientRect(),f=u.originX&&l(p.left,p.left+p.width,u.originX)?u.originX:p.left+p.width/2,m=u.originY&&l(p.top,p.top+p.height,u.originY)?u.originY:p.top+p.height/2;return{x:f,y:m}}function n(a,c,l){let u=r(a,l),p=(c==null?void 0:c.modifiers)||{},f={deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ,deltaMode:a.deltaMode,clientX:u.x,clientY:u.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",f)}function o(a,c){if(a.length===0){e({state:"success"});return}if(!c)throw new Error("element not found");let l=a.shift(),u=n(l,s.eventData,c),p=a[0]?Math.min(a[0].timeStamp-l.timeStamp,200):200;c.dispatchEvent(u),setTimeout(()=>{o(a,c)},p)}let i=getLocatedElement(s.locatedElement);o(s.events,i)};Zg.exports=_k});var sy=C((KD,ty)=>{"use strict";var Ok=re(),Nk=ey(),Hl=class extends Ok{async performAction(){var c;let e=this.step,t=this.context,r=e.events;if(!(r!=null&&r.length))return;let n={events:r,eventData:{modifiers:e.modifiers,button:e.button},locatedElement:this.getTarget().locatedElement},o=t.data.timeToPlayStep+3e3,i=`
424
424
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
425
- var wheel = ${Ok.toString()};
425
+ var wheel = ${Nk.toString()};
426
426
  var eventData = arguments[0];
427
427
  var done = arguments[1];
428
428
  return wheel.call(null, eventData, done);
429
- `;return{success:((c=(await this.driver.executeCodeAsync(i,o,n)).value)==null?void 0:c.state)==="success"}}};Zg.exports=Vl});var sy=C((KD,ty)=>{"use strict";var Lk=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let i=-1,a=0,c=[],l={waitOn(){let u=++i;return function(p){u in c||(c[u]=p,a++,e.length===a&&l.endWithCallback(c))}},endWith(u){l.endWithCallback=u}};return l}function n(i,a,c){let l=new XMLHttpRequest;l.open("GET",i),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let o=r();e.forEach(i=>{n(i.url,i.name,o.waitOn())}),o.endWith(i=>{let a=createDropEvent(i);t.dispatchEvent(a)})};ty.exports=Lk});var ny=C((zD,ry)=>{"use strict";var Nk=re(),Dk=sy(),{getLogger:Mk}=(U(),w(H)),{featureFlagsService:Fk}=(le(),w(me)),Uk=Mk("drop-file-step-action"),Hl=class extends Nk{async performAction(){let{codeSnippets:e,utils:t}=this.sessionPlayerInit,r=this.context.data[this.step.targetId||"targetId"],n=Fk.flags.overrideAzureStorageUrl.isEnabled(),o=await t.addTokenToFileUrl(this.context.project.id,this.step.fileUrls,this.stepActionUtils.testimServicesApi,n,Uk),i=`
429
+ `;return{success:((c=(await this.driver.executeCodeAsync(i,o,n)).value)==null?void 0:c.state)==="success"}}};ty.exports=Hl});var ny=C((zD,ry)=>{"use strict";var Lk=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let i=-1,a=0,c=[],l={waitOn(){let u=++i;return function(p){u in c||(c[u]=p,a++,e.length===a&&l.endWithCallback(c))}},endWith(u){l.endWithCallback=u}};return l}function n(i,a,c){let l=new XMLHttpRequest;l.open("GET",i),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let o=r();e.forEach(i=>{n(i.url,i.name,o.waitOn())}),o.endWith(i=>{let a=createDropEvent(i);t.dispatchEvent(a)})};ry.exports=Lk});var iy=C((JD,oy)=>{"use strict";var Dk=re(),Mk=ny(),{getLogger:Fk}=(U(),y(H)),{featureFlagsService:Uk}=(le(),y(me)),qk=Fk("drop-file-step-action"),Kl=class extends Dk{async performAction(){let{codeSnippets:e,utils:t}=this.sessionPlayerInit,r=this.context.data[this.step.targetId||"targetId"],n=Uk.flags.overrideAzureStorageUrl.isEnabled(),o=await t.addTokenToFileUrl(this.context.project.id,this.step.fileUrls,this.stepActionUtils.testimServicesApi,n,qk),i=`
430
430
  var getLocatedElement = ${e.getLocatedElementCode};
431
431
  var createDropEvent = ${e.createDropEvent.toString()};
432
- var downloadFileAndFireDropEvent = ${Dk.toString()};
432
+ var downloadFileAndFireDropEvent = ${Mk.toString()};
433
433
  return downloadFileAndFireDropEvent.apply(null, arguments)
434
- `;return await this.driver.executeJSWithArray(i,[r.locatedElement,o])}};ry.exports=Hl});var ay=C((JD,iy)=>{"use strict";var qk=(rt(),w(ht)),jk=require("fs/promises"),$k=require("os"),{promiseMap:oy}=(M(),w(q)),{getLogger:Bk}=(U(),w(H)),Wk=Bk("input-file-utils");function Gk(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
434
+ `;return await this.driver.executeJSWithArray(i,[r.locatedElement,o])}};oy.exports=Kl});var ly=C((XD,cy)=>{"use strict";var jk=(rt(),y(ht)),$k=require("fs/promises"),Bk=require("os"),{promiseMap:ay}=(M(),y(q)),{getLogger:Wk}=(U(),y(H)),Gk=Wk("input-file-utils");function Vk(s={width:"2px",height:"2px",left:"0px",top:"400px"}){return`function getVisibleElement(locatedElement) {
435
435
  var input = getLocatedElement(locatedElement);
436
436
  if(input) {
437
437
  function parents(element, _elements) {
@@ -473,14 +473,14 @@ Build info`),n=e.seleniumStack.orgStatusMessage.slice(0,r===-1?void 0:r);throw n
473
473
  input.removeAttribute("disabled");
474
474
  input.focus();
475
475
  }
476
- }`}async function Vk(s,e){let t=null;try{t=(await qk.download(s)).body}catch(n){if(Wk.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${$k.tmpdir()}/${e}`;return await jk.writeFile(r,t),r}function Hk(s){return oy(s,e=>Vk(e.url,e.name))}function Kk(s,e){return e(s)}async function zk(s,e){let t=await Hk(s),r=await oy(t,n=>Kk(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}iy.exports={getVisibleElementScript:Gk,downloadFilesAndUploadToGrid:zk}});var uy=C((XD,ly)=>{"use strict";var Jk=re(),cy=ay(),{getLogger:Xk}=(U(),w(H)),{extractElementId:Yk,download:Qk}=(M(),w(q)),{featureFlagsService:Ko}=(le(),w(me)),zo=Xk("input-file-step-action"),Kl=class extends Jk{uploadFile(e){return this.driver.uploadFile(e)}forceInputToBeVisible(e,t){zo.info("workaround - stepaction - move element to visible position");let r=`
476
+ }`}async function Hk(s,e){let t=null;try{t=(await jk.download(s)).body}catch(n){if(Gk.error("failed to download input-file content",{err:{message:n.message,stack:n.stack,status:n.status}}),n.response)t=n.response.body;else throw n.cause?new Error(n.message):n}let r=`${Bk.tmpdir()}/${e}`;return await $k.writeFile(r,t),r}function Kk(s){return ay(s,e=>Hk(e.url,e.name))}function zk(s,e){return e(s)}async function Jk(s,e){let t=await Kk(s),r=await ay(t,n=>zk(n,e));return Array.isArray(r)&&r.map(n=>n==null?void 0:n.value)}cy.exports={getVisibleElementScript:Vk,downloadFilesAndUploadToGrid:Jk}});var py=C((YD,dy)=>{"use strict";var Xk=re(),uy=ly(),{getLogger:Yk}=(U(),y(H)),{extractElementId:Qk,download:Zk}=(M(),y(q)),{featureFlagsService:Ko}=(le(),y(me)),zo=Yk("input-file-step-action"),zl=class extends Xk{uploadFile(e){return this.driver.uploadFile(e)}forceInputToBeVisible(e,t){zo.info("workaround - stepaction - move element to visible position");let r=`
477
477
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
478
- var getVisibleElement = ${cy.getVisibleElementScript(t)};
478
+ var getVisibleElement = ${uy.getVisibleElementScript(t)};
479
479
  return getVisibleElement.apply(null, arguments);
480
- `;return this.driver.executeJS(r,e.locatedElement)}async safariPreUploadActions(e){let t={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(e,t)}catch(r){throw zo.error("failed to set input file in Safari recovery",{err:r}),r}}async uploadFilesAndForceVisibility(e,t){try{this.driver.isSafari()&&await this.safariPreUploadActions(t),await this.uploadFiles(e,t)}catch(r){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",l="invalid element state: Element is not currently interactable and may not be manipulated",u="Element must not be hidden, disabled or read-only",p="is not reachable by keyboard",f=r?r.message:"";if(f===l||f.startsWith(u)||f.startsWith(n)||f.startsWith(o)||f.startsWith(i)||f.includes(p)||f.includes(a)||f.includes(c)){await this.forceInputToBeVisible(t),await this.uploadFiles(e,t);return}throw zo.error("failed to set input file",{err:r}),r}}async uploadFiles(e,t){for(let r of e)await this.driver.elementIdValue(Yk(t.seleniumElement),r)}async performAction(){let e=this.context.data[this.step.targetId||"targetId"],t=Ko.flags.overrideAzureStorageUrl.isEnabled(),r=Ko.flags.useJsInputCodeInSafari.isEnabled(),n=Ko.flags.useJsInputCodeInFirefox.isEnabled(),o=Ko.flags.downloadToBase64.isEnabled(),i=await this.sessionPlayerInit.utils.addTokenToFileUrl(this.context.project.id,this.step.fileUrls,this.stepActionUtils.testimServicesApi,t,zo),a=this.driver.isSafari()&&(r||i.length>1),c=this.driver.isFirefox()&&(n||i.length>1);if(o&&(i=await Promise.all(i.map(async({name:u,url:p})=>{let f=await Qk(p);return{name:u,url:`data:${f.type};base64,${Buffer.from(f.body).toString("base64")}`}}))),a||c){await this.driver.executeJSWithArray(`
480
+ `;return this.driver.executeJS(r,e.locatedElement)}async safariPreUploadActions(e){let t={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(e,t)}catch(r){throw zo.error("failed to set input file in Safari recovery",{err:r}),r}}async uploadFilesAndForceVisibility(e,t){try{this.driver.isSafari()&&await this.safariPreUploadActions(t),await this.uploadFiles(e,t)}catch(r){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",l="invalid element state: Element is not currently interactable and may not be manipulated",u="Element must not be hidden, disabled or read-only",p="is not reachable by keyboard",f=r?r.message:"";if(f===l||f.startsWith(u)||f.startsWith(n)||f.startsWith(o)||f.startsWith(i)||f.includes(p)||f.includes(a)||f.includes(c)){await this.forceInputToBeVisible(t),await this.uploadFiles(e,t);return}throw zo.error("failed to set input file",{err:r}),r}}async uploadFiles(e,t){for(let r of e)await this.driver.elementIdValue(Qk(t.seleniumElement),r)}async performAction(){let e=this.context.data[this.step.targetId||"targetId"],t=Ko.flags.overrideAzureStorageUrl.isEnabled(),r=Ko.flags.useJsInputCodeInSafari.isEnabled(),n=Ko.flags.useJsInputCodeInFirefox.isEnabled(),o=Ko.flags.downloadToBase64.isEnabled(),i=await this.sessionPlayerInit.utils.addTokenToFileUrl(this.context.project.id,this.step.fileUrls,this.stepActionUtils.testimServicesApi,t,zo),a=this.driver.isSafari()&&(r||i.length>1),c=this.driver.isFirefox()&&(n||i.length>1);if(o&&(i=await Promise.all(i.map(async({name:u,url:p})=>{let f=await Zk(p);return{name:u,url:`data:${f.type};base64,${Buffer.from(f.body).toString("base64")}`}}))),a||c){await this.driver.executeJSWithArray(`
481
481
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
482
- const downloadAndUploadFile = ${Zk()};
483
- return downloadAndUploadFile.apply(null, arguments);`,[e.locatedElement,i]);return}let l=await cy.downloadFilesAndUploadToGrid(i,this.uploadFile.bind(this));await this.uploadFilesAndForceVisibility(l,e)}};ly.exports=Kl;function Zk(){return`async function downloadAndUpload(locatedElement, fileUrls) {
482
+ const downloadAndUploadFile = ${eA()};
483
+ return downloadAndUploadFile.apply(null, arguments);`,[e.locatedElement,i]);return}let l=await uy.downloadFilesAndUploadToGrid(i,this.uploadFile.bind(this));await this.uploadFilesAndForceVisibility(l,e)}};dy.exports=zl;function eA(){return`async function downloadAndUpload(locatedElement, fileUrls) {
484
484
  const fileIsNative = typeof window.File === 'function' && (window.File.toString().indexOf('native code') > -1);
485
485
  const File = fileIsNative ? window.File : (function obtainSafeGlobals() {
486
486
  const attachTo = document.body || document.documentElement;
@@ -557,15 +557,15 @@ Build info`),n=e.seleniumStack.orgStatusMessage.slice(0,r===-1?void 0:r);throw n
557
557
  element.dispatchEvent(new Event("change", { bubbles: true }));
558
558
  }
559
559
  element.removeEventListener("change", changeFiredHandler, true);
560
- }`}});var py=C((YD,dy)=>{"use strict";var eA=re(),zl=require("url"),Jl=class extends eA{async updateBaseUrl(e){let t=zl.parse(e),r=zl.parse(this.context.recordedBaseUrl),n=zl.parse(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}};dy.exports=Jl});var fy=C((QD,my)=>{"use strict";var tA=re(),{delay:sA}=(M(),w(q)),Xl=class extends tA{async performAction(){await sA(this.step.durationMS)}};my.exports=Xl});var gy=C((ZD,hy)=>{"use strict";var rA=re(),Yl=class extends rA{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}};hy.exports=Yl});var wy=C((eM,yy)=>{"use strict";var nA=re(),Ql=class extends nA{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return new Promise(r=>{t(e,r)})}async performAction(){let{commonConstants:e}=this.sessionPlayerInit,t=this.step,r=this.context,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:r.fileUrls},o;t.sendViaWebApp?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}}};yy.exports=Ql});var Ty=C((tM,by)=>{"use strict";var oA=re(),Zl=class extends oA{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}}};by.exports=Zl});var vy=C((sM,Ey)=>{"use strict";var iA=re(),{execute:aA}=Jo(),eu=class extends iA{async performAction(){return await aA(this.step,this.context,this.driver,this.stepActionUtils.testimServicesApi.authenticationManager.getLoggedUserInfo(),this.frameHandler.frameManager)}};Ey.exports=eu});var xy=C(Iy=>{"use strict";var zs=require("lodash"),{makeSDK:cA}=require("@applitools/eyes-sdk-core"),{W3C_ELEMENT_ID:Xo}=(Es(),w(Rn)),{getSessionPlayer:Sy}=(he(),w(Re)),{dependencies:lA}=Cn(),Yo="ELEMENT";function Mt(s){if(zs.has(s,"elementId"))return s.elementId;if(zs.has(s,Xo))return s[Xo];if(zs.has(s,Yo))return s[Yo]}var tu=class{isDriver(e){return Boolean((e==null?void 0:e.getPrototype)&&e.desiredCapabilities&&e.requestHandler)}isElement(e){if(!e)return!1;let t=e.value||e;return Boolean(t[Xo]||t[Yo])}isSelector(e){return typeof e=="string"}transformDriver(e){return new Proxy(e,{get:(t,r)=>{if(r!=="then")return Reflect.get(t,r)}})}transformElement(e){let t=Mt(e.value||e);return{[Xo]:t,[Yo]:t}}transformSelector(e){return zs.has(e,"selector")?zs.has(e,"type")?e.type==="css"?`css selector:${e.selector}`:`${e.type}:${e.selector}`:e.selector:e}extractSelector(e){return zs.has(e,"selector")?e.selector:void 0}isStaleElementError(e,t){if(!e)return!1;let r=e.originalError||e;return r instanceof Error?r.seleniumStack&&r.seleniumStack.type==="StaleElementReference":r.value&&r.selector&&r.selector===t}isEqualElements(e,t,r){if(!t||!r)return!1;let n=Mt(t),o=Mt(r);return n===o}async executeScript(e,t,r){let{value:n}=await e.execute(t,r);return n}async mainContext(e){return await e.frame(null),e}async parentContext(e){return await e.frameParent(),e}async childContext(e,t){return await e.frame(t),e}async findElement(e,t,r){let{value:n}=r?await e.elementIdElement(Mt(r),t):await e.element(t);return n}async findElements(e,t,r){let{value:n}=r?await e.elementIdElements(Mt(r),t):await e.elements(t);return n}async getWindowSize(e){let{value:t}=await e.windowHandleSize();return{width:t.width,height:t.height}}async setWindowSize(e,t){await e.windowHandlePosition({x:0,y:0}),await e.windowHandleSize(t)}async getDriverInfo(e){let t=e.desiredCapabilities;return{sessionId:e.requestHandler.sessionID||e.sessionId,isMobile:e.isMobile,isNative:e.isMobile&&!t.browserName,deviceName:t.deviceName,platformName:t.platformName||t.platform,platformVersion:t.platformVersion,browserName:t.browserName??t.name,browserVersion:t.browserVersion??t.version,pixelRatio:t.pixelRatio}}async getTitle(e){return e.getTitle()}async getUrl(e){return e.getUrl()}async visit(e,t){await e.url(t)}async takeScreenshot(e){return e.saveScreenshot()}async click(e,t){this.isSelector(t)&&(t=await this.findElement(e,t)),await e.elementIdClick(Mt(t))}async hover(e,t,r){this.isSelector(t)&&(t=await this.findElement(e,t)),await e.moveTo(Mt(t),r==null?void 0:r.x,r==null?void 0:r.y)}async type(e,t,r){this.isSelector(t)?t=await this.findElement(e,t):e.elementIdValue(Mt(t),r)}async scrollIntoView(e,t,r=!1){this.isSelector(t)&&(t=await this.findElement(e,t)),await e.execute("arguments[0].scrollIntoView(arguments[1])",t,r)}async waitUntilDisplayed(e,t,r){await e.waitForVisible(t,r)}},su=class{constructor(){let{EyeSdkBuilder:e}=Sy(),t=lA["@applitools/eyes-sdk-core"]||"N/A";this.sdk=cA({name:"Testim.io",version:`4.0.0/eyes-sdk-core/${t}`,spec:new tu}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=Sy(),i=await this.sdk.makeManager({type:e?"vg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}};Iy.eyeSdkService=new su});var ky=C((nM,Py)=>{"use strict";var uA=require("lodash"),dA=re(),{eyeSdkService:Ry}=xy(),{getLogger:pA}=(U(),w(H)),Cy=pA("pixel-validation-step-action"),ru=class extends dA{async performAction(){var u,p;let{shouldUseVisualGrid:e,applitoolsSdkConfig:t,applitoolsSdkLogger:r,testResultId:n}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((u=this.runContext.incomingParams)==null?void 0:u.final)||{},i=((p=t.batch)==null?void 0:p.id)||n,a=await Ry.getManager(e,this.context.config.applitoolsConcurrency||5,i,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},l;try{let f=await a.openEyes({driver:this.driver.client,config:t,logger:r}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};uA.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(h,o.applitoolsStepSettings),Cy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:h}),l={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){Cy.error("Applitools SDK step failed",{err:f,info:f.info}),l={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ry.handleApplitoolsSdkResult(this.context,l,this.step)}};Py.exports=ru});var ou=C((oM,Ay)=>{"use strict";var mA=(M(),w(q)),fA=Ho(),hA=fs(),nu=class extends fA{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o,id:i}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:u}=t,p={config:t.config,data:t.data},f=t.data.timeToPlayStep,m=await hA.runCodeWithPackages(o,i,a,p,c,l,u,f);return await this.checkCodeResponse(m)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof mA.TimeoutError?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}};Ay.exports=nu});var Oy=C((iM,_y)=>{"use strict";var gA=ou(),iu=class extends gA{isFailedResult(e){return e===!1}};_y.exports=iu});var Ny=C((aM,Ly)=>{"use strict";var yA=ou(),au=class extends yA{isFailedResult(e){return!e}};Ly.exports=au});var My=C((cM,Dy)=>{"use strict";var wA=re(),{NpmPackageError:bA}=(K(),w(Z)),TA=fs(),EA=(M(),w(q)),cu=class extends wA{async performAction(){let{context:e}=this,{stepId:t,packageData:r,resultId:n,retryIndex:o,stepResultId:i,timeToPlayBeforeExec:a}=e;try{return{data:await TA.installPackage(t,n,o,r,i,a),success:!0}}catch(c){return c instanceof bA?{success:!1,code:"invalid-node-package",message:c.message}:c instanceof EA.TimeoutError?{success:!1,code:"timeout"}:{success:!1,reason:c.message,exception:c}}}};Dy.exports=cu});var Uy=C((lM,Fy)=>{"use strict";var vA=re(),lu=class extends vA{async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}};Fy.exports=lu});var jy=C((uM,qy)=>{"use strict";var SA=re(),uu=class extends SA{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,(o,i)=>this.context.playback.sfdcAddLog(o,i));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}};qy.exports=uu});var By=C((dM,$y)=>{"use strict";var IA=re(),du=class extends IA{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,(o,i)=>this.context.playback.sfdcAddLog(o,i));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}};$y.exports=du});var fu=C((pM,Ky)=>{"use strict";var Hy=cg(),xA=pg(),RA=Ig(),Wy=Rg(),CA=Pg(),PA=Og(),Js=Ug(),pu=jg(),kA=Bg(),AA=Hg(),_A=zg(),OA=Xg(),LA=ey(),NA=ny(),DA=uy(),MA=py(),FA=fy(),UA=gy(),Gy=wy(),qA=Ty(),jA=vy(),Vy=ky(),tn=Oy(),$A=Ny(),BA=My(),mu=Uy(),Xe=jy(),WA=By();function GA(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}var VA={locate:Hy,scroll:xA,mouse:RA,submit:_A,text:PA,"special-key":kA,"user-code":Js,"validation-code-step":Js,"wait-for-code-step":Js,"action-code-step":Js,"condition-step":pu,"skip-code-step":pu,"element-code-step":pu,"evaluate-expression":CA,"text-validation":Wy,"wait-for-text-validation":Wy,"select-option":AA,"drop-file":NA,"input-file":DA,hover:OA,navigation:MA,wheel:LA,sleep:FA,refresh:UA,"api-validation":Gy,"api-action":Gy,"api-code-step":Js,"extract-text":qA,"simple-ui-verification":Vy,"wait-for-simple-ui-verification":Vy,"cli-validation-download-file":mu,"cli-wait-for-download-file":mu,"network-validation-step":mu,"cli-validation-code-step":tn,"cli-wait-for-code-step":tn,"cli-action-code-step":tn,"cli-api-code-step":tn,"cli-condition-step":$A,"node-package":BA,"email-code-step":Js,"cli-email-code-step":tn,"tdk-hybrid":jA,"sfdc-recorded-step":WA,"sfdc-step-login":Xe,"sfdc-step-logout":Xe,"sfdc-step-sobjectcreate":Xe,"sfdc-step-sobjectdelete":Xe,"sfdc-step-findrecord":Xe,"sfdc-step-quickaction":Xe,"sfdc-step-sobjectedit":Xe,"sfdc-step-sobjectvalidate":Xe,"sfdc-step-launchapp":Xe,"sfdc-step-closeconsoletabs":Xe,"sfdc-step-relatedlistaction":Xe};Ky.exports=function(s,e,t){GA(VA,e),e.registerLocateStepActionUtils&&e.registerLocateStepActionUtils(Hy.getUtils(s))}});var Qo=C((mM,Yy)=>{"use strict";var zy=(M(),w(q)),HA=Xr(),KA=rl(),zA=Vh(),JA=pl(),XA=Jh(),{testResultService:YA}=(Ks(),w(en)),Jy=bl(),QA=El(),{portSelector:ZA}=(Il(),w(Sl)),{isDebuggerConnected:e_}=(Rl(),w(xl)),{getSessionPlayer:Xy}=(he(),w(Re)),hu=class{constructor(e,t,r,n="code",o=new HA,i,a){let{sessionPlayer:c,commonConstants:l,stepActionFactory:u}=Xy();this.driver=o,this.id=e;let p=new JA(this.driver);this.stepActionFactory=new u(p),fu()(this.driver,this.stepActionFactory,"selenium"),this.tabService=this.driver.tabService||new zA(this.driver),this.driver.tabService=this.tabService,this.windowCreationListener=Jy,this.playbackTimeoutCalculator=new QA(e_()),this.tabService.createSesion(e);let f=XA(this.driver);this.sessionPlayer=new c(e,this.tabService,KA(this.driver),Jy,f,ZA,null,null,p,this.stepActionFactory,this.playbackTimeoutCalculator,YA.getSocket(),n),this.sessionPlayer.setShouldMonitorPerformance&&this.sessionPlayer.setShouldMonitorPerformance(r),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>{})}onDone(){let{commonConstants:e}=Xy(),t=1e3*60*2;return zy.promiseTimeout(this.driver.end(),t).catch(r=>{if(r instanceof zy.TimeoutError)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},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}};Yy.exports=hu});var gu={};W(gu,{buildCodeTests:()=>s_});async function t_(s,e,t,r,n){try{return await Qy(s,e,t,r,n)}catch(o){if((o==null?void 0:o.code)==="ENOENT")return Ft.compiler=null,Ft.webpackConfig=null,r&&(r.data={}),await Qy(s,e,t,r,n);throw o}}async function Qy(s,e={mode:"development"},t=void 0,r=void 0,n=void 0){let o=await ss("webpack"),i=Ut.cloneDeep(e);e.externals={testim:"__testim"},e.devtool||(e.devtool="inline-source-map"),e.plugins||(e.plugins=[]),e.plugins.push(new o.DefinePlugin(r_(t)),new o.DefinePlugin({"process.argv":JSON.stringify(process.argv)})),s=s.map(h=>Zo.resolve(h));let a=s.map(()=>Oe(30));if(e.optimization={minimize:!1},Number(process.versions.node.split(".")[0])>=17){let h=require("crypto"),g=h.createHash;h.createHash=(y,b)=>g(y==="md4"?"sha256":y,b)}e.entry=Object.fromEntries(Ut.zip(s,a).map(([h,g])=>[g,h])),e.output=Object.assign({devtoolModuleFilenameTemplate:h=>`file:///${h.absoluteResourcePath}`,filename:"[name].bundle.js"},e.output);let l;r?(Ut.isEqual(Ft.webpackConfig,i)&&Ft.compiler||(Ft.webpackConfig=i,Ft.compiler=o(e)),l=Ft.compiler):l=o(e);let u=r||new Zy.default;l.outputFileSystem=u;let p=Kt(h=>{n==null||n.addEventListener("abort",()=>{h(new hr,void 0)})});try{let h=await Promise.race([Kt(g=>l.run(g)),p]);if(h!=null&&h.hasErrors())throw new Error(h==null?void 0:h.toJson().errors.toString())}catch(h){let g=h.message.match(/Entry module not found: Error: Can't resolve '(.*)'/);throw g&&g.length===2?e.output&&e.output.library==="tdk"?new L(`Could not open dev-kit functions file in ${g[1]}`):new L(`Can't find test files in: '${g[1]}'`):new L(`Compilation Webpack Error in tests: ${h.message}`)}return{tests:[s.map((h,g)=>({code:u.readFileSync(Zo.resolve("./dist",`${a[g]}.bundle.js`)),name:h})).map(({code:h,name:g})=>({code:h.toString(),baseUrl:"",name:Zo.resolve(g),testConfig:{},testConfigId:null,testId:Oe(),resultId:Oe(),isTestsContainer:!0}))],runName:`Testim Dev Kit Run ${new Date().toLocaleString()}`}}function r_(s){let e=Ut.fromPairs(Object.keys(process.env).filter(r=>/^TDK_/i.test(r)||r==="BASE_URL").map(r=>[r,process.env[r]])),t={BASE_URL:s==null?void 0:s.baseUrl};return{"process.env":n_({...t,...e})}}function n_(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,JSON.stringify(t)]))}var Ut,Zo,Zy,Ft,s_,yu=F(()=>{"use strict";Ut=S(require("lodash")),Zo=S(require("path"));M();Zy=S(require("memory-fs"));K();Je();Ft={compiler:null,webpackConfig:null};s_=t_});var wu=C((exports,module)=>{"use strict";var _=require("lodash"),path=require("path"),fsPromises=require("fs/promises"),{AbortError}=(K(),w(Z)),{buildCodeTests}=(yu(),w(gu)),findTestFolder=_.memoize(async s=>(await fsPromises.readdir(s)).includes("tests")&&(await fsPromises.stat(path.join(s,"tests"))).isDirectory()?path.join(s,"tests"):s);async function getLocalLocators(){let folder=await findTestFolder(process.cwd()),locatorsFilePath=path.join(folder,"locators","locators.js");function parseLocators(buffer){return eval(buffer.toString().replace(/require/g,"(x => /locator.(.*).json/.exec(x)[1])"))}let locators=await fsPromises.readFile(locatorsFilePath).then(parseLocators,()=>({}));return Object.fromEntries(Object.keys(locators).map(s=>[s.replace(/"/g,'\\"'),locators[s]]))}async function findTests(s=process.cwd()){let e=await findTestFolder(s),t=await fsPromises.readdir(e,{withFileTypes:!0}),r=["webpack.config.js","tsconfig.js",".DS_Store","functions.js"],n=[".html",".json"];return t.filter(o=>!r.includes(o.name)&&!n.some(i=>o.name.endsWith(i))&&o.isFile()&&!o.name.startsWith(".")).map(o=>o.name)}async function promiseFromProps(s){let e=Object.entries(s),t=e.map(([,n])=>n),r=await Promise.all(t);for(let n=0;n<r.length;n++)e[n][1]=r[n];return Object.fromEntries(e)}async function getLocalLocatorContents(s,e=!1,t=process.cwd()){let r={};if(e){let n=await findTestFolder(t);for(let o of Object.values(s))r[o]=fsPromises.readFile(path.join(n,"locators",`locator.${o}.json`)).then(JSON.parse)}try{return await promiseFromProps(r)}catch(n){return console.error(n),{}}}async function saveTest({body:s,name:e,locators:t,language:r="javascript"}){let n=await findTestFolder(process.cwd()),o=path.join(n,"locators","locators.js"),i=path.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(r==="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 fsPromises.writeFile(i,s),await fsPromises.mkdir(path.join(n,"locators")).catch(()=>{});for(let{id:l,body:u}of t)await fsPromises.writeFile(path.join(n,"locators",`locator.${l}.json`),JSON.stringify(u));let a=Object.fromEntries(t.map(({name:l,id:u})=>[l,u])),c=await getLocalLocators();Object.assign(c,a),await writeLocators(o,c)}async function writeLocators(s,e){let t=`module.exports = {
560
+ }`}});var fy=C((QD,my)=>{"use strict";var tA=re(),Jl=require("url"),Xl=class extends tA{async updateBaseUrl(e){let t=Jl.parse(e),r=Jl.parse(this.context.recordedBaseUrl),n=Jl.parse(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}};my.exports=Xl});var gy=C((ZD,hy)=>{"use strict";var sA=re(),{delay:rA}=(M(),y(q)),Yl=class extends sA{async performAction(){await rA(this.step.durationMS)}};hy.exports=Yl});var wy=C((eM,yy)=>{"use strict";var nA=re(),Ql=class extends nA{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}};yy.exports=Ql});var Ty=C((tM,by)=>{"use strict";var oA=re(),Zl=class extends oA{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return new Promise(r=>{t(e,r)})}async performAction(){let{commonConstants:e}=this.sessionPlayerInit,t=this.step,r=this.context,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:r.fileUrls},o;t.sendViaWebApp?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}}};by.exports=Zl});var vy=C((sM,Ey)=>{"use strict";var iA=re(),eu=class extends iA{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}}};Ey.exports=eu});var Iy=C((rM,Sy)=>{"use strict";var aA=re(),{execute:cA}=Jo(),tu=class extends aA{async performAction(){return await cA(this.step,this.context,this.driver,this.stepActionUtils.testimServicesApi.authenticationManager.getLoggedUserInfo(),this.frameHandler.frameManager)}};Sy.exports=tu});var Cy=C(Ry=>{"use strict";var Js=require("lodash"),{makeSDK:lA}=require("@applitools/eyes-sdk-core"),{W3C_ELEMENT_ID:Xo}=(Es(),y(Pn)),{getSessionPlayer:xy}=(he(),y(Re)),{dependencies:uA}=kn(),Yo="ELEMENT";function Mt(s){if(Js.has(s,"elementId"))return s.elementId;if(Js.has(s,Xo))return s[Xo];if(Js.has(s,Yo))return s[Yo]}var su=class{isDriver(e){return Boolean((e==null?void 0:e.getPrototype)&&e.desiredCapabilities&&e.requestHandler)}isElement(e){if(!e)return!1;let t=e.value||e;return Boolean(t[Xo]||t[Yo])}isSelector(e){return typeof e=="string"}transformDriver(e){return new Proxy(e,{get:(t,r)=>{if(r!=="then")return Reflect.get(t,r)}})}transformElement(e){let t=Mt(e.value||e);return{[Xo]:t,[Yo]:t}}transformSelector(e){return Js.has(e,"selector")?Js.has(e,"type")?e.type==="css"?`css selector:${e.selector}`:`${e.type}:${e.selector}`:e.selector:e}extractSelector(e){return Js.has(e,"selector")?e.selector:void 0}isStaleElementError(e,t){if(!e)return!1;let r=e.originalError||e;return r instanceof Error?r.seleniumStack&&r.seleniumStack.type==="StaleElementReference":r.value&&r.selector&&r.selector===t}isEqualElements(e,t,r){if(!t||!r)return!1;let n=Mt(t),o=Mt(r);return n===o}async executeScript(e,t,r){let{value:n}=await e.execute(t,r);return n}async mainContext(e){return await e.frame(null),e}async parentContext(e){return await e.frameParent(),e}async childContext(e,t){return await e.frame(t),e}async findElement(e,t,r){let{value:n}=r?await e.elementIdElement(Mt(r),t):await e.element(t);return n}async findElements(e,t,r){let{value:n}=r?await e.elementIdElements(Mt(r),t):await e.elements(t);return n}async getWindowSize(e){let{value:t}=await e.windowHandleSize();return{width:t.width,height:t.height}}async setWindowSize(e,t){await e.windowHandlePosition({x:0,y:0}),await e.windowHandleSize(t)}async getDriverInfo(e){let t=e.desiredCapabilities;return{sessionId:e.requestHandler.sessionID||e.sessionId,isMobile:e.isMobile,isNative:e.isMobile&&!t.browserName,deviceName:t.deviceName,platformName:t.platformName||t.platform,platformVersion:t.platformVersion,browserName:t.browserName??t.name,browserVersion:t.browserVersion??t.version,pixelRatio:t.pixelRatio}}async getTitle(e){return e.getTitle()}async getUrl(e){return e.getUrl()}async visit(e,t){await e.url(t)}async takeScreenshot(e){return e.saveScreenshot()}async click(e,t){this.isSelector(t)&&(t=await this.findElement(e,t)),await e.elementIdClick(Mt(t))}async hover(e,t,r){this.isSelector(t)&&(t=await this.findElement(e,t)),await e.moveTo(Mt(t),r==null?void 0:r.x,r==null?void 0:r.y)}async type(e,t,r){this.isSelector(t)?t=await this.findElement(e,t):e.elementIdValue(Mt(t),r)}async scrollIntoView(e,t,r=!1){this.isSelector(t)&&(t=await this.findElement(e,t)),await e.execute("arguments[0].scrollIntoView(arguments[1])",t,r)}async waitUntilDisplayed(e,t,r){await e.waitForVisible(t,r)}},ru=class{constructor(){let{EyeSdkBuilder:e}=xy(),t=uA["@applitools/eyes-sdk-core"]||"N/A";this.sdk=lA({name:"Testim.io",version:`4.0.0/eyes-sdk-core/${t}`,spec:new su}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=xy(),i=await this.sdk.makeManager({type:e?"vg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}};Ry.eyeSdkService=new ru});var _y=C((oM,Ay)=>{"use strict";var dA=require("lodash"),pA=re(),{eyeSdkService:Py}=Cy(),{getLogger:mA}=(U(),y(H)),ky=mA("pixel-validation-step-action"),nu=class extends pA{async performAction(){var u,p;let{shouldUseVisualGrid:e,applitoolsSdkConfig:t,applitoolsSdkLogger:r,testResultId:n}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((u=this.runContext.incomingParams)==null?void 0:u.final)||{},i=((p=t.batch)==null?void 0:p.id)||n,a=await Py.getManager(e,this.context.config.applitoolsConcurrency||5,i,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},l;try{let f=await a.openEyes({driver:this.driver.client,config:t,logger:r}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};dA.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(h,o.applitoolsStepSettings),ky.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:h}),l={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){ky.error("Applitools SDK step failed",{err:f,info:f.info}),l={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Py.handleApplitoolsSdkResult(this.context,l,this.step)}};Ay.exports=nu});var iu=C((iM,Oy)=>{"use strict";var fA=(M(),y(q)),hA=Ho(),gA=fs(),ou=class extends hA{async executeCliCode(){var h,g,w;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((w=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:w.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o,id:i}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:u}=t,p={config:t.config,data:t.data},f=t.data.timeToPlayStep,m=await gA.runCodeWithPackages(o,i,a,p,c,l,u,f);return await this.checkCodeResponse(m)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof fA.TimeoutError?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}};Oy.exports=ou});var Ly=C((aM,Ny)=>{"use strict";var yA=iu(),au=class extends yA{isFailedResult(e){return e===!1}};Ny.exports=au});var My=C((cM,Dy)=>{"use strict";var wA=iu(),cu=class extends wA{isFailedResult(e){return!e}};Dy.exports=cu});var Uy=C((lM,Fy)=>{"use strict";var bA=re(),{NpmPackageError:TA}=(K(),y(Z)),EA=fs(),vA=(M(),y(q)),lu=class extends bA{async performAction(){let{context:e}=this,{stepId:t,packageData:r,resultId:n,retryIndex:o,stepResultId:i,timeToPlayBeforeExec:a}=e;try{return{data:await EA.installPackage(t,n,o,r,i,a),success:!0}}catch(c){return c instanceof TA?{success:!1,code:"invalid-node-package",message:c.message}:c instanceof vA.TimeoutError?{success:!1,code:"timeout"}:{success:!1,reason:c.message,exception:c}}}};Fy.exports=lu});var jy=C((uM,qy)=>{"use strict";var SA=re(),uu=class extends SA{async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}};qy.exports=uu});var By=C((dM,$y)=>{"use strict";var IA=re(),du=class extends IA{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}};$y.exports=du});var Gy=C((pM,Wy)=>{"use strict";var xA=re(),pu=class extends xA{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}};Wy.exports=pu});var hu=C((mM,Jy)=>{"use strict";var zy=ug(),RA=fg(),CA=Rg(),Vy=Pg(),PA=Ag(),kA=Lg(),Xs=jg(),mu=Bg(),AA=Gg(),_A=zg(),OA=Xg(),NA=Qg(),LA=sy(),DA=iy(),MA=py(),FA=fy(),UA=gy(),qA=wy(),Hy=Ty(),jA=vy(),$A=Iy(),Ky=_y(),rn=Ly(),BA=My(),WA=Uy(),fu=jy(),Ke=By(),GA=Gy();function VA(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}var HA={locate:zy,scroll:RA,mouse:CA,submit:OA,text:kA,"special-key":AA,"user-code":Xs,"validation-code-step":Xs,"wait-for-code-step":Xs,"action-code-step":Xs,"condition-step":mu,"skip-code-step":mu,"element-code-step":mu,"evaluate-expression":PA,"text-validation":Vy,"wait-for-text-validation":Vy,"select-option":_A,"drop-file":DA,"input-file":MA,hover:NA,navigation:FA,wheel:LA,sleep:UA,refresh:qA,"api-validation":Hy,"api-action":Hy,"api-code-step":Xs,"extract-text":jA,"simple-ui-verification":Ky,"wait-for-simple-ui-verification":Ky,"cli-validation-download-file":fu,"cli-wait-for-download-file":fu,"network-validation-step":fu,"cli-validation-code-step":rn,"cli-wait-for-code-step":rn,"cli-action-code-step":rn,"cli-api-code-step":rn,"cli-condition-step":BA,"node-package":WA,"email-code-step":Xs,"cli-email-code-step":rn,"tdk-hybrid":$A,"sfdc-recorded-step":GA,"sfdc-step-login":Ke,"sfdc-step-loginas":Ke,"sfdc-step-logout":Ke,"sfdc-step-sobjectcreate":Ke,"sfdc-step-sobjectdelete":Ke,"sfdc-step-findrecord":Ke,"sfdc-step-quickaction":Ke,"sfdc-step-sobjectedit":Ke,"sfdc-step-sobjectvalidate":Ke,"sfdc-step-launchapp":Ke,"sfdc-step-closeconsoletabs":Ke,"sfdc-step-relatedlistaction":Ke};Jy.exports=function(s,e,t){VA(HA,e),e.registerLocateStepActionUtils&&e.registerLocateStepActionUtils(zy.getUtils(s))}});var Qo=C((fM,Zy)=>{"use strict";var Xy=(M(),y(q)),KA=Qr(),zA=nl(),JA=Kh(),XA=ml(),YA=Yh(),{testResultService:QA}=(zs(),y(sn)),Yy=Tl(),ZA=vl(),{portSelector:e_}=(xl(),y(Il)),{isDebuggerConnected:t_}=(Cl(),y(Rl)),{getSessionPlayer:Qy}=(he(),y(Re)),gu=class{constructor(e,t,r,n="code",o=new KA,i,a){let{sessionPlayer:c,commonConstants:l,stepActionFactory:u}=Qy();this.driver=o,this.id=e;let p=new XA(this.driver);this.stepActionFactory=new u(p),hu()(this.driver,this.stepActionFactory,"selenium"),this.tabService=this.driver.tabService||new JA(this.driver),this.driver.tabService=this.tabService,this.windowCreationListener=Yy,this.playbackTimeoutCalculator=new ZA(t_()),this.tabService.createSesion(e);let f=YA(this.driver);this.sessionPlayer=new c(e,this.tabService,zA(this.driver),Yy,f,e_,null,null,p,this.stepActionFactory,this.playbackTimeoutCalculator,QA.getSocket(),n),this.sessionPlayer.setShouldMonitorPerformance&&this.sessionPlayer.setShouldMonitorPerformance(r),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>{})}onDone(){let{commonConstants:e}=Qy(),t=1e3*60*2;return Xy.promiseTimeout(this.driver.end(),t).catch(r=>{if(r instanceof Xy.TimeoutError)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},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}};Zy.exports=gu});var yu={};W(yu,{buildCodeTests:()=>r_});async function s_(s,e,t,r,n){try{return await ew(s,e,t,r,n)}catch(o){if((o==null?void 0:o.code)==="ENOENT")return Ft.compiler=null,Ft.webpackConfig=null,r&&(r.data={}),await ew(s,e,t,r,n);throw o}}async function ew(s,e={mode:"development"},t=void 0,r=void 0,n=void 0){let o=await ss("webpack"),i=Ut.cloneDeep(e);e.externals={testim:"__testim"},e.devtool||(e.devtool="inline-source-map"),e.plugins||(e.plugins=[]),e.plugins.push(new o.DefinePlugin(n_(t)),new o.DefinePlugin({"process.argv":JSON.stringify(process.argv)})),s=s.map(h=>Zo.resolve(h));let a=s.map(()=>Oe(30));if(e.optimization={minimize:!1},Number(process.versions.node.split(".")[0])>=17){let h=require("crypto"),g=h.createHash;h.createHash=(w,b)=>g(w==="md4"?"sha256":w,b)}e.entry=Object.fromEntries(Ut.zip(s,a).map(([h,g])=>[g,h])),e.output=Object.assign({devtoolModuleFilenameTemplate:h=>`file:///${h.absoluteResourcePath}`,filename:"[name].bundle.js"},e.output);let l;r?(Ut.isEqual(Ft.webpackConfig,i)&&Ft.compiler||(Ft.webpackConfig=i,Ft.compiler=o(e)),l=Ft.compiler):l=o(e);let u=r||new tw.default;l.outputFileSystem=u;let p=Kt(h=>{n==null||n.addEventListener("abort",()=>{h(new gr,void 0)})});try{let h=await Promise.race([Kt(g=>l.run(g)),p]);if(h!=null&&h.hasErrors())throw new Error(h==null?void 0:h.toJson().errors.toString())}catch(h){let g=h.message.match(/Entry module not found: Error: Can't resolve '(.*)'/);throw g&&g.length===2?e.output&&e.output.library==="tdk"?new N(`Could not open dev-kit functions file in ${g[1]}`):new N(`Can't find test files in: '${g[1]}'`):new N(`Compilation Webpack Error in tests: ${h.message}`)}return{tests:[s.map((h,g)=>({code:u.readFileSync(Zo.resolve("./dist",`${a[g]}.bundle.js`)),name:h})).map(({code:h,name:g})=>({code:h.toString(),baseUrl:"",name:Zo.resolve(g),testConfig:{},testConfigId:null,testId:Oe(),resultId:Oe(),isTestsContainer:!0}))],runName:`Testim Dev Kit Run ${new Date().toLocaleString()}`}}function n_(s){let e=Ut.fromPairs(Object.keys(process.env).filter(r=>/^TDK_/i.test(r)||r==="BASE_URL").map(r=>[r,process.env[r]])),t={BASE_URL:s==null?void 0:s.baseUrl};return{"process.env":o_({...t,...e})}}function o_(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,JSON.stringify(t)]))}var Ut,Zo,tw,Ft,r_,wu=F(()=>{"use strict";Ut=S(require("lodash")),Zo=S(require("path"));M();tw=S(require("memory-fs"));K();Xe();Ft={compiler:null,webpackConfig:null};r_=s_});var bu=C((exports,module)=>{"use strict";var _=require("lodash"),path=require("path"),fsPromises=require("fs/promises"),{AbortError}=(K(),y(Z)),{buildCodeTests}=(wu(),y(yu)),findTestFolder=_.memoize(async s=>(await fsPromises.readdir(s)).includes("tests")&&(await fsPromises.stat(path.join(s,"tests"))).isDirectory()?path.join(s,"tests"):s);async function getLocalLocators(){let folder=await findTestFolder(process.cwd()),locatorsFilePath=path.join(folder,"locators","locators.js");function parseLocators(buffer){return eval(buffer.toString().replace(/require/g,"(x => /locator.(.*).json/.exec(x)[1])"))}let locators=await fsPromises.readFile(locatorsFilePath).then(parseLocators,()=>({}));return Object.fromEntries(Object.keys(locators).map(s=>[s.replace(/"/g,'\\"'),locators[s]]))}async function findTests(s=process.cwd()){let e=await findTestFolder(s),t=await fsPromises.readdir(e,{withFileTypes:!0}),r=["webpack.config.js","tsconfig.js",".DS_Store","functions.js"],n=[".html",".json"];return t.filter(o=>!r.includes(o.name)&&!n.some(i=>o.name.endsWith(i))&&o.isFile()&&!o.name.startsWith(".")).map(o=>o.name)}async function promiseFromProps(s){let e=Object.entries(s),t=e.map(([,n])=>n),r=await Promise.all(t);for(let n=0;n<r.length;n++)e[n][1]=r[n];return Object.fromEntries(e)}async function getLocalLocatorContents(s,e=!1,t=process.cwd()){let r={};if(e){let n=await findTestFolder(t);for(let o of Object.values(s))r[o]=fsPromises.readFile(path.join(n,"locators",`locator.${o}.json`)).then(JSON.parse)}try{return await promiseFromProps(r)}catch(n){return console.error(n),{}}}async function saveTest({body:s,name:e,locators:t,language:r="javascript"}){let n=await findTestFolder(process.cwd()),o=path.join(n,"locators","locators.js"),i=path.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(r==="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 fsPromises.writeFile(i,s),await fsPromises.mkdir(path.join(n,"locators")).catch(()=>{});for(let{id:l,body:u}of t)await fsPromises.writeFile(path.join(n,"locators",`locator.${l}.json`),JSON.stringify(u));let a=Object.fromEntries(t.map(({name:l,id:u})=>[l,u])),c=await getLocalLocators();Object.assign(c,a),await writeLocators(o,c)}async function writeLocators(s,e){let t=`module.exports = {
561
561
  `;for(let[r,n]of Object.entries(e))t+=` "${r}": require('./locator.${n}.json'),
562
- `;t+="};",await fsPromises.writeFile(s,t)}async function saveLocators(s,{mergeIntoExisting:e}={mergeIntoExisting:!1}){let t=await findTestFolder(process.cwd()),r=path.join(t,"locators","locators.js");await fsPromises.mkdir(path.join(t,"locators")).catch(()=>{});for(let{name:o,id:i,elementLocator:a}of s)await fsPromises.writeFile(path.join(t,"locators",`locator.${i}.json`),JSON.stringify({name:o,id:i,elementLocator:a}));let n=Object.fromEntries(s.map(({name:o,id:i})=>[o,i]));if(e){let o=await getLocalLocators();Object.assign(n,o)}await writeLocators(r,n)}async function compileFunctionsLibrary({fileSystem:s,bypassWebpack:e}={},t=void 0){let r=await findTestFolder(process.cwd());if(t!=null&&t.aborted)throw new AbortError;let n=path.join(r,"functions.js");if(e!=null&&e.testim){let i=require("module"),a=i.prototype.require;i.prototype.require=function(l){return l==="testim"?e.testim:a.apply(this,arguments)};try{return delete require.cache[require.resolve(n)],require(n)}finally{i.prototype.require=a}}return(await buildCodeTests([n],{output:{libraryTarget:"umd",library:"tdk",globalObject:"globalThis"},cache:{type:"memory"},mode:"development"},{},s,t)).tests[0][0].code}module.exports={findTestFolder,findTests,getLocalLocators,getLocalLocatorContents,saveTest,saveLocators,compileFunctionsLibrary}});var sn=C((gM,ew)=>{"use strict";ew.exports.getArgumentsFromContext=async function(e,t,r){let n=o_(e.parameterNames.map(o=>o.displayName),t.incomingParams.as);return await Promise.all(n.map(o=>typeof o=="object"&&o.locatedElement?r(o):o))};function o_(s,e){let t=[];for(let r of s){let n=e.functionParameters.indexOf(r);t.push(e.functionArguments[n])}return t}});var rw=C((yM,sw)=>{"use strict";var{AbortError:tw}=(K(),w(Z)),{lazyRequire:i_}=(Je(),w(Tt)),{getArgumentsFromContext:a_}=sn();sw.exports.execute=async function(e,t,r,n,o,i){var c;let a;try{let{WebDriver:l}=await i_("selenium-webdriver");if(i.aborted)throw new tw;let{Executor:u,HttpClient:p}=require("selenium-webdriver/http"),f=e.driver.client.requestHandler.defaultOptions,m=e.driver.client.requestHandler.startPath,g=`${f.protocol}://${f.hostname}:${f.port}`+m,y=new p(g),b=new l(e.getSessionId(),new u(y));await c_(b,e.driver);let T=await a_(r,n,x=>b.findElement({css:x.selector})),v=t.bind(null,b,...T);return a=function(){y.send=async function(){throw new tw}},i.addEventListener("abort",a),await v(),{success:!0}}catch(l){return i.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(l==null?void 0:l.message)||l,extraInfo:(c=l==null?void 0:l.constructor)==null?void 0:c.name}}finally{a&&i.removeEventListener("abort",a)}};async function c_(s,e){if(e.cdpUrl){let t=await s.getAllWindowHandles();for(let r of t)if(await s.switchTo().window(r),await s.executeScript("return window.__isMainTestimTab"))break}}});var iw=C((wM,ow)=>{"use strict";var{AbortError:nw}=(K(),w(Z)),{lazyRequire:l_}=(Je(),w(Tt)),{getArgumentsFromContext:u_}=sn();ow.exports.execute=async function(e,t,r,n,o,i){var c;let a;try{let l=await l_("puppeteer");if(i.aborted)throw new nw;let u=await l.connect({browserWSEndpoint:e.driver.cdpUrl,defaultViewport:null,product:"chrome"});if(i.aborted)throw u.disconnect(),new nw;a=function(){u.disconnect()},i.addEventListener("abort",a);let p=await u.pages(),f;for(let b of p)if(await b.evaluate(()=>window.__isMainTestimTab)){f=b;break}let m=f||p.at(-1),g=await u_(r,n,b=>m.$(b.selector));return await t.bind(null,m,...g)(),{success:!0}}catch(l){return i.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(l==null?void 0:l.message)||l,extraInfo:(c=l==null?void 0:l.constructor)==null?void 0:c.name}}finally{i.removeEventListener("abort",a)}}});var lw=C((bM,cw)=>{"use strict";var{AbortError:aw}=(K(),w(Z)),{lazyRequire:d_}=(Je(),w(Tt)),{getArgumentsFromContext:p_}=sn();cw.exports.execute=async function(e,t,r,n,o,i){var c;let a;try{let l=await d_("playwright");if(i.aborted)throw new aw;let u=await l.chromium.connect({wsEndpoint:e.driver.cdpUrl});if(i.aborted)throw u.disconnect(),new aw;a=function(){u.disconnect()},i.addEventListener("abort",a);let m=(await(await u.newContext({viewport:null})).pages()).at(-1),g=await p_(r,n,b=>m.$(b.selector));return await t.bind(null,m,...g)(),{success:!0}}catch(l){return i.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,reason:(l==null?void 0:l.message)||l,extraInfo:(c=l==null?void 0:l.constructor)==null?void 0:c.name}}finally{a&&i.removeEventListener("abort",a)}}});var pw=C((TM,dw)=>{"use strict";var m_=require("lodash"),bu=Ie(),{guid:Tu}=(M(),w(q)),{AbortError:f_}=(K(),w(Z)),{getArgumentsFromContext:h_}=sn(),{getSessionPlayer:uw}=(he(),w(Re));dw.exports.execute=async function(e,t,r,n,o,i,a,c){function l(){e.sessionPlayer.stopPlaying()}c.addEventListener("abort",l);function u(E){if(i.parameterValues){let P=i.parameterValues.find(j=>j.type==="locate"&&j.id===E.locatorId);return{elementLocator:P.elementLocator,id:P.id,name:"Hybrid Step Locator"}}return E.locatedElement.shadowPath?E.locatedElement.shadowPath[0]:E}let p=await h_(i,r,u),f=t.bind(null,...p),m=Tu(),h=Tu(),g=r.testResultId,y=r.config.baseUrl,b=m_.cloneDeep(r);b.loginData=n;let T=uw().manifestVersion||"runner",v=!1,x=null,A="master",N=`Execute TDK Function '${i.functionName}'`,B=!0,$={fn:f,bypassSetup:!0,isBeforeOrAfterTest:!0,name:N,sourceCode:f.toString(),sourceName:f.name,testId:m,resultId:Tu()},k=typeof t.results=="boolean"&&!t.results;try{bu.log("tdkHybridStepPlayback before addAllTabs"),o?(e.sessionPlayer.playbackAutUtils.frameManager=o,e.sessionPlayer.frameManager=o):await e.addAllTabs(null,{loadInfo:!0,checkForMainTab:!0,takeScreenshots:!k},[e.driver.initialUrl]),e.sessionPlayer.playbackManager.dontAssociateChildResult=!0,e.sessionPlayer.playbackManager.onlyLocalReporting=k,bu.log("tdkHybridStepPlayback before playTestByCode");let E=await new Promise((P,j)=>{a==="agent"&&g_(e,P);function z(){j(new f_),c.removeEventListener("abort",z)}c.addEventListener("abort",z),e.sessionPlayer.playTestByCode(m,h,g,y,b,T,P,v,x,A,[$],N,B).catch(j)});return bu.log("tdkHybridStepPlayback after playTestByCode"),{success:E.success,shouldRetry:!1,resultInfo:{testId:m,executionId:h,resultId:$.resultId}}}catch(E){return{success:!1,error:E,shouldRetry:!1}}finally{c.removeEventListener("abort",l)}};function g_(s,e){let{commonConstants:t}=uw();s.sessionPlayer.playbackManager.on(t.playback.START,({testResult:r})=>{let n=r.runnerStatus;Object.defineProperty(r,"runnerStatus",{get(){return n},set(o){n=o,o==="FINISHED"&&e(r)}})})}});var Jo=C((EM,rn)=>{"use strict";var y_=require("memory-fs"),w_=require("abort-controller"),ys=Ie(),{getLogger:b_}=(U(),w(H)),{sessionType:T_}=(ee(),w(fe)),E_=new y_,v_=b_("hybrid-step-playback"),vu=new Map,Eu;rn.exports.run=(s,e,t,r)=>{let{step:n,context:o}=e.data;return rn.exports.execute(n,o,s,r.loginData)};rn.exports.execute=async function(e,t,r,n,o,i="cli"){let a=new w_,{signal:c}=a;vu.set(t.stepResultId,a);try{ys.log("before seleniumTestPlayer require");let l=Qo(),{compileFunctionsLibrary:u}=wu(),{functionName:p}=e,f={},m=!1,h=new l(t.id,f,m,T_.CODEFUL,r);Eu=h.sessionPlayer.codeSessionPlayer.proxy;let g=e.bypassWebpack?{testim:Eu.wrappedSteps()}:!1;ys.log("before compileFunctionsLibrary",{bypassWebpack:Boolean(e.bypassWebpack)});let y;try{y=await u({fileSystem:E_,bypassWebpack:g},c)}catch(I){return{success:!1,shouldRetry:!1,reason:`Unable to compile functions library. ${I.message}`,extraInfo:I.stack}}typeof globalThis>"u"&&(global.globalThis=process);let b;if(g?b=y[p]:(global.globalThis.__testim=Eu.wrappedSteps(),(0,eval)(y),b=globalThis.tdk[p]),ys.log("after hybridFunction obtain and eval"),!b)return{success:!1,shouldRetry:!1,reason:`Could not find function '${p}' locally. Please make sure you have a functions.js file with a '${p}' function defined`,extraInfo:Object.keys(globalThis.tdk)};if(b.type==="selenium"){let I=rw().execute;return await I(h,b,e,t,i,c)}if(b.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."};ys.log("before puppeteerPlayback");let I=iw().execute;try{return await I(h,b,e,t,i,c)}finally{ys.log("after puppeteerPlayback")}}if(b.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 I=lw().execute;return await I(h,b,e,t,i,c)}if(b.type==="tdk"||!b.type){let I=pw().execute;ys.log("before tdkPlayback");try{return await I(h,b,t,n,o,e,i,c)}finally{ys.log("after tdkPlayback")}}return{success:!1,shouldRetry:!1,reason:`unknown hybrid format ${b.type}`}}catch(l){v_.info("error running hybrid step",{err:l});return}finally{vu.delete(t.stepResultId)}};rn.exports.abort=function(e){let t=vu.get(e);if(t)t.abort();else throw new Error("No such stepResultId")}});var fw=C((vM,mw)=>{"use strict";var S_=fs(),{NpmPackageError:I_}=(K(),w(Z)),x_=(M(),w(q));mw.exports.run=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await S_.installPackage(t,r,n,i,o,a),success:!0}}catch(c){if(c instanceof I_)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof x_.TimeoutError)return{success:!1,code:"timeout"};throw c}}});var ww=C((SM,yw)=>{"use strict";var Xs=Lh(),R_=Jo(),C_=fw(),P_=pe(),{getLogger:k_}=(U(),w(H)),ei=k_("step-playback"),A_={"cli-validation-code-step":Xs,"cli-wait-for-code-step":Xs,"cli-action-code-step":Xs,"cli-api-code-step":Xs,"cli-condition-step":Xs,"cli-download-code-step":Xs,"node-package":C_,"tdk-hybrid":R_};async function gw(s,e,t,r){try{return await P_.saveRemoteStep(s,e,t,r)}catch{ei.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function __(s,e,t,r,n){return ei.info("finished to run remote step",{stepId:t,sessionId:n}),await gw(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function hw(s,e,t,r,n){return ei.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await gw(s,e,t,{status:"completed",success:!1,failureReason:r})}async function O_(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o,userData:i}=s,a=t.type,c=e.getSessionId(),l=t.id;ei.info("start play remote step",{stepType:a,stepId:l,sessionId:c});let u=A_[a];if(!u)return await hw(n,r,l,`Failed to find step type ${a}`,c);try{let p=await u.run(e,t,o,i);return await __(n,r,l,p,c)}catch(p){return await hw(n,r,l,p.message,c)}}yw.exports={executeStep:O_}});var Tw=C((IM,bw)=>{"use strict";var L_=Go(),Su=class extends L_{init(e){super.init(e,"remoteStep"),this.listerers={}}emitJoinRoom(e){return this.emitPromise("remoteStep:join",{resultId:e})}emitLeaveRoom(e){return this.emitPromise("remoteStep:leave",{resultId:e})}joinToRemoteStep(e){return this.rooms[e]?Promise.resolve():(this.joinRoom(e),this.emitJoinRoom(e))}saveRemoteStep(e,t,r){return this.emitPromise("remoteStep:save",{resultId:e,stepId:t,remoteStep:r})}listenToRemoteStep(e,t){this.listerers[e]&&(this._socket.off("remoteStep:saved",this.listerers[e]),delete this.listerers[e]),this.listerers[e]=r=>{r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending"&&t(r.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[e])}unlistenToRemoteStep(e){return this.listerers[e]?(this.leaveRoom(e),this._socket.off("remoteStep:saved",this.listerers[e]),delete this.listerers[e],this.emitLeaveRoom(e)):Promise.resolve()}};bw.exports=new Su});var Cu={};W(Cu,{remoteStepService:()=>ti});var Iu,N_,nn,xu,Ys,Ru,ti,si=F(()=>{"use strict";Iu=Br(),{socketEventTypes:N_}=(ee(),w(fe)),{featureFlagsService:nn}=(le(),w(me)),{REMOTE_STEP_SAVED:xu}=N_,Ru=class{init(e){nn.flags.useNewWSCLI.isEnabled()||(Ys=Tw(),Ys.init(e))}joinToRemoteStep(e){return nn.flags.useNewWSCLI.isEnabled()?Iu.addFilter(`${e}:remoteStep`,{resultId:e},[xu]):Ys.joinToRemoteStep(e)}saveRemoteStep(e,t,r){return nn.flags.useNewWSCLI.isEnabled()?Promise.resolve():Ys.saveRemoteStep(e,t,r)}listenToRemoteStep(e,t){if(nn.flags.useNewWSCLI.isEnabled()){Iu.listenTo(`${e}:remoteStep`,[xu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Ys.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return nn.flags.useNewWSCLI.isEnabled()?(Iu.removeFilter(`${e}:remoteStep`,[xu]),Promise.resolve()):Ys.unlistenToRemoteStep(e)}},ti=new Ru});var Cw=C((xM,Pu)=>{"use strict";var D_=require("lodash"),M_=require("p-retry"),Ew=(M(),w(q)),vw=(ne(),w(ce)),on=Ie(),F_=Os(),Sw=ot(),Qs=pe(),U_=ww(),{remoteStepService:q_}=(si(),w(Cu)),{testResultService:an}=(Ks(),w(en)),{URL:j_}=require("url"),{getLogger:$_}=(U(),w(H)),{preloadTests:B_}=(no(),w(Za)),{timeoutMessages:Iw,CLI_MODE:W_}=(ee(),w(fe)),{SeleniumPerfStats:G_}=Gs(),ge=$_("test-run-handler"),V_=3,Rw=20*1e3,xw=s=>JSON.stringify(s).length<Rw,ri=class{constructor(e,t,r,n,o,i){var c,l;this._executionId=e,this._executionName=t,this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._code=r.code,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._options=n,this._branch=o,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId,this._retryCount=1,this._timeoutRetryCount=1,this._totalRetryCount=1,this._testRunStatus=i;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?Ew.getRunConfigByBrowserName(n.browser,n.saucelabs,n.browserstack):r.runConfig,this.clearTestResultFinished=Promise.resolve(),this.seleniumPerfStats=new G_}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}get executionId(){return this._executionId}get executionName(){return this._executionName}get androidActivityWait(){let e="appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if(e.activity.includes(e.id))return`${e.id}.*`;let{activity:t}=e,r=t.split(".").pop();return t.replace(r,"*")}get nativeAppLink(){let e=null;return"filePath"in this._nativeApp&&(e=`${vw.SERVICES_HOST}/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 r=t||this.baseUrl;if(!r)return null;let[n,o]=r.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 r,n;let t={tokenV3:await Sw.getCustomTokenV3(),refreshToken:Sw.getRefreshToken(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:vw.EXTENSION_SERVICES_HOST,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&&F_.trackWithCIUser("user-disable-mock"),(r=this._options.lightweightMode)!=null&&r.general){t.company=this._options.company;let o=this.runData;t.lightweightMode.isRunDataSentInUrl=xw(o);let i=JSON.stringify(o).length,a=this.testId;t.lightweightMode.isRunDataSentInUrl?(t.runData=o,ge.info(`Run data sent as URL param, test id: ${a} run data length: ${i}`)):ge.warn(`Run data is too big to be sent as a URL param. Test id: ${a}, run data size: ${i} (limit: ${Rw} characters)`),t.isLocalRun=Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await B_(this._options);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 ge.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(){return this._options.runParams[this._testResultId]||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e=this.runData;this.runMode===W_.EXTENSION&&(e.code=this.code),this._options.mockNetworkRules&&(e.mockNetworkRules=this._options.mockNetworkRules);let t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&xw(e))return;let r=async()=>{try{return await Qs.uploadRunDataArtifact(this._options.project,this._testId,this._testResultId,e)}catch(i){return ge.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Qs.clearTestResult(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){on.log("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},{targetId:r}=t.find(o=>o.type==="background_page"&&o.title==="Testim Editor")||{},{targetId:n}=t.find(o=>o.type==="page")||{};if(!r)throw new Error("testim extension not found");if(!n)throw new Error("AUT target not found");try{on.log("before Target.attachToTarget");let[o,i]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:r,flatten:!0}),this.getRunRequestParams()]),{sessionId:a}=o||{};on.log("before Runtime.evaluate"),await M_(async()=>{let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},a);if(!l.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),on.log("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 on.log("after Runtime.evaluate"),c.value}catch(o){throw ge.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new j_(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){ge.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"&&(ge.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:u}}=this;try{let p=await Qs.getTestResults(a,c,u,l);n(p),r||setTimeout(i,3e3)}catch(p){ge.error("failed to check if done",{err:p}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else an.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=Qs.getTestResults(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return ge.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw ge.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Iw.TEST_START_TIMEOUT_MSG)}catch(o){throw ge.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Iw.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await an.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ge.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||an.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){ge.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=D_.debounce(async()=>{try{let i=await Qs.getTestResults(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(ge.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"?(ge.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return ge.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)an.on("socket-connected",e);else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Qs.isTestResultCompleted(this._testResultId,this._options.project,this.retryKey);a?await e()||(ge.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){ge.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&an.off("socket-connected",e)}}listenToRemoteStep(e){q_.listenToRemoteStep(this.testResultId,t=>{U_.executeStep(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:V_;return this._timeoutRetryCount<e}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId=this._originalTestResultId||this._previousTestResultId,this._testResultId=Ew.guid(),!((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}))}};Pu.exports=ri;Pu.exports.TestRunHandler=ri});var Pw,ni,kw=F(()=>{"use strict";Pw=S(Cw()),ni=class{constructor(e,t,r,n,o,i){this._waitingTests=r.map(a=>new Pw.TestRunHandler(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 Aw,H_,K_,cn,ku=F(()=>{"use strict";Aw=S(js());U();H_=G("worker-utils"),K_=async(s,e,t)=>{e&&await Aw.releaseGridSlot(s,t)},cn=async(s,e,t,r)=>{H_.info("releasing player",{hasPlayer:Boolean(r)});try{await(r==null?void 0:r.onDone())}finally{await K_(s,e,t)}}});function eO(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Ou,Lw,_u,ut,ii,ai,Nw,lt,z_,_w,Ow,oi,J_,Au,X_,St,Y_,Q_,Z_,dt,ci=F(()=>{"use strict";Ou=S(require("ms")),Lw=S(require("moment")),_u=S(require("p-retry"));M();ut=S(Ie()),ii=S(js()),ai=S(pe());U();ku();Et();Nw=S(po());le();si();Ks();rt();ee();K();lt=G("base-worker"),{GET_BROWSER_TIMEOUT_MSG:z_,TEST_START_TIMEOUT_MSG:_w,TEST_COMPLETE_TIMEOUT_MSG:Ow}=je,{SETUP_TIMEOUT:oi,NETWORK_ERROR:J_,GRID_ERROR:Au,BROWSER_CLOSED:X_,SELENIUM_ERROR:St,UNKNOWN_ERROR:Y_}=Er,Q_=(0,Ou.default)("1s"),Z_=1;dt=class{constructor(e,t,r,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=dt.getWorkerId();this.lambdatestService=new Nw.LambdatestService;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 Z_++}async getGridSlot(e,t){let r=await ii.getGridSlot(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return se.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Is(!0)}async getBrowserOnce(e,t,r,n){throw new Is(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),lt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!nt({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:xe.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}setSessionTimeout(){return this.options.mode===ae.APPIUM?Math.max((0,Ou.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{ut.log("before getSlotOnce retries");let i=0,a=await(0,_u.default)(async()=>{let u=Date.now();try{return await de(this.getSlotOnce(e),this.options.getBrowserTimeout,je.GET_BROWSER_TIMEOUT_MSG)}catch(p){let f={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw p instanceof gr?lt.info("could not get grid slot due to concurrency issue",f):lt.error("error getting grid slot",{error:p,...f}),i++,await qe(this.options.getBrowserTimeout-(Date.now()-u)),p}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});ut.log("after getSlotOnce retries"),ut.log("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,_u.default)(async()=>{let u=Date.now(),p=this.initPlayer(e);try{a=await ii.handleHybridOrVendorIfNeeded(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let f=this.setSessionTimeout();ut.log("before getBrowserOnce");let m=await de(this.getBrowserOnce(e,t,p,a),f,je.GET_BROWSER_TIMEOUT_MSG);return ut.log("after getBrowserOnce"),se.onGetBrowserSuccess(this.id,r),p||m}catch(f){let m={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},h=this.options.mode===ae.APPIUM?"device":"browser";throw lt.error(`error getting ${h} from grid`,{error:f,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:m}),se.onGetBrowserFailure(this.id,r,++l),p.onDone(),f instanceof ft||await qe(this.options.getBrowserTimeout-(Date.now()-u)),f}},{retries:c-1,minTimeout:0,factor:1}),ut.log("after getBrowserOnce retries")}catch(i){throw await cn(this.id,this.releaseSlotOnTestFinished,r,n),i instanceof ft?i:i instanceof Ss?new xt(i,Au):new xt(i,St)}return n}async runTest(e,t,r){var c;ut.log("inside runTest");let n=(c=this.userData)==null?void 0:c.projectId,o=this.handleQuarantine(e);if(o)return o;ut.log("before runTest onTestStarted");let i=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey);e._baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,a)}finally{await cn(this.id,this.releaseSlotOnTestFinished,n,a)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var p,f;let e=()=>process.nextTick(()=>this.run()),t=async(m,h,g)=>{var x;if(nt(m,this.options))return e();let y=h.sessionId,b=A=>g==null?void 0:g.message.includes(A),I=g&&g instanceof xt,T=g&&(b(_w)||b(Ow)),v=!m.success&&(h.hasMoreRetries()&&!I&&!T||T&&h.hasMoreTimeoutRetries());try{let A=h.retryKey;return m.testRetryKey=A,await this.onTestCompleted(this.id,this.testId,m,y,v),this.executionQueue.hasMoreTests()&&!((x=this.options.lightweightMode)!=null&&x.general)&&await qe(Q_),await this.runTestCleanup(),v?(T?await h.startNewTimeoutRetry():await h.startNewRetry(),lt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:T,testRetryKey:A,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await l(h,v)):await e()}catch(A){if(A instanceof mt)return;lt.error("failed to process test result",{error:A}),e();return}},r=()=>`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. ${zi()?"(Internal: network connectivity test failed)":""}`,n=(m,h)=>{let g=this.options.mode===ae.APPIUM?"device":"browser";if(!h&&lo.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:J_,reason:r()};let y=m instanceof Error?m.message:m;if(y.includes(z_))return{errorType:oi,reason:`Test couldn't get ${g}`};if(y.includes(_w))return{errorType:oi,reason:"Test couldn't be started"};if(y.includes(Ow)){if(!this.testRunTimeout)return{errorType:oi,reason:"Test timeout reached: test is too long"};let b=Lw.default.duration(this.testRunTimeout,"milliseconds"),I=Math.floor(b.asMinutes()),T=b.seconds(),v=I>0?` ${I} min`:"",x=T>0?` ${T} sec`:"";return{errorType:oi,reason:`Test timeout reached (timeout:${v}${x}): test is too long`}}if(m instanceof xt&&m.type){if(m.type===Au)return{errorType:Au,reason:`Test couldn't get ${g} from grid - ${m.message}`};if(m.type===St)return{errorType:St,reason:`Failed to create new session - ${m.message}`}}return"type"in m&&m.type===X_?{errorType:St,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 m&&m.failure instanceof Ht?{errorType:St,reason:`Test couldn't get ${g} from grid - ${m.failure.message}`}:/SeleniumError: connect ECONNREFUSED/.test(m.message)||/Couldn't connect to selenium server/.test(m.message)?{errorType:St,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(m.message)?{errorType:St,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(m.message)?{errorType:St,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(m.message)?{errorType:St,reason:`Session could not be created, please check that the ${g} you requested is supported in your plan`}:{errorType:Y_,reason:y}},o=async(m,h)=>{var T;let g=await Ki();!g&&lo.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),lt.warn("error on run",{err:m});let y=(T=this.userData)==null?void 0:T.projectId,{errorType:b,reason:I}=n(m,g);ai.updateTestResult(y,this.testResultId,this.testId,{status:Tr.COMPLETED,success:!1,reason:I,errorType:b,testRetryKey:h.retryKey,setupStepResult:{status:Tr.COMPLETED,success:!1,reason:I,errorType:b}},h.remoteRunId),await t(eO(this.testId,this.testName,this.testResultId,I),h,m)},i=async(m,h)=>{var T;let g=this.testId,y=this.testResultId,b=(T=this.userData)==null?void 0:T.projectId,I=this.branch;if(!g||!y||!b||!I)return lt.warn("Test failed. Not enough data to recover results via API",{err:m}),o(m,h);try{let v=await ai.getTestResults(g,y,b,I);if(lt.warn("Test failed. Got results via API",{err:m,testResult:v}),v&&v.status===Tr.COMPLETED)return await t(v,h);throw m}catch(v){return v!==m&&lt.error("Failed to fetch test results from server",{testId:g,resultId:y,projectId:b,branch:I,err:v}),o(m,h)}},a=this.options.disableSockets||((p=this.options.lightweightMode)==null?void 0:p.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),c=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),l=async(m,h)=>{try{await Promise.all([!c&&ti.joinToRemoteStep(this.testResultId),!a&&yl.joinToTestResult(this.testResultId,this.testId)]),m.validateRunConfig();let g=await this.runTest(m,this.customExtensionLocalLocation,h),y=await t(g,m);return ut.log("After onRunComplete"),y}catch(g){return i(g,m)}finally{c||ti.unlistenToRemoteStep(this.testResultId)}},u=this.executionQueue.getNext();return u?(this.testId=u.testId,this.testName=u.testName,this.testResultId=u.testResultId,this.overrideTestConfigId=u.overrideTestConfigId,this.testRunConfig=u.runConfig,this.branch=u.branch,l(u)):this.onQueueCompleted()}}});var Fw={};W(Fw,{WorkerSelenium:()=>Lu});function sO(s){let{playback:e}=_s().commonConstants;function t(r){s.playbackManager.on(r,()=>{Ye.log(`Got event ${r}`)})}Object.values(e).forEach(t)}var Ye,Dw,Mw,li,tO,Lu,Uw=F(()=>{"use strict";M();Ye=S(Ie()),Dw=S(il()),Mw=S(Qo());ci();U();Et();K();no();ee();he();li=G("worker-selenium"),tO=1e9,Lu=class extends dt{initPlayer(t){return new Mw.default(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Ye.log("in WorkerSelenium getBrowserOnce"),se.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new Dw.default(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,r,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),Ye.log("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),Ye.log("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,tO),await this.windowUtils.validatePageIsAvailable(),Ye.log("in WorkerSelenium after navigate")}catch(l){let u=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",p=l.message&&l.message==="invalid argument";throw l instanceof ft||u||p?new ft(`Page '${c}' is not available`):(li.error("failed to navigate to page",{err:l}),l)}}async runTestOnce(t,r){var u;let n=_s(),{driver:o,sessionPlayer:i}=r,a=n.manifestVersion||"runner";se.onWaitToTestComplete(this.id,this.isCodeMode),sO(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;(u=this.options.lightweightMode)!=null&&u.preloadTests&&(c=(await Qa(this.options))[this.testId]);let l=async()=>{if(t.automationMode==="codeful"){i.callOrderScheduler?i.callOrderScheduler.schedule(()=>t.waitForExecutionStartedFinished(),{key:`test-result:${this.userData.projectId}:${this.testResultId}`}):await t.waitForExecutionStartedFinished(),Ye.log("right before playTestByCode");let f=new Promise((m,h)=>{i.playTestByCode(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,m,!1,this.overrideTestConfigId,this.branch,t.code,t.testName).catch(h)});return de(f.then(m=>(Ye.log("right after playTestByCode"),m)),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG).catch(m=>{var h;throw m instanceof ke&&((h=i.stopPlayingOnTestTimeout)==null||h.call(i)),m}).then(m=>(m.resultId=this.testResultId,m))}let p=!1;return de(new Promise((f,m)=>{i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,f,!1,this.overrideTestConfigId,this.branch,p,t.remoteRunId,void 0,void 0,c).catch(m)}),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG).catch(f=>{var m;throw f instanceof ke&&((m=i.stopPlayingOnTestTimeout)==null||m.call(i)),f}).then(async f=>{n.localAssetService&&await n.localAssetService.drain(),f.stepsResults=null,f.resultId=this.testResultId,o.isAlive()||(li.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),f.gridIssues="could not validate grid is alive");let m=o.maxKeepAliveGap();m>=3e4&&(li.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),f.keepAliveIssue=m);let g={...f,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g})};o.start(),Ye.log("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),Ye.log("right after super.runTestOnce in workerSelenium");let p=await l();return Ye.log("right after runSeleniumTest"),p}catch(p){throw li.error("failed to run test once",{err:p}),p}}}});var jw=C((HM,qw)=>{"use strict";var Nu=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,r,n={}){}addOpenerStepId(e,t,r){}addOpenerStep(e,t,r){}fixMissingMainTab(e){}buildTabInfo(e,t,r,n,o={}){}addTab(e,t,r,n,o={}){}getTabUtilsByTabIdAndSessionId(e,t){}getTabUtilsByTabId(e){}getTabInfo(e,t){}getTabUtils(e,t){}exactUrlMatch(e,t,r){}singleExactMatchForParts(e,t,r,n){}isSameTab(e,t,r){}getMainTabInfo(e){}getMainTabUtils(e){return{}}removeTabInfo(e,t){}getMainTabId(e){}isMainTabExists(e){}clearAllTabs(e){}clearNonMainTabs(e){}switchTab(e,t,{forceSwitch:r}={forceSwitch:!1}){}getTabDetails(e,t,r={}){}getUnregisteredTabId(e){}waitForTabToOpen(e){}tryToAddTab(e,t){}addNewPopup(e,t){}waitToPendingTabs(e,t){}isMainTabIncognito(){}isInvalidStepVersion(e){}getTabIdByTabInfo(e,t){}};qw.exports=Nu});var Bw=C((KM,$w)=>{"use strict";var Du=(U(),w(H)).getLogger("mobile-frame-locator-mock");$w.exports=function(e){class t{constructor(n,o){this.frameManager=n,this.locateElementPlayer=o}foundFrameCallback(n,o,i){return Du.info("foundFrameCallback-mock invoked"),{}}locate(n,o,i,a,c,l){return Du.info("locate-mock invoked"),{}}findFrame(n,o,i,a){return Du.info("findFrame-mock invoked"),{}}}return t}});var Vw=C((zM,Gw)=>{"use strict";var rO=require("webdriverio"),nO=jw(),oO=pl(),iO=Bw(),{testResultService:aO}=(Ks(),w(en)),cO=bl(),lO=El(),{portSelector:uO}=(Il(),w(Sl)),{isDebuggerConnected:dO}=(Rl(),w(xl)),{getSessionPlayer:Ww}=(he(),w(Re)),pO=(U(),w(H)).getLogger("appium-test-player"),Mu=class{constructor(e,t,r,n="code",o=rO,i,a){let{sessionPlayer:c,commonConstants:l,stepActionFactory:u,MobileLocateElementPlayer:p}=Ww();this.driver=o,this.id=e;let f=new oO(this.driver);this.stepActionFactory=new u(f),fu()(this.driver,this.stepActionFactory,"selenium"),this.tabService=new nO(this.driver),this.windowCreationListener=cO,this.playbackTimeoutCalculator=new lO(dO()),this.tabService.createSesion(e);let m=iO(this.driver);this.sessionPlayer=new c(e,this.tabService,null,null,m,uO,p,null,f,this.stepActionFactory,this.playbackTimeoutCalculator,aO.getSocket(),n),this.sessionPlayer.setShouldMonitorPerformance&&this.sessionPlayer.setShouldMonitorPerformance(r),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){try{await this.driver.activeSession.deleteSession()}catch(e){pO.error("error while deleting appium session",{error:e})}finally{let{commonConstants:e}=Ww();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}};Gw.exports=Mu});var Jw={};W(Jw,{WorkerAppium:()=>Fu});var Hw,Zs,Kw,zw,ln,Fu,Xw=F(()=>{"use strict";Hw=S(require("jsdom"));ne();Zs=S(pe()),Kw=S(Do()),zw=S(Vw());ci();U();Et();he();ln=G("worker-appium"),Fu=class extends dt{initPlayer(e){return new zw.default(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,r,n){se.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=r,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,l=e.nativeAppLink;if(this.options.appId){let{project:u,appId:p}=this.options,f=await Zs.getAppDetails({appId:p,projectId:u});if(!f)throw ln.error("mobile app not found",{appId:p,projectId:u}),new Error("mobile app not found");l=`${mr}/storage${f.filePath}?access_token=${this.options.authData.token}`}try{let u=Kw.buildAppiumOptions({projectType:i,gridInfo:n,testRunConfig:this.testRunConfig,nativeApp:a,options:this.options,appPath:l,androidActivityWait:c}),p=await o.remote(u);Object.assign(o,{activeSession:p}),await this.updateDeviceInfo(e,p),ln.info(`init new appium session testName: ${this.testName}`,{sessionId:p.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(u){throw ln.error("failed to start application",{err:u}),u}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:r}=this.options.gridData;return`https://${e}:${t}/v0/${r}/wd/hub`}async updateDeviceInfo(e,t){var m;let{_executionId:r,_testId:n,_testResultId:o,_options:{project:i}}=e,{projectData:{type:a}={},company:{companyId:c=""}={},gridData:{gridId:l}}=this.options,f={name:(m=(await Zs.getMobileDevicesFromGrid({projectId:i,projectType:a,companyId:c,gridId:l,selectors:`device_id:${t.capabilities.udid}`}))[0])==null?void 0:m.name,model:t.capabilities.deviceModel,osVersion:t.capabilities.platformVersion,udid:t.capabilities.udid,osType:t.capabilities.platformName,scaleFactor:t.capabilities.pixelRatio,virtual:!1};await Zs.updateTestStatus(i,r,n,o,"RUNNING",{device:f})}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:r,directConnectPort:n,directConnectPath:o}=e;if(t&&r&&n&&o)return`${t}://${r}:${n}${o}`}async runTestOnce(e,t){let r=_s(),{sessionPlayer:n}=t,o=t.driver,i=r.manifestVersion||"runner";se.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 Hw.JSDOM("").window.DOMParser;n.playbackManager.appiumApi=new r.AppiumApi(a,o.activeSession.sessionId,c),r.localAssetService&&r.localAssetService.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let p=await new Promise((m,h)=>n.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,i,m,!1,this.overrideTestConfigId,this.branch,!1,e.remoteRunId,void 0,void 0,void 0).catch(h));return r.localAssetService&&await r.localAssetService.drain(),p.stepsResults=null,p.resultId=this.testResultId,{...p,...e.seleniumPerfStats.getStats()}}catch(u){throw ln.error("error while running appium tests",{err:u}),u}};try{return await super.runTestOnce(e,t),await l.call(this)}catch(u){throw ln.error("failed to run test once",{err:u}),u}}}});var Zw=C((ZM,Qw)=>{"use strict";var Yw=(M(),w(q)),mO=Xr(),Uu=class{constructor(e){this.driver=new mO,this.id=e}onDone(){return Yw.promiseTimeout(this.driver.end(),12e4).catch(t=>{if(t instanceof Yw.TimeoutError)return this.driver.forceEnd();throw t}).catch(()=>{}).then(()=>{this.driver=null})}getSessionId(){return this.driver.getSessionId()}};Qw.exports=Uu});var tb={};W(tb,{CDPTestRunner:()=>qu});var eb,qu,sb=F(()=>{"use strict";eb=S(require("ws"));M();qu=class{constructor(){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 eb.default(this._cdpUrl,{timeout:e}),r=Kt(o=>{t.once("open",o)}),n=Kt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return await e.close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId=this._lastWsId||0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var ib=C((tF,ob)=>{"use strict";var rb=require("chrome-launcher"),nb=(M(),w(q)),fO=Do(),{CDPTestRunner:hO}=(sb(),w(tb)),{registerExitHook:gO}=(Mr(),w(Kn)),ju=class{constructor(e){this.sessionId=e,this.cdpTestRunner=new hO}async init(e,t,r,n,o,i,a){let l=[...fO.buildSeleniumOptions(e,t,r,n,o,i,a).desiredCapabilities.chromeOptions.args,...rb.Launcher.defaultFlags().filter(p=>p!=="--disable-extensions")];this.chrome=await rb.launch({chromeFlags:l,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 u=await nb.getCdpAddressForHost(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(u),gO(()=>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}},$u=class{constructor(e){this.sessionId=nb.guid(),this.driver=new ju(this.sessionId),this.id=e}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}};ob.exports=$u});var lb={};W(lb,{WorkerExtension:()=>un});var ui,ab,cb,Qe,un,Bu=F(()=>{"use strict";ui=S(Ie()),ab=S(Zw()),cb=S(ib());K();ci();M();U();Et();ee();Qe=G("worker-ext"),un=class extends dt{initPlayer(){return this.options.useChromeLauncher?new cb.default(this.id):new ab.default(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw Qe.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return se.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;ui.log("WorkerExtension runTestOnce");let i=async u=>{let p=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await de(e.runTestUsingCDP(u.cdpTestRunner),p,je.TEST_START_TIMEOUT_MSG)}catch(f){if(!(f instanceof ke))throw f;return Qe.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(u,p,f)=>{try{let m=await u.url(p);return f.driverUrlFinished=!0,m}catch(m){throw Qe.error("error from driver.url",{err:m,testResultId:r,executionId:n,testId:o,url:p,urlLength:p.length}),m}},c=async u=>{let p=await e.onStarted(this.options.testStartTimeout);return u.testRunHandlerOnStartedHadFinished=!0,p},l=async()=>{var m;if(ui.log("WorkerExtension runExtTest"),((m=this.options.lightweightMode)==null?void 0:m.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){se.onWaitToTestStart(this.id),se.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw Qe.warn("failed to run test via CDP",{err:h}),h}}let{driver:p}=t,f={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();se.onWaitToTestStart(this.id);try{await de(Promise.all([a(t.driver,h,f),c(f)]),this.options.testStartTimeout,je.TEST_START_TIMEOUT_MSG)}catch(y){if(!(y instanceof ke))throw y;Qe.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...f}),await e.checkViaRestAPIIfTestStarted()}se.onWaitToTestComplete(this.id,this.isCodeMode);let g=y=>{throw e.onCompletedCleanup(),Qe.warn("on browser closed error detected",{err:y,testResultId:r,executionId:n,testId:o}),p.unregisterToClosedBrowser(g),y.type=Er.BROWSER_CLOSED,y};p.registerToClosedBrowser(g);try{let y=await de(e.onCompleted(),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG);p.unregisterToClosedBrowser(g),this.lambdatestService.isLambdatestRun()&&await p.executeJS(`lambda-status=${y.success?"passed":"failed"}`).catch(()=>{}),p.isAlive()||(Qe.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&&(Qe.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),y.keepAliveIssue=b),{...y,...e.seleniumPerfStats.getStats()}}catch(y){throw Qe.warn("timeout wait until test completed",{err:y,testResultId:r,executionId:n,testId:o}),new Error(y)}finally{p.unregisterToClosedBrowser(g)}}catch(h){throw Qe.warn("failed to start url",{err:h}),new Error(h)}};t.driver.start();try{return await super.runTestOnce(e,t),ui.log("WorkerExtension super.runTestOnce"),await l()}catch(u){throw Qe.error("failed to run test",{err:u,testId:e.testId,resultId:e.testResultId}),u}}}});var db={};W(db,{WorkerExtensionSingleBrowser:()=>Wu});var ub,yO,wO,Wu,pb=F(()=>{"use strict";ub=S(Ie());M();U();ku();Et();Bu();yO=G("base-worker"),wO=500,Wu=class extends un{async _releasePlayer(){var t;this.testPlayer&&(await cn(this.id,this.releaseSlotOnTestFinished,(t=this.userData)==null?void 0:t.projectId,this.testPlayer),this.testPlayer=null)}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return se.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(yO.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;ub.log("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t._baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await qe(wO)}}});function bO(s,e){e===0?s():setTimeout(s,e*Ii)}var mF,er,pi,ws,Gu,di,mb=F(()=>{"use strict";mF=S(Xr());M();ne();er=S(Ie()),pi=S(Mc()),ws=S(ot());yc();K();U();ee();kw();Gu=G("parallel-worker-manager"),di=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e){case ae.SELENIUM:return(Uw(),w(Fw)).WorkerSelenium;case ae.APPIUM:return(Xw(),w(Jw)).WorkerAppium;default:return gc.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(pb(),w(db)).WorkerExtensionSingleBrowser:(Bu(),w(lb)).WorkerExtension}}createWorkers(e,t,r,...n){let o=this.getWorkerType(r),i=()=>{try{return er.log("before new Worker",r),new o(t,...n)}finally{er.log("after new Worker",r)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,c,l){if(e&&e.length===0)return;let u=!1,p=0,f=m=>new Promise(h=>{var Me,Bt,R,O,D,V;let g=o.project,y=new ni(r,n,e,o,i,t),b={},I=e.length,T=(Me=o.company)==null?void 0:Me.companyId,v=(Bt=o.company)==null?void 0:Bt.name,x=o.source||"cli",A=o.user,N=(R=o.company)==null?void 0:R.planType,B=(O=o.company)==null?void 0:O.isStartUp,$=(D=o.projectData)==null?void 0:D.name,k=(V=o.projectData)==null?void 0:V.type,E=o.lightweightMode,P=vr(o),j=(ie,Fe,ue,hi,hn)=>(p++,pi.analyticsTestStart({executionId:r,projectId:g,testId:Fe,resultId:ue,companyId:T,companyName:v,projectName:$,companyPlan:N,sessionType:P,source:x,user:A,lightweightMode:E,isStartUp:B,projectType:k}),t.testStartAndReport(ie,r,ue,hi,hn)),z=async(ie,Fe,ue,hi,hn)=>{var cd,ld,ud;p--;let Ze={...(E==null?void 0:E.onlyTestIdsNoSuite)&&{show:!0},...ue.seleniumStats&&{seleniumStats:ue.seleniumStats},...ue.gridIssues&&{gridIssues:ue.gridIssues},...ue.keepAliveIssue&&{keepAliveIssue:ue.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ue.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ue.seleniumPerfMarks),delete ue.seleniumPerfMarks),o.grid||o.gridId?(Ze.gridName=o.grid||((cd=o.gridData)==null?void 0:cd.name),Ze.gridType=(ld=o.gridData)==null?void 0:ld.type,Ze.gridProvider=(ud=o.gridData)==null?void 0:ud.provider):o.useLocalChromeDriver?(Ze.gridName="local-chrome-driver-from-options",Ze.gridType="local-chrome"):o.useChromeLauncher?(Ze.gridName="chrome-launcher-from-options",Ze.gridType="local-chrome"):o.browserstack?Ze.gridName="browserstack-from-options":o.saucelabs&&(Ze.gridName="saucelabs-from-options"),await t.testEndAndReport(ie,ue,r,hi,hn,Ze).catch(AT=>Gu.error("testEndAndReport threw an error",{err:AT})),hn)return;b[ue.resultId]=ue,pi.analyticsTestEnd({executionId:r,projectId:g,testId:Fe,resultId:ue.resultId,result:ue,companyId:T,companyName:v,projectName:$,companyPlan:N,sessionType:P,source:x,user:A,lightweightMode:E,logger:Gu,isStartUp:B,projectType:k}),l&&!ue.success&&(y.stop(),u=!0),(Object.keys(b).length===I||u&&p===0)&&h(b)},X=(ie,Fe)=>{b[Fe.resultId]=Fe,t.onTestIgnored(ie,Fe.resultId),p--,(Object.keys(b).length===I||u&&p===0)&&h(b)},oe=(ie,Fe)=>t.onGridSlot(ie,Fe);o.userData={loginData:Object.assign({},ws.getTokenV3UserData(),{refreshToken:ws.getRefreshToken(),authData:ws.getTokenV3UserData(),token:m}),projectId:o.project,company:o.company,servicesUrl:mr},er.log("in localStrategy before createWorker"),this.createWorkers(c,y,o.mode,o,this.customExtensionLocalLocation,r,j,z,oe,X).forEach((ie,Fe)=>{er.log("before schedule worker.run after createWorkers"),bO(()=>{er.log("right before worker.run"),ie.run()},Fe)})});try{let m=await ws.getCustomTokenV3(),h=await f(m);if(u)throw new mt;return h}catch(m){throw Gu.error("failed running parallel workers",{executionId:r,err:m}),m}}}});var hb=C((TF,fb)=>{"use strict";var TO=Go(),Vu=class extends TO{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(r){e(r.data)}this._socket.on("testResult:changes",t.bind(this))}};fb.exports=Vu});var yb=C((vF,gb)=>{"use strict";var Hu=Br(),EO=hb(),{socketEventTypes:vO}=(ee(),w(fe)),{featureFlagsService:dn}=(le(),w(me)),{TEST_RESULT_CREATED:Ku,TEST_RESULT_UPDATED:zu}=vO;gb.exports.RealDataService=class{constructor(){dn.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new EO)}init(e){return dn.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(dn.flags.useNewWSCLI.isEnabled())return Hu.addFilter(e,{runId:e},[zu,Ku],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(dn.flags.useNewWSCLI.isEnabled()){Hu.removeFilter(e,[zu,Ku]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(dn.flags.useNewWSCLI.isEnabled()){Hu.listenTo(e,[zu,Ku],r=>r.runId===e,r=>t(r));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function vb(s,e){var t;if((t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId)return{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:Oe()}))]};if(s.files.length>0){let{buildCodeTests:r}=await Promise.resolve().then(()=>(yu(),gu)),n={};if(s.webpackConfig){let o=bb.join(process.cwd(),s.webpackConfig);n=require(o)}return r(s.files,n,{baseUrl:s.baseUrl})}return await Eb.getSuiteTestList({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Ju(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Xu(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=wb.difference(Qi(s,e),t);if(r.length>0)throw Tb.trackWithCIUser("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new L(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var wb,bb,Tb,Eb,Sb=F(()=>{"use strict";wb=S(require("lodash")),bb=S(require("path"));M();Tb=S(Os()),Eb=S(pe());K()});var _b={};W(_b,{TestPlanRunner:()=>Yu});var bs,Ee,xb,Rb,Cb,qt,Pb,kb,Ab,Ib,SO,pn,IO,Yu,Ob=F(()=>{"use strict";bs=S(require("lodash"));M();U();ne();ee();Ee=S(Ie()),xb=S(js()),Rb=S(pc()),Cb=S(Mc()),qt=S(pe()),Pb=S(ot());Et();kb=S(nh());K();mb();Ab=S(yb());Sb();({testRunStatus:Ib,CLI_MODE:SO}=fe),pn=G("test-plan-runner"),IO=1e3*60*5,Yu=class{constructor(e){this.startTime=Date.now();this.workerManager=new di(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},u=Pb.getTokenV3UserData(),p=async()=>{let y=o.beforeParallel||1,b=!0,I=await this.workerManager.runTests(e,c,i,a,o,n,u,y,b);Object.assign(l,I)},f=async()=>{let y=vi||o.parallel,b=!1;Ee.log("right before this.workerManager.runTests");let I=await this.workerManager.runTests(t,c,i,a,o,n,u,y,b);Ee.log("right after this.workerManager.runTests"),Object.assign(l,I)},m=async()=>{let y=o.afterParallel||1,b=!1,I=await this.workerManager.runTests(r,c,i,a,o,n,u,y,b);Object.assign(l,I)},h=vr(o);Cb.analyticsExecsStart({executionId:i,projectId:o.project,sessionType:h}),Ee.log("right before runBeforeTests");try{return await p(),Ee.log("right before runTestPlanTests"),await f(),Ee.log("right after runTestPlanTests"),await m(),l}catch(y){if(pn.error("error running test plan",{err:y}),y instanceof mt)return c.markAllQueuedTests(i,xe.ABORTED,"aborted",!1);throw y}finally{await g()}async function g(){var b,I,T,v;if((b=o.lightweightMode)!=null&&b.disablePixelValidation)return;if(o.mode===SO.SELENIUM){let{EyeSdkBuilder:x}=(await Promise.resolve().then(()=>(he(),Re))).getSessionPlayer();await x.closeBatch(i);return}let y;try{if(!((v=(T=(I=o.company)==null?void 0:I.activePlan)==null?void 0:T.premiumFeatures)!=null&&v.applitools)||(y=await qt.getApplitoolsIntegrationData(o.project),bs.default.isEmpty(y)||!i))return;let{runKey:x,url:A}=y;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:A,apiKey:x}})}catch(x){if(x.message&&(x.message.startsWith("Request failed with status code 404")||x.message.startsWith("no batchIds were set")))return;pn.error("Failed closing batch in extension mode",{err:x,projectId:o.project,applitoolsIntegrationData:y,batchIds:[i]})}}}async initRealDataService(e){let t=new Ab.RealDataService;return await t.init(e),t}async listenToTestCreatedInFile(e,t,r,n){let o={};e.joinToTestResultsByRunId(r,t);let i=!0;return await new Promise(c=>{let l=u=>{i=!1,c(u)};e.listenToTestResultsByRunId(r,u=>{let p=u.id;if(!n.getTestResult(p)){let h=o[p],g=bs.default.merge({},h,u,{resultId:p});if(o[p]=g,!h||h.status!==u.status){let b=(n.getTestResult(g.parentResultId)||{workerId:1}).workerId;[Ib.RUNNING].includes(u.status)&&se.onTestStarted(g,b),[Ib.COMPLETED].includes(u.status)&&(g.duration=g.endTime-g.startTime||0,se.onTestFinished(g,b))}}let f=!Object.values(o).some(h=>["QUEUED","RUNNING"].includes(h.runnerStatus)),m=!Object.values(n.getAllTestResults()).some(h=>["QUEUED","RUNNING"].includes(h.status));if(f&&m)return l(Object.values(o));if(m&&!f)return qe(1e4).then(()=>{i&&l(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,r){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,r)}async runTestPlan(e,t,r,n,o,i,a,c){var A,N,B;let l=Oe(),u=n.project;Oi(l),e.forEach($=>Object.assign($,{isBeforeTestPlan:!0})),r.forEach($=>Object.assign($,{isAfterTestPlan:!0}));let p=[...e,...t,...r],f=new kb.TestRunStatus(p,n,i,a),m=bs.default.chain(p).map($=>{var k;return((k=$.overrideTestConfig)==null?void 0:k.name)||""}).uniq().compact().value(),h=(m==null?void 0:m.length)===1?m[0]:null,g=n.files.length>0,y=(A=n.lightweightMode)!=null&&A.onlyTestIdsNoSuite?[]:p.map($=>$.name),b=(N=n.lightweightMode)!=null&&N.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:f.executionStart(l,u,this.startTime,o,y),I;g&&(I=this.initRealDataServiceAndListenToTestsCreatedInFile(u,l,f)),Ee.log("before testListInfoPromise");let T=await b;(B=n.lightweightMode)!=null&&B.onlyTestIdsNoSuite||se.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,l,c,h,g),Ee.log("before runTestAllPhases");let v=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,o||"All Tests",f),x=await de(I,IO).catch(async()=>{var k;pn.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:u,executionId:l});let $=await qt.getRealData(u,"testResult",`runId=${l}&sort=runOrder`);return bs.default.chain(((k=$==null?void 0:$.data)==null?void 0:k.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return Ee.log("before executionEnd"),await f.executionEnd(l),Ee.log("after executionEnd"),{results:v,executionId:l,testPlanName:o,configName:h,childTestResults:x}}async runTestPlans(e,t){pn.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(u){return bs.default.flattenDeep(Object.values(u)).reduce((p,f)=>p.concat(f.beforeTests,f.tests,f.afterTests),[])}let n={},o={},i=e.project,a=await qt.getTestPlanTestList(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new L(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new L(`no test to run in test plan ${e.testPlan}`)}return await Xu(e,r(l)),await Ke(c,async u=>{let p=u.testPlanId;n[p]={};let f=Object.assign({},e);f.baseUrl=e.baseUrl||u.startUrl,f.host=e.host,f.port=e.port,f.gridId=e.gridId||u.gridId,e.grid&&delete f.gridId,f.gridData=await xb.getTestPlanGridData(e,u);let m=f.overrideExecutionName||u.name;return await Ke(l[p],async h=>{let g=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,f,m,p,t),y=e.files.length>0;se.onTestPlanFinished(g.results,u.name,this.startTime,g.executionId,!1,y,g.childTestResults),n[p][g.executionId]=g.results;let b=Object.keys(n[p]).map(x=>({executionId:x,status:Ju(n[p][x])})),I=Object.keys(n[p]).map(x=>n[p][x]).reduce((x,A)=>Object.assign(x,A),{}),T=Ju(I);Object.assign(o,I);let v=T?b[0].executionId:b.find(x=>!x.status).executionId;return await qt.saveTestPlanResult(i,p,{success:T,executions:b,executionId:v}),g})})}async runAnonymousTestPlan(e,t){var a;pn.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),Ee.log("before getSuite");let r=await vb(e,t);if(Ee.log("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new L("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new L("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new L("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 Ee.log("Right before validateConfig + runAnonymousTestPlan tests map"),await Ke(r.tests,async c=>{if(e.resultId){let p=c[0];p.resultId=e.resultId,c=[p]}await Xu(e,c),Ee.log("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);Ee.log("right after runTestPlan");let u=e.files.length>0;return await se.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i,u,l.childTestResults),l})}async run(e){let t=Rb.getCurrentBranch(),r=[];Zi(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=bs.default.flattenDeep(r);return Ee.log("right before onAllTestPlansFinished"),await se.onAllTestPlansFinished(n),Ee.log("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var $b=C((kF,jb)=>{"use strict";var Qu=require("lodash"),Mb=(M(),w(q)),xO=(tc(),w(ec)),Lb=(uc(),w(lc)),jt=Ie(),Zu=js(),mi=Os(),ed=pc(),Fb=pe(),RO=Br(),CO=ot(),{labFeaturesService:PO}=(yc(),w(Tf)),{getLogger:kO}=(U(),w(H)),{reporter:AO}=(Et(),w(Dc)),{EDITOR_URL:Nb}=(ne(),w(ce)),{CLI_MODE:_O}=(ee(),w(fe)),{ArgError:tr,QuotaDepletedError:Ub}=(K(),w(Z)),{TestPlanRunner:OO}=(Ob(),w(_b)),{featureFlagsService:pt}=(le(),w(me)),{featureAvailabilityService:qb}=(Gr(),w(Sc)),{prepareMockNetwork:LO,initializeUserWithAuth:NO}=(Da(),w(Na)),Db=30*60*1e3,DO=kO("runner");function MO(s){if(!Qu.get(s,"company.activePlan.premiumFeatures.allowCLI")){let t=s.project;mi.track(s.authData.uid,"cli-not-supported",{projectId:t}),console.warn("Testim CLI is not supported in this plan")}}async function FO(s){let e=s.project,t=await Fb.getUsageForCurrentBillingPeriod(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"),mi.track(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ub}function UO(s,e){let t=s.retentionDays;if(!t)return;let r=Qu.get(e,"activePlan.premiumFeatures.resultRetention");if(t>r)throw new tr(`Retention days (${t}) cannot be greater than the company's retention days (${r}). Run aborted`)}async function qO(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await Promise.all([FO(s),MO(s)])}catch(t){if([tr,Ub].some(r=>t instanceof r))throw t;DO.error("could not validate cli account",{err:t})}}function jO(s){let e=CO.getTokenV3UserData();return mi.identify({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}function $O(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(pt.flags.useNewWSCLI.isEnabled()&&!e&&!t)return RO.connect(s);if(!t){let{remoteStepService:r}=(si(),w(Cu));r.init(s)}if(!e){let{testResultService:r}=(Ks(),w(en));r.init(s)}}function BO(s,e){let{branch:t,autoDetect:r}=s;if(ed.setCurrentBranch(e,r),!e&&!r)throw new tr(`branch ${t} does not exist, run aborted.`)}async function WO(s){let{projectData:{projectId:e}={}}=s,t=ed.getCurrentBranch();Qu.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(s.sfdcCredential=await Fb.loadSfdcCredential({projectId:e,branch:t}))}function GO(s,e){let{onprem:t,id:r,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:p,extensionPath:f,ext:m,playerPath:h}=s;if([_O.SELENIUM].includes(p)&&!h)throw new tr("in selenium on prem mode --player-path must be provided");if(p==="extension"&&!f&&!m)throw new tr("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),u=Mb.getPlanType(a);u==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<Db?Db:s.newBrowserWaitTimeout),pt.setCompanyId(r),pt.setIsPOC(c),pt.setIsStartUp(l),pt.setPlanType(u),qb.setPlanType(u),s.company={companyId:r,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:u,isPOC:c,isStartUp:l,activePlan:a}}function VO(s,e){if(Nb){s.editorUrl=Nb;return}s.editorUrl=e.editorUrl}function HO(s,e){s.allGrids=e}function KO(s,e){s.authData=e}function zO(s,e){let{id:t,name:r,type:n,defaults:o}=e;pt.setProjectId(t),pt.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function JO(s){s.gridData=await Zu.getGridData(s)}async function XO(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(mi.trackWithCIUser("user-override-file",t),s.mockNetworkRules=await LO(s.overrideMappingFile))}async function YO(s,e){jt.log("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await xO.checkNpmVersion(),jt.log("in runner.js after checkNpmVersion"),await qO(s),jt.log("in runRunner before tunnel.connect"),await Lb.connect(s),jt.log("in runRunner after tunnel.connect");let a=await new OO(e).run(s);return jt.log("before tunnel.disconnect"),await Lb.disconnect(s),await Zu.keepAlive.end(t),jt.log("after tunnel.disconnect and gridService.keepAlive.end"),a}function QO(s){var e;qb.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
562
+ `;t+="};",await fsPromises.writeFile(s,t)}async function saveLocators(s,{mergeIntoExisting:e}={mergeIntoExisting:!1}){let t=await findTestFolder(process.cwd()),r=path.join(t,"locators","locators.js");await fsPromises.mkdir(path.join(t,"locators")).catch(()=>{});for(let{name:o,id:i,elementLocator:a}of s)await fsPromises.writeFile(path.join(t,"locators",`locator.${i}.json`),JSON.stringify({name:o,id:i,elementLocator:a}));let n=Object.fromEntries(s.map(({name:o,id:i})=>[o,i]));if(e){let o=await getLocalLocators();Object.assign(n,o)}await writeLocators(r,n)}async function compileFunctionsLibrary({fileSystem:s,bypassWebpack:e}={},t=void 0){let r=await findTestFolder(process.cwd());if(t!=null&&t.aborted)throw new AbortError;let n=path.join(r,"functions.js");if(e!=null&&e.testim){let i=require("module"),a=i.prototype.require;i.prototype.require=function(l){return l==="testim"?e.testim:a.apply(this,arguments)};try{return delete require.cache[require.resolve(n)],require(n)}finally{i.prototype.require=a}}return(await buildCodeTests([n],{output:{libraryTarget:"umd",library:"tdk",globalObject:"globalThis"},cache:{type:"memory"},mode:"development"},{},s,t)).tests[0][0].code}module.exports={findTestFolder,findTests,getLocalLocators,getLocalLocatorContents,saveTest,saveLocators,compileFunctionsLibrary}});var nn=C((yM,sw)=>{"use strict";sw.exports.getArgumentsFromContext=async function(e,t,r){let n=i_(e.parameterNames.map(o=>o.displayName),t.incomingParams.as);return await Promise.all(n.map(o=>typeof o=="object"&&o.locatedElement?r(o):o))};function i_(s,e){let t=[];for(let r of s){let n=e.functionParameters.indexOf(r);t.push(e.functionArguments[n])}return t}});var ow=C((wM,nw)=>{"use strict";var{AbortError:rw}=(K(),y(Z)),{lazyRequire:a_}=(Xe(),y(Tt)),{getArgumentsFromContext:c_}=nn();nw.exports.execute=async function(e,t,r,n,o,i){var c;let a;try{let{WebDriver:l}=await a_("selenium-webdriver");if(i.aborted)throw new rw;let{Executor:u,HttpClient:p}=require("selenium-webdriver/http"),f=e.driver.client.requestHandler.defaultOptions,m=e.driver.client.requestHandler.startPath,g=`${f.protocol}://${f.hostname}:${f.port}`+m,w=new p(g),b=new l(e.getSessionId(),new u(w));await l_(b,e.driver);let T=await c_(r,n,x=>b.findElement({css:x.selector})),v=t.bind(null,b,...T);return a=function(){w.send=async function(){throw new rw}},i.addEventListener("abort",a),await v(),{success:!0}}catch(l){return i.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(l==null?void 0:l.message)||l,extraInfo:(c=l==null?void 0:l.constructor)==null?void 0:c.name}}finally{a&&i.removeEventListener("abort",a)}};async function l_(s,e){if(e.cdpUrl){let t=await s.getAllWindowHandles();for(let r of t)if(await s.switchTo().window(r),await s.executeScript("return window.__isMainTestimTab"))break}}});var cw=C((bM,aw)=>{"use strict";var{AbortError:iw}=(K(),y(Z)),{lazyRequire:u_}=(Xe(),y(Tt)),{getArgumentsFromContext:d_}=nn();aw.exports.execute=async function(e,t,r,n,o,i){var c;let a;try{let l=await u_("puppeteer");if(i.aborted)throw new iw;let u=await l.connect({browserWSEndpoint:e.driver.cdpUrl,defaultViewport:null,product:"chrome"});if(i.aborted)throw u.disconnect(),new iw;a=function(){u.disconnect()},i.addEventListener("abort",a);let p=await u.pages(),f;for(let b of p)if(await b.evaluate(()=>window.__isMainTestimTab)){f=b;break}let m=f||p.at(-1),g=await d_(r,n,b=>m.$(b.selector));return await t.bind(null,m,...g)(),{success:!0}}catch(l){return i.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(l==null?void 0:l.message)||l,extraInfo:(c=l==null?void 0:l.constructor)==null?void 0:c.name}}finally{i.removeEventListener("abort",a)}}});var dw=C((TM,uw)=>{"use strict";var{AbortError:lw}=(K(),y(Z)),{lazyRequire:p_}=(Xe(),y(Tt)),{getArgumentsFromContext:m_}=nn();uw.exports.execute=async function(e,t,r,n,o,i){var c;let a;try{let l=await p_("playwright");if(i.aborted)throw new lw;let u=await l.chromium.connect({wsEndpoint:e.driver.cdpUrl});if(i.aborted)throw u.disconnect(),new lw;a=function(){u.disconnect()},i.addEventListener("abort",a);let m=(await(await u.newContext({viewport:null})).pages()).at(-1),g=await m_(r,n,b=>m.$(b.selector));return await t.bind(null,m,...g)(),{success:!0}}catch(l){return i.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,reason:(l==null?void 0:l.message)||l,extraInfo:(c=l==null?void 0:l.constructor)==null?void 0:c.name}}finally{a&&i.removeEventListener("abort",a)}}});var fw=C((EM,mw)=>{"use strict";var f_=require("lodash"),Tu=Ie(),{guid:Eu}=(M(),y(q)),{AbortError:h_}=(K(),y(Z)),{getArgumentsFromContext:g_}=nn(),{getSessionPlayer:pw}=(he(),y(Re));mw.exports.execute=async function(e,t,r,n,o,i,a,c){function l(){e.sessionPlayer.stopPlaying()}c.addEventListener("abort",l);function u(E){if(i.parameterValues){let P=i.parameterValues.find(j=>j.type==="locate"&&j.id===E.locatorId);return{elementLocator:P.elementLocator,id:P.id,name:"Hybrid Step Locator"}}return E.locatedElement.shadowPath?E.locatedElement.shadowPath[0]:E}let p=await g_(i,r,u),f=t.bind(null,...p),m=Eu(),h=Eu(),g=r.testResultId,w=r.config.baseUrl,b=f_.cloneDeep(r);b.loginData=n;let T=pw().manifestVersion||"runner",v=!1,x=null,A="master",L=`Execute TDK Function '${i.functionName}'`,B=!0,$={fn:f,bypassSetup:!0,isBeforeOrAfterTest:!0,name:L,sourceCode:f.toString(),sourceName:f.name,testId:m,resultId:Eu()},k=typeof t.results=="boolean"&&!t.results;try{Tu.log("tdkHybridStepPlayback before addAllTabs"),o?(e.sessionPlayer.playbackAutUtils.frameManager=o,e.sessionPlayer.frameManager=o):await e.addAllTabs(null,{loadInfo:!0,checkForMainTab:!0,takeScreenshots:!k},[e.driver.initialUrl]),e.sessionPlayer.playbackManager.dontAssociateChildResult=!0,e.sessionPlayer.playbackManager.onlyLocalReporting=k,Tu.log("tdkHybridStepPlayback before playTestByCode");let E=await new Promise((P,j)=>{a==="agent"&&y_(e,P);function z(){j(new h_),c.removeEventListener("abort",z)}c.addEventListener("abort",z),e.sessionPlayer.playTestByCode(m,h,g,w,b,T,P,v,x,A,[$],L,B).catch(j)});return Tu.log("tdkHybridStepPlayback after playTestByCode"),{success:E.success,shouldRetry:!1,resultInfo:{testId:m,executionId:h,resultId:$.resultId}}}catch(E){return{success:!1,error:E,shouldRetry:!1}}finally{c.removeEventListener("abort",l)}};function y_(s,e){let{commonConstants:t}=pw();s.sessionPlayer.playbackManager.on(t.playback.START,({testResult:r})=>{let n=r.runnerStatus;Object.defineProperty(r,"runnerStatus",{get(){return n},set(o){n=o,o==="FINISHED"&&e(r)}})})}});var Jo=C((vM,on)=>{"use strict";var w_=require("memory-fs"),b_=require("abort-controller"),ys=Ie(),{getLogger:T_}=(U(),y(H)),{sessionType:E_}=(ee(),y(fe)),v_=new w_,S_=T_("hybrid-step-playback"),Su=new Map,vu;on.exports.run=(s,e,t,r)=>{let{step:n,context:o}=e.data;return on.exports.execute(n,o,s,r.loginData)};on.exports.execute=async function(e,t,r,n,o,i="cli"){let a=new b_,{signal:c}=a;Su.set(t.stepResultId,a);try{ys.log("before seleniumTestPlayer require");let l=Qo(),{compileFunctionsLibrary:u}=bu(),{functionName:p}=e,f={},m=!1,h=new l(t.id,f,m,E_.CODEFUL,r);vu=h.sessionPlayer.codeSessionPlayer.proxy;let g=e.bypassWebpack?{testim:vu.wrappedSteps()}:!1;ys.log("before compileFunctionsLibrary",{bypassWebpack:Boolean(e.bypassWebpack)});let w;try{w=await u({fileSystem:v_,bypassWebpack:g},c)}catch(I){return{success:!1,shouldRetry:!1,reason:`Unable to compile functions library. ${I.message}`,extraInfo:I.stack}}typeof globalThis>"u"&&(global.globalThis=process);let b;if(g?b=w[p]:(global.globalThis.__testim=vu.wrappedSteps(),(0,eval)(w),b=globalThis.tdk[p]),ys.log("after hybridFunction obtain and eval"),!b)return{success:!1,shouldRetry:!1,reason:`Could not find function '${p}' locally. Please make sure you have a functions.js file with a '${p}' function defined`,extraInfo:Object.keys(globalThis.tdk)};if(b.type==="selenium"){let I=ow().execute;return await I(h,b,e,t,i,c)}if(b.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."};ys.log("before puppeteerPlayback");let I=cw().execute;try{return await I(h,b,e,t,i,c)}finally{ys.log("after puppeteerPlayback")}}if(b.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 I=dw().execute;return await I(h,b,e,t,i,c)}if(b.type==="tdk"||!b.type){let I=fw().execute;ys.log("before tdkPlayback");try{return await I(h,b,t,n,o,e,i,c)}finally{ys.log("after tdkPlayback")}}return{success:!1,shouldRetry:!1,reason:`unknown hybrid format ${b.type}`}}catch(l){S_.info("error running hybrid step",{err:l});return}finally{Su.delete(t.stepResultId)}};on.exports.abort=function(e){let t=Su.get(e);if(t)t.abort();else throw new Error("No such stepResultId")}});var gw=C((SM,hw)=>{"use strict";var I_=fs(),{NpmPackageError:x_}=(K(),y(Z)),R_=(M(),y(q));hw.exports.run=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await I_.installPackage(t,r,n,i,o,a),success:!0}}catch(c){if(c instanceof x_)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof R_.TimeoutError)return{success:!1,code:"timeout"};throw c}}});var Tw=C((IM,bw)=>{"use strict";var Ys=Lh(),C_=Jo(),P_=gw(),k_=pe(),{getLogger:A_}=(U(),y(H)),ei=A_("step-playback"),__={"cli-validation-code-step":Ys,"cli-wait-for-code-step":Ys,"cli-action-code-step":Ys,"cli-api-code-step":Ys,"cli-condition-step":Ys,"cli-download-code-step":Ys,"node-package":P_,"tdk-hybrid":C_};async function ww(s,e,t,r){try{return await k_.saveRemoteStep(s,e,t,r)}catch{ei.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function O_(s,e,t,r,n){return ei.info("finished to run remote step",{stepId:t,sessionId:n}),await ww(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function yw(s,e,t,r,n){return ei.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await ww(s,e,t,{status:"completed",success:!1,failureReason:r})}async function N_(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o,userData:i}=s,a=t.type,c=e.getSessionId(),l=t.id;ei.info("start play remote step",{stepType:a,stepId:l,sessionId:c});let u=__[a];if(!u)return await yw(n,r,l,`Failed to find step type ${a}`,c);try{let p=await u.run(e,t,o,i);return await O_(n,r,l,p,c)}catch(p){return await yw(n,r,l,p.message,c)}}bw.exports={executeStep:N_}});var vw=C((xM,Ew)=>{"use strict";var L_=Go(),Iu=class extends L_{init(e){super.init(e,"remoteStep"),this.listerers={}}emitJoinRoom(e){return this.emitPromise("remoteStep:join",{resultId:e})}emitLeaveRoom(e){return this.emitPromise("remoteStep:leave",{resultId:e})}joinToRemoteStep(e){return this.rooms[e]?Promise.resolve():(this.joinRoom(e),this.emitJoinRoom(e))}saveRemoteStep(e,t,r){return this.emitPromise("remoteStep:save",{resultId:e,stepId:t,remoteStep:r})}listenToRemoteStep(e,t){this.listerers[e]&&(this._socket.off("remoteStep:saved",this.listerers[e]),delete this.listerers[e]),this.listerers[e]=r=>{r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending"&&t(r.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[e])}unlistenToRemoteStep(e){return this.listerers[e]?(this.leaveRoom(e),this._socket.off("remoteStep:saved",this.listerers[e]),delete this.listerers[e],this.emitLeaveRoom(e)):Promise.resolve()}};Ew.exports=new Iu});var Pu={};W(Pu,{remoteStepService:()=>ti});var xu,D_,an,Ru,Qs,Cu,ti,si=F(()=>{"use strict";xu=Wr(),{socketEventTypes:D_}=(ee(),y(fe)),{featureFlagsService:an}=(le(),y(me)),{REMOTE_STEP_SAVED:Ru}=D_,Cu=class{init(e){an.flags.useNewWSCLI.isEnabled()||(Qs=vw(),Qs.init(e))}joinToRemoteStep(e){return an.flags.useNewWSCLI.isEnabled()?xu.addFilter(`${e}:remoteStep`,{resultId:e},[Ru]):Qs.joinToRemoteStep(e)}saveRemoteStep(e,t,r){return an.flags.useNewWSCLI.isEnabled()?Promise.resolve():Qs.saveRemoteStep(e,t,r)}listenToRemoteStep(e,t){if(an.flags.useNewWSCLI.isEnabled()){xu.listenTo(`${e}:remoteStep`,[Ru],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Qs.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return an.flags.useNewWSCLI.isEnabled()?(xu.removeFilter(`${e}:remoteStep`,[Ru]),Promise.resolve()):Qs.unlistenToRemoteStep(e)}},ti=new Cu});var kw=C((RM,ku)=>{"use strict";var M_=require("lodash"),F_=require("p-retry"),Sw=(M(),y(q)),Iw=(ne(),y(ce)),cn=Ie(),U_=Os(),xw=ot(),Zs=pe(),q_=Tw(),{remoteStepService:j_}=(si(),y(Pu)),{testResultService:ln}=(zs(),y(sn)),{URL:$_}=require("url"),{getLogger:B_}=(U(),y(H)),{preloadTests:W_}=(io(),y(ec)),{timeoutMessages:Rw,CLI_MODE:G_}=(ee(),y(fe)),{SeleniumPerfStats:V_}=Gs(),ge=B_("test-run-handler"),H_=3,Pw=20*1e3,Cw=s=>JSON.stringify(s).length<Pw,ri=class{constructor(e,t,r,n,o,i){var c,l;this._executionId=e,this._executionName=t,this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._code=r.code,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._options=n,this._branch=o,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId,this._retryCount=1,this._timeoutRetryCount=1,this._totalRetryCount=1,this._testRunStatus=i;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?Sw.getRunConfigByBrowserName(n.browser,n.saucelabs,n.browserstack):r.runConfig,this.clearTestResultFinished=Promise.resolve(),this.seleniumPerfStats=new V_}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}get executionId(){return this._executionId}get executionName(){return this._executionName}get androidActivityWait(){let e="appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if(e.activity.includes(e.id))return`${e.id}.*`;let{activity:t}=e,r=t.split(".").pop();return t.replace(r,"*")}get getAppSource(){if(this._nativeApp)return this.nativeAppLink?"from-library":"from-device"}get nativeAppLink(){let e=null;return"filePath"in this._nativeApp&&(e=`${Iw.SERVICES_HOST}/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 r=t||this.baseUrl;if(!r)return null;let[n,o]=r.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 r,n;let t={tokenV3:await xw.getCustomTokenV3(),refreshToken:xw.getRefreshToken(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Iw.EXTENSION_SERVICES_HOST,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&&U_.trackWithCIUser("user-disable-mock"),(r=this._options.lightweightMode)!=null&&r.general){t.company=this._options.company;let o=this.runData;t.lightweightMode.isRunDataSentInUrl=Cw(o);let i=JSON.stringify(o).length,a=this.testId;t.lightweightMode.isRunDataSentInUrl?(t.runData=o,ge.info(`Run data sent as URL param, test id: ${a} run data length: ${i}`)):ge.warn(`Run data is too big to be sent as a URL param. Test id: ${a}, run data size: ${i} (limit: ${Pw} characters)`),t.isLocalRun=Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await W_(this._options);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 ge.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(){return this._options.runParams[this._testResultId]||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e=this.runData;this.runMode===G_.EXTENSION&&(e.code=this.code),this._options.mockNetworkRules&&(e.mockNetworkRules=this._options.mockNetworkRules);let t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Cw(e))return;let r=async()=>{try{return await Zs.uploadRunDataArtifact(this._options.project,this._testId,this._testResultId,e)}catch(i){return ge.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Zs.clearTestResult(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){cn.log("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},{targetId:r}=t.find(o=>o.type==="background_page"&&o.title==="Testim Editor")||{},{targetId:n}=t.find(o=>o.type==="page")||{};if(!r)throw new Error("testim extension not found");if(!n)throw new Error("AUT target not found");try{cn.log("before Target.attachToTarget");let[o,i]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:r,flatten:!0}),this.getRunRequestParams()]),{sessionId:a}=o||{};cn.log("before Runtime.evaluate"),await F_(async()=>{let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},a);if(!l.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),cn.log("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 cn.log("after Runtime.evaluate"),c.value}catch(o){throw ge.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new $_(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){ge.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"&&(ge.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:u}}=this;try{let p=await Zs.getTestResults(a,c,u,l);n(p),r||setTimeout(i,3e3)}catch(p){ge.error("failed to check if done",{err:p}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else ln.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=Zs.getTestResults(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return ge.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw ge.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Rw.TEST_START_TIMEOUT_MSG)}catch(o){throw ge.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Rw.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await ln.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ge.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||ln.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){ge.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=M_.debounce(async()=>{try{let i=await Zs.getTestResults(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(ge.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"?(ge.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return ge.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)ln.on("socket-connected",e);else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Zs.isTestResultCompleted(this._testResultId,this._options.project,this.retryKey);a?await e()||(ge.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){ge.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&ln.off("socket-connected",e)}}listenToRemoteStep(e){j_.listenToRemoteStep(this.testResultId,t=>{q_.executeStep(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:H_;return this._timeoutRetryCount<e}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId=this._originalTestResultId||this._previousTestResultId,this._testResultId=Sw.guid(),!((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}))}};ku.exports=ri;ku.exports.TestRunHandler=ri});var Aw,ni,_w=F(()=>{"use strict";Aw=S(kw()),ni=class{constructor(e,t,r,n,o,i){this._waitingTests=r.map(a=>new Aw.TestRunHandler(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 Ow,K_,z_,un,Au=F(()=>{"use strict";Ow=S(js());U();K_=G("worker-utils"),z_=async(s,e,t)=>{e&&await Ow.releaseGridSlot(s,t)},un=async(s,e,t,r)=>{K_.info("releasing player",{hasPlayer:Boolean(r)});try{await(r==null?void 0:r.onDone())}finally{await z_(s,e,t)}}});function tO(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Nu,Dw,Ou,ut,ii,ai,Mw,lt,J_,Nw,Lw,oi,X_,_u,Y_,St,Q_,Z_,eO,dt,ci=F(()=>{"use strict";Nu=S(require("ms")),Dw=S(require("moment")),Ou=S(require("p-retry"));M();ut=S(Ie()),ii=S(js()),ai=S(pe());U();Au();Et();Mw=S(fo());le();si();zs();rt();ee();K();lt=G("base-worker"),{GET_BROWSER_TIMEOUT_MSG:J_,TEST_START_TIMEOUT_MSG:Nw,TEST_COMPLETE_TIMEOUT_MSG:Lw}=je,{SETUP_TIMEOUT:oi,NETWORK_ERROR:X_,GRID_ERROR:_u,BROWSER_CLOSED:Y_,SELENIUM_ERROR:St,UNKNOWN_ERROR:Q_}=vr,Z_=(0,Nu.default)("1s"),eO=1;dt=class{constructor(e,t,r,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=dt.getWorkerId();this.lambdatestService=new Mw.LambdatestService;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 eO++}async getGridSlot(e,t){let r=await ii.getGridSlot(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return se.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Is(!0)}async getBrowserOnce(e,t,r,n){throw new Is(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),lt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!nt({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:xe.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}setSessionTimeout(){return this.options.mode===ae.APPIUM?Math.max((0,Nu.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{ut.log("before getSlotOnce retries");let i=0,a=await(0,Ou.default)(async()=>{let u=Date.now();try{return await de(this.getSlotOnce(e),this.options.getBrowserTimeout,je.GET_BROWSER_TIMEOUT_MSG)}catch(p){let f={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw p instanceof yr?lt.info("could not get grid slot due to concurrency issue",f):lt.error("error getting grid slot",{error:p,...f}),i++,await qe(this.options.getBrowserTimeout-(Date.now()-u)),p}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});ut.log("after getSlotOnce retries"),ut.log("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,Ou.default)(async()=>{let u=Date.now(),p=this.initPlayer(e);try{a=await ii.handleHybridOrVendorIfNeeded(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let f=this.setSessionTimeout();ut.log("before getBrowserOnce");let m=await de(this.getBrowserOnce(e,t,p,a),f,je.GET_BROWSER_TIMEOUT_MSG);return ut.log("after getBrowserOnce"),se.onGetBrowserSuccess(this.id,r),p||m}catch(f){let m={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},h=this.options.mode===ae.APPIUM?"device":"browser";throw lt.error(`error getting ${h} from grid`,{error:f,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:m}),se.onGetBrowserFailure(this.id,r,++l),p.onDone(),f instanceof ft||await qe(this.options.getBrowserTimeout-(Date.now()-u)),f}},{retries:c-1,minTimeout:0,factor:1}),ut.log("after getBrowserOnce retries")}catch(i){throw await un(this.id,this.releaseSlotOnTestFinished,r,n),i instanceof ft?i:i instanceof Ss?new xt(i,_u):new xt(i,St)}return n}async runTest(e,t,r){var l;ut.log("inside runTest");let n=(l=this.userData)==null?void 0:l.projectId,o=this.handleQuarantine(e);if(o)return o;ut.log("before runTest onTestStarted");let i=e.getAppSource,a=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,i);e._baseUrl=a.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,c)}finally{await un(this.id,this.releaseSlotOnTestFinished,n,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var p,f;let e=()=>process.nextTick(()=>this.run()),t=async(m,h,g)=>{var x;if(nt(m,this.options))return e();let w=h.sessionId,b=A=>g==null?void 0:g.message.includes(A),I=g&&g instanceof xt,T=g&&(b(Nw)||b(Lw)),v=!m.success&&(h.hasMoreRetries()&&!I&&!T||T&&h.hasMoreTimeoutRetries());try{let A=h.retryKey;m.testRetryKey=A;let L=h.getAppSource;return await this.onTestCompleted(this.id,this.testId,m,w,v,L),this.executionQueue.hasMoreTests()&&!((x=this.options.lightweightMode)!=null&&x.general)&&await qe(Z_),await this.runTestCleanup(),v?(T?await h.startNewTimeoutRetry():await h.startNewRetry(),lt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:T,testRetryKey:A,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await l(h,v)):await e()}catch(A){if(A instanceof mt)return;lt.error("failed to process test result",{error:A}),e();return}},r=()=>`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. ${Ji()?"(Internal: network connectivity test failed)":""}`,n=(m,h)=>{let g=this.options.mode===ae.APPIUM?"device":"browser";if(!h&&po.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:X_,reason:r()};let w=m instanceof Error?m.message:m;if(w.includes(J_))return{errorType:oi,reason:`Test couldn't get ${g}`};if(w.includes(Nw))return{errorType:oi,reason:"Test couldn't be started"};if(w.includes(Lw)){if(!this.testRunTimeout)return{errorType:oi,reason:"Test timeout reached: test is too long"};let b=Dw.default.duration(this.testRunTimeout,"milliseconds"),I=Math.floor(b.asMinutes()),T=b.seconds(),v=I>0?` ${I} min`:"",x=T>0?` ${T} sec`:"";return{errorType:oi,reason:`Test timeout reached (timeout:${v}${x}): test is too long`}}if(m instanceof xt&&m.type){if(m.type===_u)return{errorType:_u,reason:`Test couldn't get ${g} from grid - ${m.message}`};if(m.type===St)return{errorType:St,reason:`Failed to create new session - ${m.message}`}}return"type"in m&&m.type===Y_?{errorType:St,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 m&&m.failure instanceof Ht?{errorType:St,reason:`Test couldn't get ${g} from grid - ${m.failure.message}`}:/SeleniumError: connect ECONNREFUSED/.test(m.message)||/Couldn't connect to selenium server/.test(m.message)?{errorType:St,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(m.message)?{errorType:St,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(m.message)?{errorType:St,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(m.message)?{errorType:St,reason:`Session could not be created, please check that the ${g} you requested is supported in your plan`}:{errorType:Q_,reason:w}},o=async(m,h)=>{var T;let g=await zi();!g&&po.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),lt.warn("error on run",{err:m});let w=(T=this.userData)==null?void 0:T.projectId,{errorType:b,reason:I}=n(m,g);ai.updateTestResult(w,this.testResultId,this.testId,{status:Er.COMPLETED,success:!1,reason:I,errorType:b,testRetryKey:h.retryKey,setupStepResult:{status:Er.COMPLETED,success:!1,reason:I,errorType:b}},h.remoteRunId),await t(tO(this.testId,this.testName,this.testResultId,I),h,m)},i=async(m,h)=>{var T;let g=this.testId,w=this.testResultId,b=(T=this.userData)==null?void 0:T.projectId,I=this.branch;if(!g||!w||!b||!I)return lt.warn("Test failed. Not enough data to recover results via API",{err:m}),o(m,h);try{let v=await ai.getTestResults(g,w,b,I);if(lt.warn("Test failed. Got results via API",{err:m,testResult:v}),v&&v.status===Er.COMPLETED)return await t(v,h);throw m}catch(v){return v!==m&&lt.error("Failed to fetch test results from server",{testId:g,resultId:w,projectId:b,branch:I,err:v}),o(m,h)}},a=this.options.disableSockets||((p=this.options.lightweightMode)==null?void 0:p.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),c=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),l=async(m,h)=>{try{await Promise.all([!c&&ti.joinToRemoteStep(this.testResultId),!a&&wl.joinToTestResult(this.testResultId,this.testId)]),m.validateRunConfig();let g=await this.runTest(m,this.customExtensionLocalLocation,h),w=await t(g,m);return ut.log("After onRunComplete"),w}catch(g){return i(g,m)}finally{c||ti.unlistenToRemoteStep(this.testResultId)}},u=this.executionQueue.getNext();return u?(this.testId=u.testId,this.testName=u.testName,this.testResultId=u.testResultId,this.overrideTestConfigId=u.overrideTestConfigId,this.testRunConfig=u.runConfig,this.branch=u.branch,l(u)):this.onQueueCompleted()}}});var qw={};W(qw,{WorkerSelenium:()=>Lu});function rO(s){let{playback:e}=_s().commonConstants;function t(r){s.playbackManager.on(r,()=>{Ye.log(`Got event ${r}`)})}Object.values(e).forEach(t)}var Ye,Fw,Uw,li,sO,Lu,jw=F(()=>{"use strict";M();Ye=S(Ie()),Fw=S(al()),Uw=S(Qo());ci();U();Et();K();io();ee();he();li=G("worker-selenium"),sO=1e9,Lu=class extends dt{initPlayer(t){return new Uw.default(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Ye.log("in WorkerSelenium getBrowserOnce"),se.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new Fw.default(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,r,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),Ye.log("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),Ye.log("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,sO),await this.windowUtils.validatePageIsAvailable(),Ye.log("in WorkerSelenium after navigate")}catch(l){let u=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",p=l.message&&l.message==="invalid argument";throw l instanceof ft||u||p?new ft(`Page '${c}' is not available`):(li.error("failed to navigate to page",{err:l}),l)}}async runTestOnce(t,r){var u;let n=_s(),{driver:o,sessionPlayer:i}=r,a=n.manifestVersion||"runner";se.onWaitToTestComplete(this.id,this.isCodeMode),rO(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;(u=this.options.lightweightMode)!=null&&u.preloadTests&&(c=(await Za(this.options))[this.testId]);let l=async()=>{if(t.automationMode==="codeful"){i.callOrderScheduler?i.callOrderScheduler.schedule(()=>t.waitForExecutionStartedFinished(),{key:`test-result:${this.userData.projectId}:${this.testResultId}`}):await t.waitForExecutionStartedFinished(),Ye.log("right before playTestByCode");let f=new Promise((m,h)=>{i.playTestByCode(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,m,!1,this.overrideTestConfigId,this.branch,t.code,t.testName).catch(h)});return de(f.then(m=>(Ye.log("right after playTestByCode"),m)),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG).catch(m=>{var h;throw m instanceof ke&&((h=i.stopPlayingOnTestTimeout)==null||h.call(i)),m}).then(m=>(m.resultId=this.testResultId,m))}let p=!1;return de(new Promise((f,m)=>{i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,a,f,!1,this.overrideTestConfigId,this.branch,p,t.remoteRunId,void 0,void 0,c).catch(m)}),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG).catch(f=>{var m;throw f instanceof ke&&((m=i.stopPlayingOnTestTimeout)==null||m.call(i)),f}).then(async f=>{n.localAssetService&&await n.localAssetService.drain(),f.stepsResults=null,f.resultId=this.testResultId,o.isAlive()||(li.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),f.gridIssues="could not validate grid is alive");let m=o.maxKeepAliveGap();m>=3e4&&(li.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),f.keepAliveIssue=m);let g={...f,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g})};o.start(),Ye.log("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),Ye.log("right after super.runTestOnce in workerSelenium");let p=await l();return Ye.log("right after runSeleniumTest"),p}catch(p){throw li.error("failed to run test once",{err:p}),p}}}});var Bw=C((KM,$w)=>{"use strict";var Du=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,r,n={}){}addOpenerStepId(e,t,r){}addOpenerStep(e,t,r){}fixMissingMainTab(e){}buildTabInfo(e,t,r,n,o={}){}addTab(e,t,r,n,o={}){}getTabUtilsByTabIdAndSessionId(e,t){}getTabUtilsByTabId(e){}getTabInfo(e,t){}getTabUtils(e,t){}exactUrlMatch(e,t,r){}singleExactMatchForParts(e,t,r,n){}isSameTab(e,t,r){}getMainTabInfo(e){}getMainTabUtils(e){return{}}removeTabInfo(e,t){}getMainTabId(e){}isMainTabExists(e){}clearAllTabs(e){}clearNonMainTabs(e){}switchTab(e,t,{forceSwitch:r}={forceSwitch:!1}){}getTabDetails(e,t,r={}){}getUnregisteredTabId(e){}waitForTabToOpen(e){}tryToAddTab(e,t){}addNewPopup(e,t){}waitToPendingTabs(e,t){}isMainTabIncognito(){}isInvalidStepVersion(e){}getTabIdByTabInfo(e,t){}};$w.exports=Du});var Gw=C((zM,Ww)=>{"use strict";var Mu=(U(),y(H)).getLogger("mobile-frame-locator-mock");Ww.exports=function(e){class t{constructor(n,o){this.frameManager=n,this.locateElementPlayer=o}foundFrameCallback(n,o,i){return Mu.info("foundFrameCallback-mock invoked"),{}}locate(n,o,i,a,c,l){return Mu.info("locate-mock invoked"),{}}findFrame(n,o,i,a){return Mu.info("findFrame-mock invoked"),{}}}return t}});var Kw=C((JM,Hw)=>{"use strict";var nO=require("webdriverio"),oO=Bw(),iO=ml(),aO=Gw(),{testResultService:cO}=(zs(),y(sn)),lO=Tl(),uO=vl(),{portSelector:dO}=(xl(),y(Il)),{isDebuggerConnected:pO}=(Cl(),y(Rl)),{getSessionPlayer:Vw}=(he(),y(Re)),mO=(U(),y(H)).getLogger("appium-test-player"),Fu=class{constructor(e,t,r,n="code",o=nO,i,a){let{sessionPlayer:c,commonConstants:l,stepActionFactory:u,MobileLocateElementPlayer:p}=Vw();this.driver=o,this.id=e;let f=new iO(this.driver);this.stepActionFactory=new u(f),hu()(this.driver,this.stepActionFactory,"selenium"),this.tabService=new oO(this.driver),this.windowCreationListener=lO,this.playbackTimeoutCalculator=new uO(pO()),this.tabService.createSesion(e);let m=aO(this.driver);this.sessionPlayer=new c(e,this.tabService,null,null,m,dO,p,null,f,this.stepActionFactory,this.playbackTimeoutCalculator,cO.getSocket(),n),this.sessionPlayer.setShouldMonitorPerformance&&this.sessionPlayer.setShouldMonitorPerformance(r),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){try{await this.driver.activeSession.deleteSession()}catch(e){mO.error("error while deleting appium session",{error:e})}finally{let{commonConstants:e}=Vw();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}};Hw.exports=Fu});var Yw={};W(Yw,{WorkerAppium:()=>Uu});var zw,er,Jw,Xw,dn,Uu,Qw=F(()=>{"use strict";zw=S(require("jsdom"));ne();er=S(pe()),Jw=S(Fo()),Xw=S(Kw());ci();U();Et();he();dn=G("worker-appium"),Uu=class extends dt{initPlayer(e){return new Xw.default(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,r,n){se.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=r,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,l=e.nativeAppLink;if(this.options.appId){let{project:u,appId:p}=this.options,f=await er.getAppDetails({appId:p,projectId:u});if(!f)throw dn.error("mobile app not found",{appId:p,projectId:u}),new Error("mobile app not found");l=`${fr}/storage${f.filePath}?access_token=${this.options.authData.token}`}try{let u=Jw.buildAppiumOptions({projectType:i,gridInfo:n,testRunConfig:this.testRunConfig,nativeApp:a,options:this.options,appPath:l,androidActivityWait:c}),p=await o.remote(u);Object.assign(o,{activeSession:p}),await this.updateDeviceInfo(e,p),dn.info(`init new appium session testName: ${this.testName}`,{sessionId:p.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(u){throw dn.error("failed to start application",{err:u}),u}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:r}=this.options.gridData;return`https://${e}:${t}/v0/${r}/wd/hub`}async updateDeviceInfo(e,t){var m;let{_executionId:r,_testId:n,_testResultId:o,_options:{project:i}}=e,{projectData:{type:a}={},company:{companyId:c=""}={},gridData:{gridId:l}}=this.options,f={name:(m=(await er.getMobileDevicesFromGrid({projectId:i,projectType:a,companyId:c,gridId:l,selectors:`device_id:${t.capabilities.udid}`}))[0])==null?void 0:m.name,model:t.capabilities.deviceModel,osVersion:t.capabilities.platformVersion,udid:t.capabilities.udid,osType:t.capabilities.platformName,scaleFactor:t.capabilities.pixelRatio,virtual:!1};await er.updateTestStatus(i,r,n,o,"RUNNING",{device:f})}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:r,directConnectPort:n,directConnectPath:o}=e;if(t&&r&&n&&o)return`${t}://${r}:${n}${o}`}async runTestOnce(e,t){let r=_s(),{sessionPlayer:n}=t,o=t.driver,i=r.manifestVersion||"runner";se.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 zw.JSDOM("").window.DOMParser;n.playbackManager.appiumApi=new r.AppiumApi(a,o.activeSession.sessionId,c),r.localAssetService&&r.localAssetService.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let p=await new Promise((m,h)=>n.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,i,m,!1,this.overrideTestConfigId,this.branch,!1,e.remoteRunId,void 0,void 0,void 0).catch(h));return r.localAssetService&&await r.localAssetService.drain(),p.stepsResults=null,p.resultId=this.testResultId,{...p,...e.seleniumPerfStats.getStats()}}catch(u){throw dn.error("error while running appium tests",{err:u}),u}};try{return await super.runTestOnce(e,t),await l.call(this)}catch(u){throw dn.error("failed to run test once",{err:u}),u}}}});var tb=C((eF,eb)=>{"use strict";var Zw=(M(),y(q)),fO=Qr(),qu=class{constructor(e){this.driver=new fO,this.id=e}onDone(){return Zw.promiseTimeout(this.driver.end(),12e4).catch(t=>{if(t instanceof Zw.TimeoutError)return this.driver.forceEnd();throw t}).catch(()=>{}).then(()=>{this.driver=null})}getSessionId(){return this.driver.getSessionId()}};eb.exports=qu});var rb={};W(rb,{CDPTestRunner:()=>ju});var sb,ju,nb=F(()=>{"use strict";sb=S(require("ws"));M();ju=class{constructor(){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 sb.default(this._cdpUrl,{timeout:e}),r=Kt(o=>{t.once("open",o)}),n=Kt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return await e.close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId=this._lastWsId||0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var cb=C((sF,ab)=>{"use strict";var ob=require("chrome-launcher"),ib=(M(),y(q)),hO=Fo(),{CDPTestRunner:gO}=(nb(),y(rb)),{registerExitHook:yO}=(Fr(),y(Jn)),$u=class{constructor(e){this.sessionId=e,this.cdpTestRunner=new gO}async init(e,t,r,n,o,i,a){let l=[...hO.buildSeleniumOptions(e,t,r,n,o,i,a).desiredCapabilities.chromeOptions.args,...ob.Launcher.defaultFlags().filter(p=>p!=="--disable-extensions")];this.chrome=await ob.launch({chromeFlags:l,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 u=await ib.getCdpAddressForHost(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(u),yO(()=>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}},Bu=class{constructor(e){this.sessionId=ib.guid(),this.driver=new $u(this.sessionId),this.id=e}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}};ab.exports=Bu});var db={};W(db,{WorkerExtension:()=>pn});var ui,lb,ub,Qe,pn,Wu=F(()=>{"use strict";ui=S(Ie()),lb=S(tb()),ub=S(cb());K();ci();M();U();Et();ee();Qe=G("worker-ext"),pn=class extends dt{initPlayer(){return this.options.useChromeLauncher?new ub.default(this.id):new lb.default(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw Qe.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return se.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;ui.log("WorkerExtension runTestOnce");let i=async u=>{let p=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await de(e.runTestUsingCDP(u.cdpTestRunner),p,je.TEST_START_TIMEOUT_MSG)}catch(f){if(!(f instanceof ke))throw f;return Qe.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(u,p,f)=>{try{let m=await u.url(p);return f.driverUrlFinished=!0,m}catch(m){throw Qe.error("error from driver.url",{err:m,testResultId:r,executionId:n,testId:o,url:p,urlLength:p.length}),m}},c=async u=>{let p=await e.onStarted(this.options.testStartTimeout);return u.testRunHandlerOnStartedHadFinished=!0,p},l=async()=>{var m;if(ui.log("WorkerExtension runExtTest"),((m=this.options.lightweightMode)==null?void 0:m.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){se.onWaitToTestStart(this.id),se.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw Qe.warn("failed to run test via CDP",{err:h}),h}}let{driver:p}=t,f={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();se.onWaitToTestStart(this.id);try{await de(Promise.all([a(t.driver,h,f),c(f)]),this.options.testStartTimeout,je.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof ke))throw w;Qe.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...f}),await e.checkViaRestAPIIfTestStarted()}se.onWaitToTestComplete(this.id,this.isCodeMode);let g=w=>{throw e.onCompletedCleanup(),Qe.warn("on browser closed error detected",{err:w,testResultId:r,executionId:n,testId:o}),p.unregisterToClosedBrowser(g),w.type=vr.BROWSER_CLOSED,w};p.registerToClosedBrowser(g);try{let w=await de(e.onCompleted(),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG);p.unregisterToClosedBrowser(g),this.lambdatestService.isLambdatestRun()&&await p.executeJS(`lambda-status=${w.success?"passed":"failed"}`).catch(()=>{}),p.isAlive()||(Qe.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=p.maxKeepAliveGap();return b>=3e4&&(Qe.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(w){throw Qe.warn("timeout wait until test completed",{err:w,testResultId:r,executionId:n,testId:o}),new Error(w)}finally{p.unregisterToClosedBrowser(g)}}catch(h){throw Qe.warn("failed to start url",{err:h}),new Error(h)}};t.driver.start();try{return await super.runTestOnce(e,t),ui.log("WorkerExtension super.runTestOnce"),await l()}catch(u){throw Qe.error("failed to run test",{err:u,testId:e.testId,resultId:e.testResultId}),u}}}});var mb={};W(mb,{WorkerExtensionSingleBrowser:()=>Gu});var pb,wO,bO,Gu,fb=F(()=>{"use strict";pb=S(Ie());M();U();Au();Et();Wu();wO=G("base-worker"),bO=500,Gu=class extends pn{async _releasePlayer(){var t;this.testPlayer&&(await un(this.id,this.releaseSlotOnTestFinished,(t=this.userData)==null?void 0:t.projectId,this.testPlayer),this.testPlayer=null)}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return se.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(wO.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;pb.log("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t._baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await qe(bO)}}});function TO(s,e){e===0?s():setTimeout(s,e*xi)}var fF,tr,pi,ws,Vu,di,hb=F(()=>{"use strict";fF=S(Qr());M();ne();tr=S(Ie()),pi=S(Fc()),ws=S(ot());wc();K();U();ee();_w();Vu=G("parallel-worker-manager"),di=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e){case ae.SELENIUM:return(jw(),y(qw)).WorkerSelenium;case ae.APPIUM:return(Qw(),y(Yw)).WorkerAppium;default:return yc.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(fb(),y(mb)).WorkerExtensionSingleBrowser:(Wu(),y(db)).WorkerExtension}}createWorkers(e,t,r,...n){let o=this.getWorkerType(r),i=()=>{try{return tr.log("before new Worker",r),new o(t,...n)}finally{tr.log("after new Worker",r)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,c,l){if(e&&e.length===0)return;let u=!1,p=0,f=m=>new Promise(h=>{var Me,Bt,R,O,D,V;let g=o.project,w=new ni(r,n,e,o,i,t),b={},I=e.length,T=(Me=o.company)==null?void 0:Me.companyId,v=(Bt=o.company)==null?void 0:Bt.name,x=o.source||"cli",A=o.user,L=(R=o.company)==null?void 0:R.planType,B=(O=o.company)==null?void 0:O.isStartUp,$=(D=o.projectData)==null?void 0:D.name,k=(V=o.projectData)==null?void 0:V.type,E=o.lightweightMode,P=Sr(o),j=(ie,Fe,ue,hi,yn,gi)=>(p++,pi.analyticsTestStart({executionId:r,projectId:g,testId:Fe,resultId:ue,companyId:T,companyName:v,projectName:$,companyPlan:L,sessionType:P,source:x,user:A,lightweightMode:E,isStartUp:B,projectType:k,appSource:gi}),t.testStartAndReport(ie,r,ue,hi,yn)),z=async(ie,Fe,ue,hi,yn,gi)=>{var ld,ud,dd;p--;let Ze={...(E==null?void 0:E.onlyTestIdsNoSuite)&&{show:!0},...ue.seleniumStats&&{seleniumStats:ue.seleniumStats},...ue.gridIssues&&{gridIssues:ue.gridIssues},...ue.keepAliveIssue&&{keepAliveIssue:ue.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ue.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ue.seleniumPerfMarks),delete ue.seleniumPerfMarks),o.grid||o.gridId?(Ze.gridName=o.grid||((ld=o.gridData)==null?void 0:ld.name),Ze.gridType=(ud=o.gridData)==null?void 0:ud.type,Ze.gridProvider=(dd=o.gridData)==null?void 0:dd.provider):o.useLocalChromeDriver?(Ze.gridName="local-chrome-driver-from-options",Ze.gridType="local-chrome"):o.useChromeLauncher?(Ze.gridName="chrome-launcher-from-options",Ze.gridType="local-chrome"):o.browserstack?Ze.gridName="browserstack-from-options":o.saucelabs&&(Ze.gridName="saucelabs-from-options"),await t.testEndAndReport(ie,ue,r,hi,yn,Ze).catch(OT=>Vu.error("testEndAndReport threw an error",{err:OT})),yn)return;b[ue.resultId]=ue,pi.analyticsTestEnd({executionId:r,projectId:g,testId:Fe,resultId:ue.resultId,result:ue,companyId:T,companyName:v,projectName:$,companyPlan:L,sessionType:P,source:x,user:A,lightweightMode:E,logger:Vu,isStartUp:B,projectType:k,appSource:gi}),l&&!ue.success&&(w.stop(),u=!0),(Object.keys(b).length===I||u&&p===0)&&h(b)},X=(ie,Fe)=>{b[Fe.resultId]=Fe,t.onTestIgnored(ie,Fe.resultId),p--,(Object.keys(b).length===I||u&&p===0)&&h(b)},oe=(ie,Fe)=>t.onGridSlot(ie,Fe);o.userData={loginData:Object.assign({},ws.getTokenV3UserData(),{refreshToken:ws.getRefreshToken(),authData:ws.getTokenV3UserData(),token:m}),projectId:o.project,company:o.company,servicesUrl:fr},tr.log("in localStrategy before createWorker"),this.createWorkers(c,w,o.mode,o,this.customExtensionLocalLocation,r,j,z,oe,X).forEach((ie,Fe)=>{tr.log("before schedule worker.run after createWorkers"),TO(()=>{tr.log("right before worker.run"),ie.run()},Fe)})});try{let m=await ws.getCustomTokenV3(),h=await f(m);if(u)throw new mt;return h}catch(m){throw Vu.error("failed running parallel workers",{executionId:r,err:m}),m}}}});var yb=C((EF,gb)=>{"use strict";var EO=Go(),Hu=class extends EO{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(r){e(r.data)}this._socket.on("testResult:changes",t.bind(this))}};gb.exports=Hu});var bb=C((SF,wb)=>{"use strict";var Ku=Wr(),vO=yb(),{socketEventTypes:SO}=(ee(),y(fe)),{featureFlagsService:mn}=(le(),y(me)),{TEST_RESULT_CREATED:zu,TEST_RESULT_UPDATED:Ju}=SO;wb.exports.RealDataService=class{constructor(){mn.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new vO)}init(e){return mn.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(mn.flags.useNewWSCLI.isEnabled())return Ku.addFilter(e,{runId:e},[Ju,zu],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(mn.flags.useNewWSCLI.isEnabled()){Ku.removeFilter(e,[Ju,zu]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(mn.flags.useNewWSCLI.isEnabled()){Ku.listenTo(e,[Ju,zu],r=>r.runId===e,r=>t(r));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function Ib(s,e){var t;if((t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId)return{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:Oe()}))]};if(s.files.length>0){let{buildCodeTests:r}=await Promise.resolve().then(()=>(wu(),yu)),n={};if(s.webpackConfig){let o=Eb.join(process.cwd(),s.webpackConfig);n=require(o)}return r(s.files,n,{baseUrl:s.baseUrl})}return await Sb.getSuiteTestList({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Xu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Yu(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Tb.difference(Zi(s,e),t);if(r.length>0)throw vb.trackWithCIUser("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new N(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Tb,Eb,vb,Sb,xb=F(()=>{"use strict";Tb=S(require("lodash")),Eb=S(require("path"));M();vb=S(Os()),Sb=S(pe());K()});var Nb={};W(Nb,{TestPlanRunner:()=>Qu});var bs,Ee,Cb,Pb,kb,qt,Ab,_b,Ob,Rb,IO,fn,xO,Qu,Lb=F(()=>{"use strict";bs=S(require("lodash"));M();U();ne();ee();Ee=S(Ie()),Cb=S(js()),Pb=S(mc()),kb=S(Fc()),qt=S(pe()),Ab=S(ot());Et();_b=S(oh());K();hb();Ob=S(bb());xb();({testRunStatus:Rb,CLI_MODE:IO}=fe),fn=G("test-plan-runner"),xO=1e3*60*5,Qu=class{constructor(e){this.startTime=Date.now();this.workerManager=new di(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},u=Ab.getTokenV3UserData(),p=async()=>{let w=o.beforeParallel||1,b=!0,I=await this.workerManager.runTests(e,c,i,a,o,n,u,w,b);Object.assign(l,I)},f=async()=>{let w=Si||o.parallel,b=!1;Ee.log("right before this.workerManager.runTests");let I=await this.workerManager.runTests(t,c,i,a,o,n,u,w,b);Ee.log("right after this.workerManager.runTests"),Object.assign(l,I)},m=async()=>{let w=o.afterParallel||1,b=!1,I=await this.workerManager.runTests(r,c,i,a,o,n,u,w,b);Object.assign(l,I)},h=Sr(o);kb.analyticsExecsStart({executionId:i,projectId:o.project,sessionType:h}),Ee.log("right before runBeforeTests");try{return await p(),Ee.log("right before runTestPlanTests"),await f(),Ee.log("right after runTestPlanTests"),await m(),l}catch(w){if(fn.error("error running test plan",{err:w}),w instanceof mt)return c.markAllQueuedTests(i,xe.ABORTED,"aborted",!1);throw w}finally{await g()}async function g(){var b,I,T,v;if((b=o.lightweightMode)!=null&&b.disablePixelValidation)return;if(o.mode===IO.SELENIUM){let{EyeSdkBuilder:x}=(await Promise.resolve().then(()=>(he(),Re))).getSessionPlayer();await x.closeBatch(i);return}let w;try{if(!((v=(T=(I=o.company)==null?void 0:I.activePlan)==null?void 0:T.premiumFeatures)!=null&&v.applitools)||(w=await qt.getApplitoolsIntegrationData(o.project),bs.default.isEmpty(w)||!i))return;let{runKey:x,url:A}=w;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:A,apiKey:x}})}catch(x){if(x.message&&(x.message.startsWith("Request failed with status code 404")||x.message.startsWith("no batchIds were set")))return;fn.error("Failed closing batch in extension mode",{err:x,projectId:o.project,applitoolsIntegrationData:w,batchIds:[i]})}}}async initRealDataService(e){let t=new Ob.RealDataService;return await t.init(e),t}async listenToTestCreatedInFile(e,t,r,n){let o={};e.joinToTestResultsByRunId(r,t);let i=!0;return await new Promise(c=>{let l=u=>{i=!1,c(u)};e.listenToTestResultsByRunId(r,u=>{let p=u.id;if(!n.getTestResult(p)){let h=o[p],g=bs.default.merge({},h,u,{resultId:p});if(o[p]=g,!h||h.status!==u.status){let b=(n.getTestResult(g.parentResultId)||{workerId:1}).workerId;[Rb.RUNNING].includes(u.status)&&se.onTestStarted(g,b),[Rb.COMPLETED].includes(u.status)&&(g.duration=g.endTime-g.startTime||0,se.onTestFinished(g,b))}}let f=!Object.values(o).some(h=>["QUEUED","RUNNING"].includes(h.runnerStatus)),m=!Object.values(n.getAllTestResults()).some(h=>["QUEUED","RUNNING"].includes(h.status));if(f&&m)return l(Object.values(o));if(m&&!f)return qe(1e4).then(()=>{i&&l(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,r){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,r)}async runTestPlan(e,t,r,n,o,i,a,c){var A,L,B;let l=Oe(),u=n.project;Ni(l),e.forEach($=>Object.assign($,{isBeforeTestPlan:!0})),r.forEach($=>Object.assign($,{isAfterTestPlan:!0}));let p=[...e,...t,...r],f=new _b.TestRunStatus(p,n,i,a),m=bs.default.chain(p).map($=>{var k;return((k=$.overrideTestConfig)==null?void 0:k.name)||""}).uniq().compact().value(),h=(m==null?void 0:m.length)===1?m[0]:null,g=n.files.length>0,w=(A=n.lightweightMode)!=null&&A.onlyTestIdsNoSuite?[]:p.map($=>$.name),b=(L=n.lightweightMode)!=null&&L.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:f.executionStart(l,u,this.startTime,o,w),I;g&&(I=this.initRealDataServiceAndListenToTestsCreatedInFile(u,l,f)),Ee.log("before testListInfoPromise");let T=await b;(B=n.lightweightMode)!=null&&B.onlyTestIdsNoSuite||se.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,l,c,h,g),Ee.log("before runTestAllPhases");let v=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,o||"All Tests",f),x=await de(I,xO).catch(async()=>{var k;fn.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:u,executionId:l});let $=await qt.getRealData(u,"testResult",`runId=${l}&sort=runOrder`);return bs.default.chain(((k=$==null?void 0:$.data)==null?void 0:k.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return Ee.log("before executionEnd"),await f.executionEnd(l),Ee.log("after executionEnd"),{results:v,executionId:l,testPlanName:o,configName:h,childTestResults:x}}async runTestPlans(e,t){fn.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(u){return bs.default.flattenDeep(Object.values(u)).reduce((p,f)=>p.concat(f.beforeTests,f.tests,f.afterTests),[])}let n={},o={},i=e.project,a=await qt.getTestPlanTestList(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new N(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new N(`no test to run in test plan ${e.testPlan}`)}return await Yu(e,r(l)),await ze(c,async u=>{let p=u.testPlanId;n[p]={};let f=Object.assign({},e);f.baseUrl=e.baseUrl||u.startUrl,f.host=e.host,f.port=e.port,f.gridId=e.gridId||u.gridId,e.grid&&delete f.gridId,f.gridData=await Cb.getTestPlanGridData(e,u);let m=f.overrideExecutionName||u.name;return await ze(l[p],async h=>{let g=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,f,m,p,t),w=e.files.length>0;se.onTestPlanFinished(g.results,u.name,this.startTime,g.executionId,!1,w,g.childTestResults),n[p][g.executionId]=g.results;let b=Object.keys(n[p]).map(x=>({executionId:x,status:Xu(n[p][x])})),I=Object.keys(n[p]).map(x=>n[p][x]).reduce((x,A)=>Object.assign(x,A),{}),T=Xu(I);Object.assign(o,I);let v=T?b[0].executionId:b.find(x=>!x.status).executionId;return await qt.saveTestPlanResult(i,p,{success:T,executions:b,executionId:v}),g})})}async runAnonymousTestPlan(e,t){var a;fn.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),Ee.log("before getSuite");let r=await Ib(e,t);if(Ee.log("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new N("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new N("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new N("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 Ee.log("Right before validateConfig + runAnonymousTestPlan tests map"),await ze(r.tests,async c=>{if(e.resultId){let p=c[0];p.resultId=e.resultId,c=[p]}await Yu(e,c),Ee.log("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);Ee.log("right after runTestPlan");let u=e.files.length>0;return await se.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i,u,l.childTestResults),l})}async run(e){let t=Pb.getCurrentBranch(),r=[];ea(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=bs.default.flattenDeep(r);return Ee.log("right before onAllTestPlansFinished"),await se.onAllTestPlansFinished(n),Ee.log("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var Wb=C((AF,Bb)=>{"use strict";var Zu=require("lodash"),Ub=(M(),y(q)),RO=(sc(),y(tc)),Db=(dc(),y(uc)),jt=Ie(),ed=js(),mi=Os(),td=mc(),qb=pe(),CO=Wr(),PO=ot(),{labFeaturesService:kO}=(wc(),y(Ef)),{getLogger:AO}=(U(),y(H)),{reporter:_O}=(Et(),y(Mc)),{EDITOR_URL:Mb}=(ne(),y(ce)),{CLI_MODE:OO}=(ee(),y(fe)),{ArgError:sr,QuotaDepletedError:jb}=(K(),y(Z)),{TestPlanRunner:NO}=(Lb(),y(Nb)),{featureFlagsService:pt}=(le(),y(me)),{featureAvailabilityService:$b}=(Vr(),y(Ic)),{prepareMockNetwork:LO,initializeUserWithAuth:DO}=(Ma(),y(Da)),Fb=30*60*1e3,MO=AO("runner");function FO(s){if(!Zu.get(s,"company.activePlan.premiumFeatures.allowCLI")){let t=s.project;mi.track(s.authData.uid,"cli-not-supported",{projectId:t}),console.warn("Testim CLI is not supported in this plan")}}async function UO(s){let e=s.project,t=await qb.getUsageForCurrentBillingPeriod(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"),mi.track(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new jb}function qO(s,e){let t=s.retentionDays;if(!t)return;let r=Zu.get(e,"activePlan.premiumFeatures.resultRetention");if(t>r)throw new sr(`Retention days (${t}) cannot be greater than the company's retention days (${r}). Run aborted`)}async function jO(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await Promise.all([UO(s),FO(s)])}catch(t){if([sr,jb].some(r=>t instanceof r))throw t;MO.error("could not validate cli account",{err:t})}}function $O(s){let e=PO.getTokenV3UserData();return mi.identify({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}function BO(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(pt.flags.useNewWSCLI.isEnabled()&&!e&&!t)return CO.connect(s);if(!t){let{remoteStepService:r}=(si(),y(Pu));r.init(s)}if(!e){let{testResultService:r}=(zs(),y(sn));r.init(s)}}function WO(s,e){let{branch:t,autoDetect:r}=s;if(td.setCurrentBranch(e,r),!e&&!r)throw new sr(`branch ${t} does not exist, run aborted.`)}async function GO(s){let{projectData:{projectId:e}={}}=s,t=td.getCurrentBranch();Zu.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(s.sfdcCredential=await qb.loadSfdcCredential({projectId:e,branch:t}))}function VO(s,e){let{onprem:t,id:r,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:p,extensionPath:f,ext:m,playerPath:h}=s;if([OO.SELENIUM].includes(p)&&!h)throw new sr("in selenium on prem mode --player-path must be provided");if(p==="extension"&&!f&&!m)throw new sr("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),u=Ub.getPlanType(a);u==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<Fb?Fb:s.newBrowserWaitTimeout),pt.setCompanyId(r),pt.setIsPOC(c),pt.setIsStartUp(l),pt.setPlanType(u),$b.setPlanType(u),s.company={companyId:r,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:u,isPOC:c,isStartUp:l,activePlan:a}}function HO(s,e){if(Mb){s.editorUrl=Mb;return}s.editorUrl=e.editorUrl}function KO(s,e){s.allGrids=e}function zO(s,e){s.authData=e}function JO(s,e){let{id:t,name:r,type:n,defaults:o}=e;pt.setProjectId(t),pt.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function XO(s){s.gridData=await ed.getGridData(s)}async function YO(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(mi.trackWithCIUser("user-override-file",t),s.mockNetworkRules=await LO(s.overrideMappingFile))}async function QO(s,e){jt.log("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await RO.checkNpmVersion(),jt.log("in runner.js after checkNpmVersion"),await jO(s),jt.log("in runRunner before tunnel.connect"),await Db.connect(s),jt.log("in runRunner after tunnel.connect");let a=await new NO(e).run(s);return jt.log("before tunnel.disconnect"),await Db.disconnect(s),await ed.keepAlive.end(t),jt.log("after tunnel.disconnect and gridService.keepAlive.end"),a}function ZO(s){var e;$b.shouldShowFreeGridRunWarning((e=s.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 ZO(s){var g;jt.log("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o}=s,i=pt.fetch(),a=$O(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{}),Promise.resolve(a).catch(()=>{});let{authData:c,editorConfig:l,companyByProjectId:u,projectById:p,branchName:f,allGrids:m}=await NO(s);if(UO(s,u),await Promise.all([i,a]),s.browser&&pt.flags.dec2022eolBrowsers.isEnabled()){let y=Mb.getBrowserInfo(s.browser);if(y.eol)throw new tr(`Unsupported browser: ${y.browserName}`)}jt.log("after featureFlagsReady and socketConnected"),VO(s,l),GO(s,u),zO(s,p),BO(s,f),HO(s,m),KO(s,c),await WO(s),(g=s.lightweightMode)!=null&&g.disableLabs||await PO.loadLabFeatures(p.id,u.activePlan),s.lightweightMode&&s.lightweightMode.type==="turboMode"&&(pt.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,s.lightweightMode&&s.lightweightMode.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`),Zu.keepAlive.start(e),jO(e),await XO(s),await JO(s),QO(s);let h=ed.getCurrentBranch();AO.setOptions(s,h)}jb.exports={run:YO,init:ZO}});var Wb=C((AF,Bb)=>{"use strict";var{getPackageVersion:e0}=(tc(),w(ec)),{doLogin:t0}=(Ns(),w(Ls)),{getStartedWithStart:s0}=td();Bb.exports=s=>{s.get("/",(e,t)=>{let r=s0();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:e0()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());t0({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}});var Hb=C((_F,Vb)=>{"use strict";var r0=require("express"),sr=r0.Router(),Gb=(U(),w(H)).getLogger("codim-router"),{findTests:n0,getLocalLocators:o0,getLocalLocatorContents:i0,saveTest:a0,saveLocators:c0,compileFunctionsLibrary:l0}=wu();sr.get("/tests",async(s,e)=>{let t=await n0();e.json({tests:t,success:!0})});sr.get("/locators",async(s,e)=>{let t=await o0(),r=await i0(t,s.query.full);e.json({locators:t,contents:r,success:!0})});sr.post("/locators",async(s,e)=>{if(!s.body){e.status(400).send({success:!1,reason:"missing body"});return}if(!s.body.locators){e.status(400).send({success:!1,reason:"missing locators"});return}let{locators:t,mergeIntoExisting:r}=s.body;await c0(t,{mergeIntoExisting:r||!1}),e.status(200).send({success:!0})});sr.get("/compile",async(s,e)=>{try{let t=await l0(s.body.name);e.send({success:!0,code:t})}catch(t){Gb.error(t),e.json({success:!1,reason:t.message})}});sr.post("/saveTest",async(s,e)=>{if(!s.body){e.status(400).send({success:!1,reason:"missing body"});return}try{await a0(s.body),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),Gb.error(t)}});Vb.exports.router=sr});var Kb=C((OF,sd)=>{"use strict";var u0=require("fs"),d0=require("path"),p0=require("os"),{fork:m0}=require("child_process"),{ClientError:f0,PlaygroundCodeError:h0}=(K(),w(Z)),g0=["playwright","selenium","puppeteer"],Ts={};async function y0(s,e,t="utf8"){let r=d0.join(p0.tmpdir(),s);return await u0.promises.writeFile(r,e,t),r}var w0=s=>{let e,t=new Promise(n=>{e=n}),r=m0(s,{stdio:["inherit","inherit","inherit","ipc"]});return t.child=r,r.on("message",n=>{if(!n)return;let{type:o,error:i}=n;i&&["uncaughtException","unhandledRejection"].includes(o)&&e({error:Object.assign(new h0,{innerStack:n.error.stack})})}),r.on("error",n=>{e({error:n})}),r.on("exit",n=>{e({exitCode:n})}),t};async function b0({code:s}){let e=Date.now();try{let t=`
568
- module.paths = ${JSON.stringify(sd.paths)};
566
+ `)}async function e0(s){var g;jt.log("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o}=s,i=pt.fetch(),a=BO(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{}),Promise.resolve(a).catch(()=>{});let{authData:c,editorConfig:l,companyByProjectId:u,projectById:p,branchName:f,allGrids:m}=await DO(s);if(qO(s,u),await Promise.all([i,a]),s.browser&&pt.flags.dec2022eolBrowsers.isEnabled()){let w=Ub.getBrowserInfo(s.browser);if(w.eol)throw new sr(`Unsupported browser: ${w.browserName}`)}jt.log("after featureFlagsReady and socketConnected"),HO(s,l),VO(s,u),JO(s,p),WO(s,f),KO(s,m),zO(s,c),await GO(s),(g=s.lightweightMode)!=null&&g.disableLabs||await kO.loadLabFeatures(p.id,u.activePlan),s.lightweightMode&&s.lightweightMode.type==="turboMode"&&(pt.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,s.lightweightMode&&s.lightweightMode.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`),ed.keepAlive.start(e),$O(e),await YO(s),await XO(s),ZO(s);let h=td.getCurrentBranch();_O.setOptions(s,h)}Bb.exports={run:QO,init:e0}});var Vb=C((_F,Gb)=>{"use strict";var{getPackageVersion:t0}=(sc(),y(tc)),{doLogin:s0}=(Ls(),y(Ns)),{getStartedWithStart:r0}=sd();Gb.exports=s=>{s.get("/",(e,t)=>{let r=r0();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:t0()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());s0({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}});var zb=C((OF,Kb)=>{"use strict";var n0=require("express"),rr=n0.Router(),Hb=(U(),y(H)).getLogger("codim-router"),{findTests:o0,getLocalLocators:i0,getLocalLocatorContents:a0,saveTest:c0,saveLocators:l0,compileFunctionsLibrary:u0}=bu();rr.get("/tests",async(s,e)=>{let t=await o0();e.json({tests:t,success:!0})});rr.get("/locators",async(s,e)=>{let t=await i0(),r=await a0(t,s.query.full);e.json({locators:t,contents:r,success:!0})});rr.post("/locators",async(s,e)=>{if(!s.body){e.status(400).send({success:!1,reason:"missing body"});return}if(!s.body.locators){e.status(400).send({success:!1,reason:"missing locators"});return}let{locators:t,mergeIntoExisting:r}=s.body;await l0(t,{mergeIntoExisting:r||!1}),e.status(200).send({success:!0})});rr.get("/compile",async(s,e)=>{try{let t=await u0(s.body.name);e.send({success:!0,code:t})}catch(t){Hb.error(t),e.json({success:!1,reason:t.message})}});rr.post("/saveTest",async(s,e)=>{if(!s.body){e.status(400).send({success:!1,reason:"missing body"});return}try{await c0(s.body),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),Hb.error(t)}});Kb.exports.router=rr});var Jb=C((NF,rd)=>{"use strict";var d0=require("fs"),p0=require("path"),m0=require("os"),{fork:f0}=require("child_process"),{ClientError:h0,PlaygroundCodeError:g0}=(K(),y(Z)),y0=["playwright","selenium","puppeteer"],Ts={};async function w0(s,e,t="utf8"){let r=p0.join(m0.tmpdir(),s);return await d0.promises.writeFile(r,e,t),r}var b0=s=>{let e,t=new Promise(n=>{e=n}),r=f0(s,{stdio:["inherit","inherit","inherit","ipc"]});return t.child=r,r.on("message",n=>{if(!n)return;let{type:o,error:i}=n;i&&["uncaughtException","unhandledRejection"].includes(o)&&e({error:Object.assign(new g0,{innerStack:n.error.stack})})}),r.on("error",n=>{e({error:n})}),r.on("exit",n=>{e({exitCode:n})}),t};async function T0({code:s}){let e=Date.now();try{let t=`
568
+ module.paths = ${JSON.stringify(rd.paths)};
569
569
  process.on('unhandledRejection', (error) => {
570
570
  process.send({type: 'unhandledRejection', error: {message: error.message, stack: error.stack}});
571
571
  process.exit(1);
@@ -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
  ${s};
578
- `,r=await y0(`tst-playground-${Date.now()}.js`,t),n=w0(r);Ts[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{Ts[e]&&(Ts[e].kill(),delete Ts[e])}}async function T0({code:s,type:e}){if(["playwright","puppeteer","selenium"].includes(e))return b0({code:s});throw new f0}async function E0(){Object.keys(Ts).forEach(s=>{Ts[s].kill(),delete Ts[s]})}sd.exports={CODE_TYPES:g0,runPlaygroundTest:T0,stopPlaygroundTest:E0}});var Qb=C((LF,Yb)=>{"use strict";var v0=require("express"),rd=v0.Router(),Xb=(U(),w(H)).getLogger("playground-router"),{ClientError:S0,PlaygroundCodeError:I0}=(K(),w(Z)),{runPlaygroundTest:x0,stopPlaygroundTest:R0,CODE_TYPES:C0}=Kb(),{DISABLE_AGENT_ORIGIN_CHECK:P0}=(ne(),w(ce)),zb=["localhost","app.testim.io","playground.testim.io","staging.testim.io","app.staging.testim.cc","tta-crm.tricentis.com"],Jb=s=>{if(!s)return{};try{return new URL(s)}catch{return{}}},k0=(s,e,t)=>{if(P0)return t();let r=s.headers.referer,n=s.headers.origin;if(!r&&!n)return e.status(400).send();let o=Jb(r),i=Jb(n);return!zb.includes(o.hostname)&&!zb.includes(i.hostname)?e.status(400).send():t()};rd.post("/run",[k0],async(s,e)=>{let t=s.body||{},{code:r,type:n}=t;if(!r||!C0.includes(n)){e.status(400).send({success:!1,reason:"missing arguments"});return}try{await x0(t),e.send({success:!0})}catch(o){if(o instanceof S0){e.status(404).send({success:!1});return}if(o instanceof I0){e.json({success:!1,type:"playground-error",stack:o.innerStack});return}e.json({success:!1,reason:o.message}),Xb.error(o)}});rd.post("/stop",(s,e)=>{try{R0(),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),Xb.error(t)}});Yb.exports.router=rd});var sT=C((NF,tT)=>{"use strict";var A0=require("express"),eT=fs(),{NpmPackageError:_0,TimeoutError:O0}=(K(),w(Z)),rr=(U(),w(H)).getLogger("cli-router"),Zb=require("chalk"),nd=A0.Router();nd.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:u}=s.body;if(typeof t!="string"||!r||!n||!o||!i||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let p=await eT.runCodeWithPackages(t,r,n,o,i,a,c,l,u);p.success||(console.log(Zb.red(p.result.resultValue)),rr.error("CLI Action Failure",{message:p.result.resultValue})),e.status(200).json({success:!0,data:p})}catch(p){rr.error("failed to run cli code",{err:p}),console.log(Zb.red("failed to run cli code",p)),e.status(500).json({success:!1,code:"internal-error"})}});nd.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:o,stepResultId:i,timeout:a}=s.body;if(!t||typeof o!="object"||!r||typeof n!="number"||!i||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let c=await eT.installPackage(t,r,n,o,i,a);rr.info("installed packages successfully"),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof _0){rr.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 O0){rr.error("timeout installing node package"),e.status(200).json({success:!1,code:"timeout"});return}rr.error("failed to install node packages",{err:c}),e.status(500).json({success:!1,code:"internal-error"})}});tT.exports=nd});var nT=C((DF,rT)=>{"use strict";var L0=sT(),N0=fs(),D0=(U(),w(H)).getLogger("cli-service");N0.cleanLocalPackageInstallFolder().catch(s=>D0.warn("failed to clean local package folder",{err:s}));rT.exports={router:L0}});var iT=C((MF,oT)=>{"use strict";var M0=require("express");oT.exports={standaloneBrowserRoutes:F0};function F0(s){let e=M0.Router();return e.get("/cdp-url",(t,r)=>{if(!s){r.status(503).send({error:"Testim standalone browser is not running"});return}r.status(200).send({url:s.webdriverApi.cdpUrl})}),e.get("/status",(t,r)=>{if(!s){r.status(503).send({ok:!1});return}r.status(200).send({ok:!0})}),e}});var uT=C((FF,lT)=>{"use strict";var aT=Jo(),U0=require("express"),cT=(U(),w(H)).getLogger("hybrid-router");lT.exports.hybridRoutes=function(e){let t=U0.Router();return t.post("/run",(r,n)=>{var c;if(!((c=r.body)!=null&&c.step)){n.status(400).send({error:"Missing step"});return}let{step:o,context:i,loginData:a}=r.body;e.webdriverApi||n.status(503).send({success:!1,reason:"Testim Agent was not started with Testim Start."}),r.setTimeout(0),aT.execute(o,i,e.webdriverApi,a,void 0,"agent").then(l=>{n.status(200).send(l)}).catch(l=>{cT.error("failed to run hybrid code",{e:l}),n.status(500).send(Object.assign({success:!1,error:l}))})}),t.post("/abort",(r,n)=>{var o;if(!((o=r.body)!=null&&o.stepResultId)){n.status(400).send({error:"missing stepResultId"});return}try{aT.abort(r.body.stepResultId),n.status(204).end()}catch(i){if(i&&i.message==="No such stepResultId"){n.status(400).send({error:"No such stepResultId"});return}cT.error("hybrid code abort unexpected error",{e:i}),n.status(500).send({error:"unexpected error",info:`${i?i.message:"N/A"}`})}}),t}});var mT=C((UF,pT)=>{"use strict";var q0=require("compression"),j0=require("express"),dT=require("body-parser"),$0=require("cors"),{IS_ON_PREM:B0,DISABLE_AGENT_ORIGIN_CHECK:W0}=(ne(),w(ce));pT.exports=function(s,e){let t=j0();s(t),t.use(dT.urlencoded({extended:!1,limit:"50mb"})),t.use(q0()),t.use(dT.json({limit:"50mb"}));let n={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:B0||W0?"*":["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"]};t.use("*",$0(n)),Wb()(t),t.use("/files",Hb().router),t.use("/playground",Qb().router);let o=nT();return t.use("/cliJs",o.router),t.use("/standalone-browser",iT().standaloneBrowserRoutes(e)),t.use("/hybrid",uT().hybridRoutes(e)),t.use((i,a)=>{a.status(404).send("Endpoint Not Found")}),t}});var gT=C((qF,hT)=>{"use strict";var{ArgError:fT}=(K(),w(Z)),G0=ot(),{lazyRequire:od}=(Je(),w(Tt)),{prepareChromeDriver:V0}=ks();hT.exports={init:H0};async function H0({agentPort:s,agentBind:e,project:t,token:r,installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i},a){await z0({installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i,project:t}),await K0({agentPort:s,agentBind:e,project:t,token:r},a)}function K0({agentPort:s,agentBind:e,project:t,token:r},n){return new Promise((o,i)=>{let a=()=>{};t&&(G0.init(t,r),a=m=>{m.use((h,g,y)=>{h.project=t,y()})});let c=mT()(a,n),u=require("http").createServer(c);u.listen(s,e),u.on("error",p),u.on("listening",f);function p(m){if(m.syscall!=="listen")return i(m);switch(m.code){case"EACCES":case"EPERM":return i(new fT(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return i(new fT(`Port ${s} is already in use, is another Testim instance running?`));default:return i(m)}}function f(){let{port:m}=u.address();console.log(`Running on port: ${m}`),J0()}})}function z0({installPlaygroundPlaywrightDeps:s,installPlaygroundPuppeteerDeps:e,installPlaygroundSeleniumDeps:t,project:r}){let n=[];return s&&n.push(od("playwright")),e&&n.push(od("puppeteer")),t&&n.push(od("selenium-webdriver"),V0({projectId:r})),Promise.all(n)}async function J0(){let s=require("prompts"),e=process.platform==="darwin";await s({type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:r=>r.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}});var td=C((jF,xT)=>{"use strict";var or=require("path"),ve=require("fs-extra"),X0=require("ms"),Y0=require("ws"),yT=require("chrome-launcher"),ET=(ne(),w(ce)),{ArgError:Q0}=(K(),w(Z)),{lazyRequire:Z0}=(Je(),w(Tt)),vT=ks(),{downloadAndSave:wT,unzipFile:bT,getCdpAddressForHost:ad,TESTIM_BROWSER_DIR:mn,promiseFromCallback:id}=(M(),w(q)),eL=require("ora"),{downloadAndInstallChromium:tL,CHROMIUM_VERSION:sL}=(Ea(),w(Up)),rL=ET.WEBDRIVER_DEBUG?"verbose":"silent",nL=X0("1h"),nr=or.join(mn,"profile"),oL="DevToolsActivePort",fi=or.join(nr,oL);xT.exports={runAgentMode:iL,getStartedWithStart:aL};async function iL(s){var r;let e;if(await vT.preparePlayer(s.playerLocation,s.canary),s.startTestimBrowser){await uL();try{e=await lL(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new Q0('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=gT();return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>Qo());let o=["webpack"];for(let i of o)await Z0(i,{silent:!0}).catch(()=>{})},6e3),t.init(s,e)}var ST=!1;function aL(){return ST}function TT(s){try{return process.kill(s,0)}catch{return!1}}async function cL(s,e,t){let r=or.join(mn,`chrome-${sL}-process`),n=3e3,o=()=>{ve.removeSync(r),console.log(`
578
+ `,r=await w0(`tst-playground-${Date.now()}.js`,t),n=b0(r);Ts[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{Ts[e]&&(Ts[e].kill(),delete Ts[e])}}async function E0({code:s,type:e}){if(["playwright","puppeteer","selenium"].includes(e))return T0({code:s});throw new h0}async function v0(){Object.keys(Ts).forEach(s=>{Ts[s].kill(),delete Ts[s]})}rd.exports={CODE_TYPES:y0,runPlaygroundTest:E0,stopPlaygroundTest:v0}});var eT=C((LF,Zb)=>{"use strict";var S0=require("express"),nd=S0.Router(),Qb=(U(),y(H)).getLogger("playground-router"),{ClientError:I0,PlaygroundCodeError:x0}=(K(),y(Z)),{runPlaygroundTest:R0,stopPlaygroundTest:C0,CODE_TYPES:P0}=Jb(),{DISABLE_AGENT_ORIGIN_CHECK:k0}=(ne(),y(ce)),Xb=["localhost","app.testim.io","playground.testim.io","staging.testim.io","app.staging.testim.cc","tta-crm.tricentis.com"],Yb=s=>{if(!s)return{};try{return new URL(s)}catch{return{}}},A0=(s,e,t)=>{if(k0)return t();let r=s.headers.referer,n=s.headers.origin;if(!r&&!n)return e.status(400).send();let o=Yb(r),i=Yb(n);return!Xb.includes(o.hostname)&&!Xb.includes(i.hostname)?e.status(400).send():t()};nd.post("/run",[A0],async(s,e)=>{let t=s.body||{},{code:r,type:n}=t;if(!r||!P0.includes(n)){e.status(400).send({success:!1,reason:"missing arguments"});return}try{await R0(t),e.send({success:!0})}catch(o){if(o instanceof I0){e.status(404).send({success:!1});return}if(o instanceof x0){e.json({success:!1,type:"playground-error",stack:o.innerStack});return}e.json({success:!1,reason:o.message}),Qb.error(o)}});nd.post("/stop",(s,e)=>{try{C0(),e.send({success:!0})}catch(t){e.json({success:!1,reason:t.message}),Qb.error(t)}});Zb.exports.router=nd});var nT=C((DF,rT)=>{"use strict";var _0=require("express"),sT=fs(),{NpmPackageError:O0,TimeoutError:N0}=(K(),y(Z)),nr=(U(),y(H)).getLogger("cli-router"),tT=require("chalk"),od=_0.Router();od.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:u}=s.body;if(typeof t!="string"||!r||!n||!o||!i||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let p=await sT.runCodeWithPackages(t,r,n,o,i,a,c,l,u);p.success||(console.log(tT.red(p.result.resultValue)),nr.error("CLI Action Failure",{message:p.result.resultValue})),e.status(200).json({success:!0,data:p})}catch(p){nr.error("failed to run cli code",{err:p}),console.log(tT.red("failed to run cli code",p)),e.status(500).json({success:!1,code:"internal-error"})}});od.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:o,stepResultId:i,timeout:a}=s.body;if(!t||typeof o!="object"||!r||typeof n!="number"||!i||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let c=await sT.installPackage(t,r,n,o,i,a);nr.info("installed packages successfully"),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof O0){nr.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 N0){nr.error("timeout installing node package"),e.status(200).json({success:!1,code:"timeout"});return}nr.error("failed to install node packages",{err:c}),e.status(500).json({success:!1,code:"internal-error"})}});rT.exports=od});var iT=C((MF,oT)=>{"use strict";var L0=nT(),D0=fs(),M0=(U(),y(H)).getLogger("cli-service");D0.cleanLocalPackageInstallFolder().catch(s=>M0.warn("failed to clean local package folder",{err:s}));oT.exports={router:L0}});var cT=C((FF,aT)=>{"use strict";var F0=require("express");aT.exports={standaloneBrowserRoutes:U0};function U0(s){let e=F0.Router();return e.get("/cdp-url",(t,r)=>{if(!s){r.status(503).send({error:"Testim standalone browser is not running"});return}r.status(200).send({url:s.webdriverApi.cdpUrl})}),e.get("/status",(t,r)=>{if(!s){r.status(503).send({ok:!1});return}r.status(200).send({ok:!0})}),e}});var pT=C((UF,dT)=>{"use strict";var lT=Jo(),q0=require("express"),uT=(U(),y(H)).getLogger("hybrid-router");dT.exports.hybridRoutes=function(e){let t=q0.Router();return t.post("/run",(r,n)=>{var c;if(!((c=r.body)!=null&&c.step)){n.status(400).send({error:"Missing step"});return}let{step:o,context:i,loginData:a}=r.body;e.webdriverApi||n.status(503).send({success:!1,reason:"Testim Agent was not started with Testim Start."}),r.setTimeout(0),lT.execute(o,i,e.webdriverApi,a,void 0,"agent").then(l=>{n.status(200).send(l)}).catch(l=>{uT.error("failed to run hybrid code",{e:l}),n.status(500).send(Object.assign({success:!1,error:l}))})}),t.post("/abort",(r,n)=>{var o;if(!((o=r.body)!=null&&o.stepResultId)){n.status(400).send({error:"missing stepResultId"});return}try{lT.abort(r.body.stepResultId),n.status(204).end()}catch(i){if(i&&i.message==="No such stepResultId"){n.status(400).send({error:"No such stepResultId"});return}uT.error("hybrid code abort unexpected error",{e:i}),n.status(500).send({error:"unexpected error",info:`${i?i.message:"N/A"}`})}}),t}});var hT=C((qF,fT)=>{"use strict";var j0=require("compression"),$0=require("express"),mT=require("body-parser"),B0=require("cors"),{IS_ON_PREM:W0,DISABLE_AGENT_ORIGIN_CHECK:G0}=(ne(),y(ce));fT.exports=function(s,e){let t=$0();s(t),t.use(mT.urlencoded({extended:!1,limit:"50mb"})),t.use(j0()),t.use(mT.json({limit:"50mb"}));let n={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:W0||G0?"*":["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"]};t.use("*",B0(n)),Vb()(t),t.use("/files",zb().router),t.use("/playground",eT().router);let o=iT();return t.use("/cliJs",o.router),t.use("/standalone-browser",cT().standaloneBrowserRoutes(e)),t.use("/hybrid",pT().hybridRoutes(e)),t.use((i,a)=>{a.status(404).send("Endpoint Not Found")}),t}});var wT=C((jF,yT)=>{"use strict";var{ArgError:gT}=(K(),y(Z)),V0=ot(),{lazyRequire:id}=(Xe(),y(Tt)),{prepareChromeDriver:H0}=ks();yT.exports={init:K0};async function K0({agentPort:s,agentBind:e,project:t,token:r,installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i},a){await J0({installPlaygroundPlaywrightDeps:n,installPlaygroundPuppeteerDeps:o,installPlaygroundSeleniumDeps:i,project:t}),await z0({agentPort:s,agentBind:e,project:t,token:r},a)}function z0({agentPort:s,agentBind:e,project:t,token:r},n){return new Promise((o,i)=>{let a=()=>{};t&&(V0.init(t,r),a=m=>{m.use((h,g,w)=>{h.project=t,w()})});let c=hT()(a,n),u=require("http").createServer(c);u.listen(s,e),u.on("error",p),u.on("listening",f);function p(m){if(m.syscall!=="listen")return i(m);switch(m.code){case"EACCES":case"EPERM":return i(new gT(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return i(new gT(`Port ${s} is already in use, is another Testim instance running?`));default:return i(m)}}function f(){let{port:m}=u.address();console.log(`Running on port: ${m}`),X0()}})}function J0({installPlaygroundPlaywrightDeps:s,installPlaygroundPuppeteerDeps:e,installPlaygroundSeleniumDeps:t,project:r}){let n=[];return s&&n.push(id("playwright")),e&&n.push(id("puppeteer")),t&&n.push(id("selenium-webdriver"),H0({projectId:r})),Promise.all(n)}async function X0(){let s=require("prompts"),e=process.platform==="darwin";await s({type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:r=>r.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}});var sd=C(($F,CT)=>{"use strict";var ir=require("path"),ve=require("fs-extra"),Y0=require("ms"),Q0=require("ws"),bT=require("chrome-launcher"),ST=(ne(),y(ce)),{ArgError:Z0}=(K(),y(Z)),{lazyRequire:eN}=(Xe(),y(Tt)),IT=ks(),{downloadAndSave:TT,unzipFile:ET,getCdpAddressForHost:cd,TESTIM_BROWSER_DIR:hn,promiseFromCallback:ad}=(M(),y(q)),tN=require("ora"),{downloadAndInstallChromium:sN,CHROMIUM_VERSION:rN}=(va(),y(qp)),nN=ST.WEBDRIVER_DEBUG?"verbose":"silent",oN=Y0("1h"),or=ir.join(hn,"profile"),iN="DevToolsActivePort",fi=ir.join(or,iN);CT.exports={runAgentMode:aN,getStartedWithStart:cN};async function aN(s){var r;let e;if(await IT.preparePlayer(s.playerLocation,s.canary),s.startTestimBrowser){await dN();try{e=await uN(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new Z0('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=wT();return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>Qo());let o=["webpack"];for(let i of o)await eN(i,{silent:!0}).catch(()=>{})},6e3),t.init(s,e)}var xT=!1;function cN(){return xT}function vT(s){try{return process.kill(s,0)}catch{return!1}}async function lN(s,e,t){let r=ir.join(hn,`chrome-${rN}-process`),n=3e3,o=()=>{ve.removeSync(r),console.log(`
579
579
 
580
- Browser session ended`),process.exit(0)};if(ve.existsSync(r)){let m=ve.readJSONSync(r);if(TT(m.pid)){let h=()=>TT(m.pid)?setTimeout(h,n):o();return h(),{webdriverApi:m}}}let i=await tL();await ve.pathExists(nr)||await ve.mkdirp(nr);let c=[...IT(nr,e,t,i).desiredCapabilities.chromeOptions.args,...yT.Launcher.defaultFlags().filter(m=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(m))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,p=await yT.launch({chromeFlags:c,startingUrl:u,ignoreDefaultFlags:!0,userDataDir:nr,chromePath:i,envVars:l}),f={port:p.port,pid:p.pid,cdpUrl:await ad(`localhost:${p.port}`)};return ve.writeJSONSync(r,f),p.process.once("exit",o),p.process.once("close",o),{webdriverApi:f}}async function lL(s){let e=`${ET.EDGE_URL}/extension/testim-full-master.zip`,t=or.basename(e),r=or.join(mn,t),n=or.join(mn,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await ve.pathExists(r)){let m=await ve.stat(r);o=Date.now()-nL>m.mtimeMs}if(await ve.mkdirp(mn),o){let m=eL("Downloading Testim Editor").start();await wT(e,r);try{await bT(r,n)}catch{await ve.remove(r),await wT(e,r);try{await bT(r,n)}catch{throw await ve.remove(r),m.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await ve.remove(n)}m.succeed()}let i=s.extensionPath?null:(await ve.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await cL(s,i,n);await vT.prepareChromeDriver({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=IT(nr,i,s.extensionPath,s.chromeBinaryLocations),c=Xr(),{SeleniumPerfStats:l}=Gs(),u=new c;u.seleniumPerfStats=new l;let p=await u.initClient(a);ST=!0;let f=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await u.url(f),u.initialUrl=f;try{u.cdpUrl=await ad(p.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:u}}function IT(s,e,t,r){let n=e?[e]:[],o=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&o.push(`--load-extension=${t}`),{logLevel:rL,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function uL(){if(await ve.pathExists(fi))try{let{webSocketDebuggerUrl:s}=await dL();await pL(s),await ve.unlink(fi)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await ve.unlink(fi)}}async function dL(){let s=await ve.readFile(fi,{encoding:"utf8"}),[e,t]=s.split(`
581
- `).map(o=>o.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await ad(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function pL(s,e=100){let t=await mL(s,e);return id(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function mL(s,e=100){let t=new Y0(s,{timeout:e}),r=id(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=id(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}});var $F=require("source-map-support/register");var pd;(pd=Array.prototype).at||(pd.at=function(s){let e=Number.isInteger(s)?s:0,t=e>=0?e:this.length+e;if(!(t<0||t>=this.length))return this[t]});var md=require("perf_hooks");var vn=S(require("os")),cr=S(require("url")),lr=S(require("http")),gi=S(require("https")),gn=S(require("form-data"));var yn=class{constructor(){this.onloadstart=null,this.onprogress=null,this.onabort=null,this.onerror=null,this.onload=null,this.ontimeout=null,this.onloadend=null,this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]=this._listeners[e]||[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let o of r)o==null||o.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},wn=class extends yn{constructor(e){super(),this._request=e,this._reset()}_reset(){this._contentType=null,this._body=null}_setData(e){if(!(typeof e>"u"||e===null))if(typeof e=="string")e.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(e,"utf8");else if(Buffer.isBuffer(e))this._body=e;else if(e instanceof ArrayBuffer){let t=Buffer.alloc(e.byteLength),r=new Uint8Array(e);for(let n=0;n<e.byteLength;n++)t[n]=r[n];this._body=t}else if("buffer"in e&&e.buffer instanceof ArrayBuffer){let t=Buffer.alloc(e.byteLength),r=e.byteOffset,n=new Uint8Array(e.buffer);for(let o=0;o<e.byteLength;o++)t[o]=n[o+r];this._body=t}else if(typeof e=="object"&&e instanceof gn.default)this._body=null;else throw new Error(`Unsupported send() data ${e}`)}_finalizeHeaders(e,t){this._contentType&&!("content-type"in t)&&(e["Content-Type"]=this._contentType),this._body&&(e["Content-Length"]=this._body.length.toString())}_startUpload(e){this._body&&e.write(this._body),e.end()}},ar=class{constructor(e){this.type=e,this.target=null,this.currentTarget=null,this.lengthComputable=!1,this.loaded=0,this.total=0,this.bubbles=!1,this.cancelable=!1}},bn=class extends Error{},Tn=class extends Error{},En=class extends Error{},Wt=class extends Error{},ye=class extends yn{UNSENT=0;OPENED=1;HEADERS_RECEIVED=2;LOADING=3;DONE=4;nodejsHttpAgent=lr.globalAgent;nodejsHttpsAgent=gi.globalAgent;nodejsBaseUrl=null;_restrictedMethods={CONNECT:!0,TRACE:!0,TRACK:!0};_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};_privateHeaders={"set-cookie":!1,"set-cookie2":!1};_userAgent=`Mozilla/5.0 (${vn.type()} ${vn.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;constructor(e){super(),this.onreadystatechange=null,this._anonymous=e==null?void 0:e.anon,this.readyState=ye.UNSENT,this.response=null,this.responseText="",this.responseType="",this.status=0,this.statusText="",this.timeout=0,this.upload=new wn(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}static nodejsSet(e){ye.prototype.nodejsSet(e)}nodejsSet(e){if("httpAgent"in e&&(this.nodejsHttpAgent=e.httpAgent),"httpsAgent"in e&&(this.nodejsHttpsAgent=e.httpsAgent),"baseUrl"in e){let t=e.baseUrl;if(t!==null&&!cr.parse(t,!1,!0).protocol)throw new bn("baseUrl must be an absolute URL");this.nodejsBaseUrl=t}}open(e,t,r,n,o){if(e=e.toUpperCase(),e in this._restrictedMethods)throw new En(`HTTP method ${e} is not allowed in XHR`);let i=this._parseUrl(t);r===void 0&&(r=!0),this._method=e,this._url=i,this._sync=!r,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(ye.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(e,t){if(this.readyState!==ye.OPENED)throw new Wt("XHR readyState must be OPENED");let r=e.toLowerCase();this._restrictedHeaders[r]||/^sec\-/.test(r)||/^proxy-/.test(r)||(t=t.toString(),r in this._loweredHeaders?(e=this._loweredHeaders[r],this._headers[e]=`${this._headers[e]}, ${t}`):(this._loweredHeaders[r]=e,this._headers[e]=t))}send(e){if(this.readyState!==ye.OPENED)throw new Wt("XHR readyState must be OPENED");if(this._request)throw new Wt("send() already called");switch(this._url.protocol){case"file:":this._sendFile(e);break;case"http:":case"https:":this._sendHttp(e);break;default:throw new Tn(`Unsupported protocol ${this._url.protocol}`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(e){var r;let t=e.toLowerCase();return((r=this._responseHeaders)==null?void 0:r[t])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([e,t])=>`${e}: ${t}`).join(`\r
582
- `):""}overrideMimeType(e){if([ye.LOADING,ye.DONE].includes(this.readyState))throw new Wt("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=e.toLowerCase()}_setReadyState(e){this.readyState=e;let t=new ar("readystatechange");this.dispatchEvent(t)}_sendFile(){throw this._url.method!=="GET"?new Tn("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(e){if(this._sync)throw new Error("Synchronous XHR processing not implemented");e!=null&&(this._method==="GET"||this._method==="HEAD")?e=null:e=e||"",this.upload._setData(e),this._finalizeHeaders(e),this._sendHxxpRequest(e)}_sendHxxpRequest(e){let t=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,n=(this._url.protocol==="http:"?lr:gi).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:t});typeof e=="object"&&e instanceof gn.default&&e.pipe(n),this._request=n,this.timeout&&n.setTimeout(this.timeout,()=>this._onHttpTimeout(n)),n.on("response",o=>this._onHttpResponse(n,o)),n.on("error",()=>this._onHttpRequestError(n)),this.upload._startUpload(n),this._request===n&&this._dispatchProgress("loadstart")}_finalizeHeaders(e){typeof e=="object"&&e instanceof gn.default&&Object.assign(this._headers,e.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(e,t){if(this._request!==e)return;if([301,302,303,307,308].includes(t.statusCode)){this._url=this._parseUrl(t.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=t,this._response.on("data",n=>this._onHttpResponseData(t,n)),this._response.on("end",()=>this._onHttpResponseEnd(t)),this._response.on("close",()=>this._onHttpResponseClose(t)),this.status=this._response.statusCode,this.statusText=lr.STATUS_CODES[this.status],this._parseResponseHeaders(t);let r=this._responseHeaders["content-length"];r?(this._totalBytes=parseInt(r,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(ye.HEADERS_RECEIVED)}_onHttpResponseData(e,t){if(this._response===e)return this._responseParts.push(t),this._loadedBytes+=t.length,this.readyState!==ye.LOADING&&this._setReadyState(ye.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(e){if(this._response===e)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(ye.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(e){if(this._response!==e)return;let t=this._request;return this._setError(),t.abort(),this._setReadyState(ye.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(e){if(this._request===e)return this._setError(),e.abort(),this._setReadyState(ye.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(e){if(this._request===e)return this._setError(),e.abort(),this._setReadyState(ye.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(e){let t=new ar(e);t.lengthComputable=this._lengthComputable,t.loaded=this._loadedBytes,t.total=this._totalBytes,this.dispatchEvent(t)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(e){let t,r,n,o=this.nodejsBaseUrl===null?e:cr.resolve(this.nodejsBaseUrl,e),i=cr.parse(o,!1,!0);return i.hash=null,i.auth&&(typeof n<"u"&&n!==null||typeof r<"u"&&r!==null)&&(t=i.auth.indexOf(":"),t===-1?n||(n=i.auth):(n||(n=i.substring(0,t)),r||(r=i.substring(t+1)))),(n||r)&&(i.auth=`${n}:${r}`),i}_parseResponseHeaders(e){this._responseHeaders={},Object.entries(e.headers).forEach(([t,r])=>{let n=t.toLowerCase();this._privateHeaders[n]||(this._mimeOverride!==null&&n==="content-type"&&(r=this._mimeOverride),this._responseHeaders[n]=r)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let e=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(e=require("zlib").gunzipSync(e)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(e);break;case"json":this.responseText=null;try{this.response=JSON.parse(e.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=e;break;case"arraybuffer":{this.responseText=null;let t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let n=0;n<e.length;n++)r[n]=e[n];this.response=t;break}default:this._parseTextResponse(e)}}_parseTextResponse(e){try{this.responseText=e.toString(this._parseResponseEncoding())}catch{this.responseText=e.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let e=this._responseHeaders["content-type"],t=/\;\s*charset\=(.*)$/.exec(e);return e&&t?t[1]:"utf-8"}},Se=ye;Ue(Se,"SyntaxError",bn),Ue(Se,"ProgressEvent",ar),Ue(Se,"SecurityError",En),Ue(Se,"XMLHttpRequest",ye),Ue(Se,"InvalidStateError",Wt),Ue(Se,"XMLHttpRequestUpload",wn),Ue(Se,"UNSENT",0),Ue(Se,"OPENED",1),Ue(Se,"HEADERS_RECEIVED",2),Ue(Se,"LOADING",3),Ue(Se,"DONE",4);Object.assign(global,{xhr2:Se,XMLHttpRequest:Se,performance:md.performance,...typeof Blob>"u"&&{Blob:require("buffer").Blob}});var RT=S(require("semver")),fn=S(Ie());Da();var $t=S(Ct()),CT=S(ks()),PT=require("events");ee();Mr();K();ee();$n();U();var em=S(require("os")),Ua=S(require("path")),qa=S(require("chalk")),zn=require("fs-extra");function tm(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=em.homedir();(0,zn.ensureDirSync)(Ua.resolve(n,".testim_logs"));let o=Ua.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=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(i=>i.includes("player-require-path"))&&(console.log(qa.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(qa.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,zn.writeFileSync)(o,`${s}
580
+ Browser session ended`),process.exit(0)};if(ve.existsSync(r)){let m=ve.readJSONSync(r);if(vT(m.pid)){let h=()=>vT(m.pid)?setTimeout(h,n):o();return h(),{webdriverApi:m}}}let i=await sN();await ve.pathExists(or)||await ve.mkdirp(or);let c=[...RT(or,e,t,i).desiredCapabilities.chromeOptions.args,...bT.Launcher.defaultFlags().filter(m=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(m))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,p=await bT.launch({chromeFlags:c,startingUrl:u,ignoreDefaultFlags:!0,userDataDir:or,chromePath:i,envVars:l}),f={port:p.port,pid:p.pid,cdpUrl:await cd(`localhost:${p.port}`)};return ve.writeJSONSync(r,f),p.process.once("exit",o),p.process.once("close",o),{webdriverApi:f}}async function uN(s){let e=`${ST.EDGE_URL}/extension/testim-full-master.zip`,t=ir.basename(e),r=ir.join(hn,t),n=ir.join(hn,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await ve.pathExists(r)){let m=await ve.stat(r);o=Date.now()-oN>m.mtimeMs}if(await ve.mkdirp(hn),o){let m=tN("Downloading Testim Editor").start();await TT(e,r);try{await ET(r,n)}catch{await ve.remove(r),await TT(e,r);try{await ET(r,n)}catch{throw await ve.remove(r),m.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await ve.remove(n)}m.succeed()}let i=s.extensionPath?null:(await ve.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await lN(s,i,n);await IT.prepareChromeDriver({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=RT(or,i,s.extensionPath,s.chromeBinaryLocations),c=Qr(),{SeleniumPerfStats:l}=Gs(),u=new c;u.seleniumPerfStats=new l;let p=await u.initClient(a);xT=!0;let f=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await u.url(f),u.initialUrl=f;try{u.cdpUrl=await cd(p.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:u}}function RT(s,e,t,r){let n=e?[e]:[],o=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&o.push(`--load-extension=${t}`),{logLevel:nN,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function dN(){if(await ve.pathExists(fi))try{let{webSocketDebuggerUrl:s}=await pN();await mN(s),await ve.unlink(fi)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await ve.unlink(fi)}}async function pN(){let s=await ve.readFile(fi,{encoding:"utf8"}),[e,t]=s.split(`
581
+ `).map(o=>o.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await cd(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function mN(s,e=100){let t=await fN(s,e);return ad(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function fN(s,e=100){let t=new Q0(s,{timeout:e}),r=ad(o=>{t.once("open",o)}).then(()=>{t.removeAllListeners()}),n=ad(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return Promise.race([r,n]).then(()=>t)}});var BF=require("source-map-support/register");var md;(md=Array.prototype).at||(md.at=function(s){let e=Number.isInteger(s)?s:0,t=e>=0?e:this.length+e;if(!(t<0||t>=this.length))return this[t]});var fd=require("perf_hooks");var In=S(require("os")),lr=S(require("url")),ur=S(require("http")),yi=S(require("https")),wn=S(require("form-data"));var bn=class{constructor(){this.onloadstart=null,this.onprogress=null,this.onabort=null,this.onerror=null,this.onload=null,this.ontimeout=null,this.onloadend=null,this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]=this._listeners[e]||[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let o of r)o==null||o.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},Tn=class extends bn{constructor(e){super(),this._request=e,this._reset()}_reset(){this._contentType=null,this._body=null}_setData(e){if(!(typeof e>"u"||e===null))if(typeof e=="string")e.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(e,"utf8");else if(Buffer.isBuffer(e))this._body=e;else if(e instanceof ArrayBuffer){let t=Buffer.alloc(e.byteLength),r=new Uint8Array(e);for(let n=0;n<e.byteLength;n++)t[n]=r[n];this._body=t}else if("buffer"in e&&e.buffer instanceof ArrayBuffer){let t=Buffer.alloc(e.byteLength),r=e.byteOffset,n=new Uint8Array(e.buffer);for(let o=0;o<e.byteLength;o++)t[o]=n[o+r];this._body=t}else if(typeof e=="object"&&e instanceof wn.default)this._body=null;else throw new Error(`Unsupported send() data ${e}`)}_finalizeHeaders(e,t){this._contentType&&!("content-type"in t)&&(e["Content-Type"]=this._contentType),this._body&&(e["Content-Length"]=this._body.length.toString())}_startUpload(e){this._body&&e.write(this._body),e.end()}},cr=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}},En=class extends Error{},vn=class extends Error{},Sn=class extends Error{},Wt=class extends Error{},ye=class extends bn{UNSENT=0;OPENED=1;HEADERS_RECEIVED=2;LOADING=3;DONE=4;nodejsHttpAgent=ur.globalAgent;nodejsHttpsAgent=yi.globalAgent;nodejsBaseUrl=null;_restrictedMethods={CONNECT:!0,TRACE:!0,TRACK:!0};_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};_privateHeaders={"set-cookie":!1,"set-cookie2":!1};_userAgent=`Mozilla/5.0 (${In.type()} ${In.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;constructor(e){super(),this.onreadystatechange=null,this._anonymous=e==null?void 0:e.anon,this.readyState=ye.UNSENT,this.response=null,this.responseText="",this.responseType="",this.status=0,this.statusText="",this.timeout=0,this.upload=new Tn(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}static nodejsSet(e){ye.prototype.nodejsSet(e)}nodejsSet(e){if("httpAgent"in e&&(this.nodejsHttpAgent=e.httpAgent),"httpsAgent"in e&&(this.nodejsHttpsAgent=e.httpsAgent),"baseUrl"in e){let t=e.baseUrl;if(t!==null&&!lr.parse(t,!1,!0).protocol)throw new En("baseUrl must be an absolute URL");this.nodejsBaseUrl=t}}open(e,t,r,n,o){if(e=e.toUpperCase(),e in this._restrictedMethods)throw new Sn(`HTTP method ${e} is not allowed in XHR`);let i=this._parseUrl(t);r===void 0&&(r=!0),this._method=e,this._url=i,this._sync=!r,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(ye.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(e,t){if(this.readyState!==ye.OPENED)throw new Wt("XHR readyState must be OPENED");let r=e.toLowerCase();this._restrictedHeaders[r]||/^sec\-/.test(r)||/^proxy-/.test(r)||(t=t.toString(),r in this._loweredHeaders?(e=this._loweredHeaders[r],this._headers[e]=`${this._headers[e]}, ${t}`):(this._loweredHeaders[r]=e,this._headers[e]=t))}send(e){if(this.readyState!==ye.OPENED)throw new Wt("XHR readyState must be OPENED");if(this._request)throw new Wt("send() already called");switch(this._url.protocol){case"file:":this._sendFile(e);break;case"http:":case"https:":this._sendHttp(e);break;default:throw new vn(`Unsupported protocol ${this._url.protocol}`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(e){var r;let t=e.toLowerCase();return((r=this._responseHeaders)==null?void 0:r[t])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([e,t])=>`${e}: ${t}`).join(`\r
582
+ `):""}overrideMimeType(e){if([ye.LOADING,ye.DONE].includes(this.readyState))throw new Wt("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=e.toLowerCase()}_setReadyState(e){this.readyState=e;let t=new cr("readystatechange");this.dispatchEvent(t)}_sendFile(){throw this._url.method!=="GET"?new vn("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(e){if(this._sync)throw new Error("Synchronous XHR processing not implemented");e!=null&&(this._method==="GET"||this._method==="HEAD")?e=null:e=e||"",this.upload._setData(e),this._finalizeHeaders(e),this._sendHxxpRequest(e)}_sendHxxpRequest(e){let t=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,n=(this._url.protocol==="http:"?ur:yi).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:t});typeof e=="object"&&e instanceof wn.default&&e.pipe(n),this._request=n,this.timeout&&n.setTimeout(this.timeout,()=>this._onHttpTimeout(n)),n.on("response",o=>this._onHttpResponse(n,o)),n.on("error",()=>this._onHttpRequestError(n)),this.upload._startUpload(n),this._request===n&&this._dispatchProgress("loadstart")}_finalizeHeaders(e){typeof e=="object"&&e instanceof wn.default&&Object.assign(this._headers,e.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(e,t){if(this._request!==e)return;if([301,302,303,307,308].includes(t.statusCode)){this._url=this._parseUrl(t.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=t,this._response.on("data",n=>this._onHttpResponseData(t,n)),this._response.on("end",()=>this._onHttpResponseEnd(t)),this._response.on("close",()=>this._onHttpResponseClose(t)),this.status=this._response.statusCode,this.statusText=ur.STATUS_CODES[this.status],this._parseResponseHeaders(t);let r=this._responseHeaders["content-length"];r?(this._totalBytes=parseInt(r,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(ye.HEADERS_RECEIVED)}_onHttpResponseData(e,t){if(this._response===e)return this._responseParts.push(t),this._loadedBytes+=t.length,this.readyState!==ye.LOADING&&this._setReadyState(ye.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(e){if(this._response===e)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(ye.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(e){if(this._response!==e)return;let t=this._request;return this._setError(),t.abort(),this._setReadyState(ye.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(e){if(this._request===e)return this._setError(),e.abort(),this._setReadyState(ye.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(e){if(this._request===e)return this._setError(),e.abort(),this._setReadyState(ye.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(e){let t=new cr(e);t.lengthComputable=this._lengthComputable,t.loaded=this._loadedBytes,t.total=this._totalBytes,this.dispatchEvent(t)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(e){let t,r,n,o=this.nodejsBaseUrl===null?e:lr.resolve(this.nodejsBaseUrl,e),i=lr.parse(o,!1,!0);return i.hash=null,i.auth&&(typeof n<"u"&&n!==null||typeof r<"u"&&r!==null)&&(t=i.auth.indexOf(":"),t===-1?n||(n=i.auth):(n||(n=i.substring(0,t)),r||(r=i.substring(t+1)))),(n||r)&&(i.auth=`${n}:${r}`),i}_parseResponseHeaders(e){this._responseHeaders={},Object.entries(e.headers).forEach(([t,r])=>{let n=t.toLowerCase();this._privateHeaders[n]||(this._mimeOverride!==null&&n==="content-type"&&(r=this._mimeOverride),this._responseHeaders[n]=r)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let e=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(e=require("zlib").gunzipSync(e)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(e);break;case"json":this.responseText=null;try{this.response=JSON.parse(e.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=e;break;case"arraybuffer":{this.responseText=null;let t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let n=0;n<e.length;n++)r[n]=e[n];this.response=t;break}default:this._parseTextResponse(e)}}_parseTextResponse(e){try{this.responseText=e.toString(this._parseResponseEncoding())}catch{this.responseText=e.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let e=this._responseHeaders["content-type"],t=/\;\s*charset\=(.*)$/.exec(e);return e&&t?t[1]:"utf-8"}},Se=ye;Ue(Se,"SyntaxError",En),Ue(Se,"ProgressEvent",cr),Ue(Se,"SecurityError",Sn),Ue(Se,"XMLHttpRequest",ye),Ue(Se,"InvalidStateError",Wt),Ue(Se,"XMLHttpRequestUpload",Tn),Ue(Se,"UNSENT",0),Ue(Se,"OPENED",1),Ue(Se,"HEADERS_RECEIVED",2),Ue(Se,"LOADING",3),Ue(Se,"DONE",4);Object.assign(global,{xhr2:Se,XMLHttpRequest:Se,performance:fd.performance,...typeof Blob>"u"&&{Blob:require("buffer").Blob}});var PT=S(require("semver")),gn=S(Ie());Ma();var $t=S(Ct()),kT=S(ks()),AT=require("events");ee();Fr();K();ee();Wn();U();var tm=S(require("os")),qa=S(require("path")),ja=S(require("chalk")),Xn=require("fs-extra");function sm(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=tm.homedir();(0,Xn.ensureDirSync)(qa.resolve(n,".testim_logs"));let o=qa.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=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(i=>i.includes("player-require-path"))&&(console.log(ja.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(ja.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Xn.writeFileSync)(o,`${s}
583
583
  ${s==null?void 0:s.stack}
584
584
 
585
- ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Cr();var RI=G("process-handler"),sm=!1;function CI(s){return s instanceof Error?1:sm?0:(s||(s={}),Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:o})=>[t,o].includes(xe.SKIPPED)||[t,o].includes(xe.FAILED)&&n===Xt.EVALUATING?!1:r!==!0)?1:0)}function PI(){try{es("chromedriver").stop()}catch{}}function rm(){sm=!0}async function ja(s){s!=null&&s.stack&&(Ca?console.error(s,s.stack):tm(s)),PI(),await RI.waitForFlush(),process.exit(CI(s))}var kT=S(pe());U();var fL=G("cli-entry");function hL(s){if(!RT.satisfies(process.version,s))throw new L(`Required node version ${s} not satisfied with current version ${process.version}`);let e=14,t=16,r=Number(process.versions.node.split(".")[0]),n=new Date("2023-04-30T00:00:00.000Z")<=new Date;if(r<e)throw new L(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&n)throw new L(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<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 gL(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(M(),q)),Promise.resolve().then(()=>(Sm(),vm)),Promise.resolve().then(()=>(Rm(),KI)).catch(()=>{})]);fn.log("Starting Testim.io CLI"),Ma(ja);try{hL(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{let t=await e.process();if(fn.log("in main, after options.process"),Ni(global.proxyUri),"parallel"in t&&t.parallel>5&&(PT.EventEmitter.defaultMaxListeners=t.parallel*2),Li(t.project),$t.setEncryptKey("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(Je(),Tt));return await o()}if(s.isInitCodimMode(t)){let{init:o}=await Promise.resolve().then(()=>(Nm(),Lm));return o(t.initTestProject)}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await $t.clear(),await Gn(t);let{preloadTests:o}=await Promise.resolve().then(()=>(no(),Za));await o(t),!t.playerRequirePath&&t.mode!==ae.EXTENSION&&await CT.preparePlayer(t.playerLocation,t.canary);let i=await $t.waitForSave();i.success?console.log(`created prefetched data at ${$t.getCacheFileLocation()}`):console.error("failed to create prefetch data",i.error);return}let{default:r}=await Promise.resolve().then(()=>S($b()));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(uc(),lc));await o(t);return}if(s.isAgentMode(t)){let{default:{runAgentMode:o}}=await Promise.resolve().then(()=>S(td()));return o(t)}if(t.saveRCALocally){let{default:{initServer:o}}=await Promise.resolve().then(()=>S(Wc())),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&rm(),fn.log("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([La(t),r.init(t)]);return fn.log("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof Vt)return;let r=s.getArgsOnRemoteRunFailure();return r&&await(0,kT.updateRemoteRunFailure)({...r,error:t.message}).catch(()=>{}),t instanceof L?(console.log("Argument Error:",t.message),t):t instanceof Ht?(console.log("Selenium Error:",t.message),t):(console.log("Error:",t.message),fL.error("runner ended with unexpected error",{err:t}),t)}}gL().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),ja(s)});
585
+ ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Pr();var PI=G("process-handler"),rm=!1;function kI(s){return s instanceof Error?1:rm?0:(s||(s={}),Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:o})=>[t,o].includes(xe.SKIPPED)||[t,o].includes(xe.FAILED)&&n===Xt.EVALUATING?!1:r!==!0)?1:0)}function AI(){try{es("chromedriver").stop()}catch{}}function nm(){rm=!0}async function $a(s){s!=null&&s.stack&&(Pa?console.error(s,s.stack):sm(s)),AI(),await PI.waitForFlush(),process.exit(kI(s))}var _T=S(pe());U();var hN=G("cli-entry");function gN(s){if(!PT.satisfies(process.version,s))throw new N(`Required node version ${s} not satisfied with current version ${process.version}`);let e=14,t=16,r=Number(process.versions.node.split(".")[0]),n=new Date("2023-04-30T00:00:00.000Z")<=new Date;if(r<e)throw new N(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&n)throw new N(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<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 yN(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(M(),q)),Promise.resolve().then(()=>(Im(),Sm)),Promise.resolve().then(()=>(Cm(),JI)).catch(()=>{})]);gn.log("Starting Testim.io CLI"),Fa($a);try{gN(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{let t=await e.process();if(gn.log("in main, after options.process"),Di(global.proxyUri),"parallel"in t&&t.parallel>5&&(AT.EventEmitter.defaultMaxListeners=t.parallel*2),Li(t.project),$t.setEncryptKey("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(Xe(),Tt));return await o()}if(s.isInitCodimMode(t)){let{init:o}=await Promise.resolve().then(()=>(Dm(),Lm));return o(t.initTestProject)}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await $t.clear(),await Hn(t);let{preloadTests:o}=await Promise.resolve().then(()=>(io(),ec));await o(t),!t.playerRequirePath&&t.mode!==ae.EXTENSION&&await kT.preparePlayer(t.playerLocation,t.canary);let i=await $t.waitForSave();i.success?console.log(`created prefetched data at ${$t.getCacheFileLocation()}`):console.error("failed to create prefetch data",i.error);return}let{default:r}=await Promise.resolve().then(()=>S(Wb()));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(dc(),uc));await o(t);return}if(s.isAgentMode(t)){let{default:{runAgentMode:o}}=await Promise.resolve().then(()=>S(sd()));return o(t)}if(t.saveRCALocally){let{default:{initServer:o}}=await Promise.resolve().then(()=>S(Gc())),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&nm(),gn.log("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([La(t),r.init(t)]);return gn.log("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof Vt)return;let r=s.getArgsOnRemoteRunFailure();return r&&await(0,_T.updateRemoteRunFailure)({...r,error:t.message}).catch(()=>{}),t instanceof N?(console.log("Argument Error:",t.message),t):t instanceof Ht?(console.log("Selenium Error:",t.message),t):(console.log("Error:",t.message),hN.error("runner ended with unexpected error",{err:t}),t)}}yN().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),$a(s)});
586
586
  //# sourceMappingURL=cli.js.map