@testim/testim-cli 4.22.0 → 4.23.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 +2 -2
- package/cli.js.map +3 -3
- package/npm-shrinkwrap.json +20 -20
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -411,8 +411,8 @@ ${((S=n.warnings)==null?void 0:S.join(`
|
|
|
411
411
|
${typeof w=="string"?w:w.message||"Unknown error"}`).join("");throw new Error(y)}}catch(f){let h=f.message.match(/Entry module not found: Error: Can't resolve '(.*)'/);throw h&&h.length===2?e.output&&e.output.library==="tdk"?new k(`Could not open dev-kit functions file in ${h[1]}`):new k(`Can't find test files in: '${h[1]}'`):new k(`Compilation Webpack Error in tests: ${f.message}`)}return{tests:[r.map((f,h)=>({code:p.readFileSync(fa.resolve("./dist",`${a[h]}.bundle.js`)),name:f})).map(({code:f,name:h})=>({code:f.toString(),baseUrl:"",name:fa.resolve(h),testConfig:{},testConfigId:null,testId:J(),resultId:J(),isTestsContainer:!0}))],runName:`Testim Dev Kit Run ${new Date().toLocaleString()}`}}function uR(r){let e=dr.fromPairs(Object.keys(process.env).filter(s=>/^TDK_/i.test(s)||s==="BASE_URL").map(s=>[s,process.env[s]])),t={BASE_URL:r==null?void 0:r.baseUrl};return{"process.env":pR({...t,...e})}}function pR(r){return Object.fromEntries(Object.entries(r).map(([e,t])=>[e,JSON.stringify(t)]))}var dr,fa,Uy,pr,rp,sp=T(()=>{"use strict";dr=E(require("lodash")),fa=E(require("path"));B();Uy=E(require("memory-fs"));G();ht();pr={compiler:null,webpackConfig:null};rp=lR});var Wy={};W(Wy,{compileFunctionsLibrary:()=>cp,findTestFolder:()=>Dr,findTests:()=>np,getLocalLocatorContents:()=>op,getLocalLocators:()=>Un,saveLocators:()=>ap,saveTest:()=>ip});async function Un(){let r=await Dr(process.cwd()),e=Xe.join(r,"locators","locators.js");function t(n){let o=n.toString().replace("module.exports =","return").replace(/require/g,"(x => /locator\\.(.*)\\.json/.exec(x)[1])");return new Function(o)()}let s=await st.promises.readFile(e).then(t,()=>({}));return Object.fromEntries(Object.keys(s).map(n=>[n.replace(/"/g,'\\"'),s[n]]))}async function np(r=process.cwd()){let e=await Dr(r),t=await st.promises.readdir(e,{withFileTypes:!0}),s=["webpack.config.js","tsconfig.js",".DS_Store","functions.js"],n=[".html",".json"];return t.filter(o=>!s.includes(o.name)&&!n.some(i=>o.name.endsWith(i))&&o.isFile()&&!o.name.startsWith(".")).map(o=>o.name)}async function dR(r){let e=Object.entries(r),t=e.map(([,n])=>n),s=await Promise.all(t);for(let n=0;n<s.length;n++)e[n][1]=s[n];return Object.fromEntries(e)}async function op(r,e=!1,t=process.cwd()){let s={};if(e){let n=await Dr(t);for(let o of Object.values(r))s[o]=st.promises.readFile(Xe.join(n,"locators",`locator.${o}.json`)).then(JSON.parse)}try{return await dR(s)}catch(n){return console.error(n),{}}}async function ip({body:r,name:e,locators:t,language:s="javascript"}){let n=await Dr(process.cwd()),o=Xe.join(n,"locators","locators.js"),i=Xe.join(n,e);if(!i.startsWith(n))throw new Error("A test name must be a valid file name and inside the tests directory");if(s==="javascript"?i.endsWith(".js")&&!i.endsWith(".test.js")?i=`${i.substr(0,i.length-3)}.test.js`:i.endsWith(".test.js")||(i+=".test.js"):i.endsWith(".ts")&&!i.endsWith(".test.ts")?i=`${i.substr(0,i.length-3)}.test.ts`:i.endsWith(".test.ts")||(i=`${i}.test.ts`),i.endsWith("locators/locators.js"))throw new Error("Cannot override locators file from the internet as it is evaluated by the runner");await st.promises.writeFile(i,r),await st.promises.mkdir(Xe.join(n,"locators")).catch(()=>null);for(let{id:l,body:p}of t)await st.promises.writeFile(Xe.join(n,"locators",`locator.${l}.json`),JSON.stringify(p));let a=Object.fromEntries(t.map(({name:l,id:p})=>[l,p])),c=await Un();Object.assign(c,a),await $y(o,c)}async function $y(r,e){let t=`module.exports = {
|
|
412
412
|
`;for(let[s,n]of Object.entries(e))t+=` "${s}": require('./locator.${n}.json'),
|
|
413
413
|
`;t+="};",await st.promises.writeFile(r,t)}async function ap(r,{mergeIntoExisting:e}={mergeIntoExisting:!1}){let t=await Dr(process.cwd()),s=Xe.join(t,"locators","locators.js");await st.promises.mkdir(Xe.join(t,"locators")).catch(()=>null);for(let{name:o,id:i,elementLocator:a}of r)await st.promises.writeFile(Xe.join(t,"locators",`locator.${i}.json`),JSON.stringify({name:o,id:i,elementLocator:a}));let n=Object.fromEntries(r.map(({name:o,id:i})=>[o,i]));if(e){let o=await Un();Object.assign(n,o)}await $y(s,n)}async function cp({fileSystem:r,bypassWebpack:e}={},t=void 0){let s=await Dr(process.cwd());if(t!=null&&t.aborted)throw new Re;let n=Xe.join(s,"functions.js");if(typeof e!="boolean"&&(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 rp([n],{output:{libraryTarget:"umd",library:"tdk",globalObject:"globalThis"},cache:{type:"memory"},mode:"development"},{},r,t)).tests[0][0].code}var By,Xe,st,Dr,lp=T(()=>{"use strict";By=E(require("lodash")),Xe=E(require("path")),st=require("fs");G();sp();Dr=By.memoize(async r=>(await st.promises.readdir(r)).includes("tests")&&(await st.promises.stat(Xe.join(r,"tests"))).isDirectory()?Xe.join(r,"tests"):r)});async function mr(r,e,t){let s=mR(r.parameterNames.map(n=>n.displayName),e.incomingParams.as);return await Promise.all(s.map(n=>typeof n=="object"&&n.locatedElement?t(n):n))}function mR(r,e){let t=[];for(let s of r){let n=e.functionParameters.indexOf(s);t.push(e.functionArguments[n])}return t}var jn=T(()=>{"use strict"});var Hy={};W(Hy,{execute:()=>fR});async function gR(r,e,t,s,n,o){var a;let i;try{let{WebDriver:c}=await ue("selenium-webdriver");if(o.aborted)throw new Re;let{Executor:l,HttpClient:p}=require("selenium-webdriver/http"),d=r.driver.client.options,m=d.path,f=`${d.protocol}://${d.hostname}:${d.port}`+m,h=new p(f),y=new c(r.getSessionId(),new l(h));await hR(y,r.driver);let S=await mr(t,s,v=>y.findElement({css:v.selector})),b=e.bind(null,y,...S);return i=function(){h.send=async function(){throw new Re}},o.addEventListener("abort",i),await b(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}async function hR(r,e){if(e.cdpUrl){let t=await r.getAllWindowHandles();for(let s of t)if(await r.switchTo().window(s),await r.executeScript("return window.__isMainTestimTab"))break}}var fR,Vy=T(()=>{"use strict";G();ht();jn();fR=gR});var Gy={};W(Gy,{execute:()=>yR});async function bR(r,e,t,s,n,o){var a;let i;try{let c=await ue("puppeteer");if(o.aborted)throw new Re;let l=await c.connect({browserWSEndpoint:r.driver.cdpUrl,defaultViewport:null,product:"chrome"});if(o.aborted)throw l.disconnect(),new Re;i=function(){l.disconnect()},o.addEventListener("abort",i);let p=await l.pages(),d;for(let y of p)if(await y.evaluate(()=>window.__isMainTestimTab)){d=y;break}let m=d||p.at(-1),f=await mr(t,s,y=>m.$(y.selector));return await e.bind(null,m,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,shouldRetry:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}var yR,qy=T(()=>{"use strict";G();ht();jn();yR=bR});var zy={};W(zy,{execute:()=>TR});async function wR(r,e,t,s,n,o){var a;let i;try{let c=await ue("playwright");if(o.aborted)throw new Re;let l=await c.chromium.connect({wsEndpoint:r.driver.cdpUrl});if(o.aborted)throw l.disconnect(),new Re;i=function(){l.disconnect()},o.addEventListener("abort",i);let m=(await(await l.newContext({viewport:null})).pages()).at(-1),f=await mr(t,s,y=>m.$(y.selector));return await e.bind(null,m,...f)(),{success:!0}}catch(c){return o.aborted?{success:!1,shouldRetry:!1,reason:"aborted"}:{success:!1,reason:(c==null?void 0:c.message)||c,extraInfo:(a=c==null?void 0:c.constructor)==null?void 0:a.name}}finally{i&&o.removeEventListener("abort",i)}}var TR,Ky=T(()=>{"use strict";G();ht();jn();TR=wR});var Yy={};W(Yy,{execute:()=>vR});async function ER(r,e,t,s,n,o,i,a){function c(){r.sessionPlayer.stopPlaying()}a.addEventListener("abort",c);function l(C){if(o.parameterValues){let M=o.parameterValues.find($=>$.type==="locate"&&$.id===C.locatorId);return{elementLocator:M.elementLocator,id:M.id,name:"Hybrid Step Locator"}}return C.locatedElement.shadowPath?C.locatedElement.shadowPath[0]:C}let p=await mr(o,t,l),d=e.bind(null,...p),m=J(),g=J(),f=t.testResultId,h=t.config.baseUrl,y=Jy.cloneDeep(t);Object.assign(y,{loginData:s});let S=ee().manifestVersion||"runner",b=!1,v=null,I="master",A=`Execute TDK Function '${o.functionName}'`,_=!0,R={fn:d,bypassSetup:!0,isBeforeOrAfterTest:!0,name:A,sourceCode:d.toString(),sourceName:d.name,testId:m,resultId:J()},D=typeof e.results=="boolean"&&!e.results;try{O("tdkHybridStepPlayback before addAllTabs"),n?(Object.assign(r.sessionPlayer.playbackAutUtils,{frameManager:n}),Object.assign(r.sessionPlayer,{frameManager:n})):await r.addAllTabs(null,{loadInfo:!0,checkForMainTab:!0,takeScreenshots:!D},[r.driver.initialUrl]),r.sessionPlayer.playbackManager.dontAssociateChildResult=!0,r.sessionPlayer.playbackManager.onlyLocalReporting=D,O("tdkHybridStepPlayback before playTestByCode");let C=await new Promise((M,$)=>{i==="agent"&&SR(r,M);function V(){$(new Re),a.removeEventListener("abort",V)}a.addEventListener("abort",V),r.sessionPlayer.playTestByCode(m,g,f,h,y,S,M,b,v,I,[R],A,_).catch($)});return O("tdkHybridStepPlayback after playTestByCode"),{success:C.success,shouldRetry:!1,resultInfo:{testId:m,executionId:g,resultId:R.resultId}}}catch(C){return{success:!1,error:C,shouldRetry:!1}}finally{a.removeEventListener("abort",c)}}function SR(r,e){let{commonConstants:t}=ee();r.sessionPlayer.playbackManager.on(t.playback.START,({testResult:s})=>{let n=s.runnerStatus;Object.defineProperty(s,"runnerStatus",{get(){return n},set(o){n=o,o==="FINISHED"&&e(s)}})})}var Jy,vR,Xy=T(()=>{"use strict";Jy=E(require("lodash"));Oe();B();G();jn();ye();vR=ER});var ga={};W(ga,{abort:()=>dp,execute:()=>Rs,run:()=>xR});async function Rs(r,e,t,s,n,o="cli"){let i=new AbortController,{signal:a}=i;pp.set(e.stepResultId,i);try{O("before seleniumTestPlayer require");let[{SeleniumTestPlayer:c},{compileFunctionsLibrary:l}]=await Promise.all([Promise.resolve().then(()=>(ma(),tp)),Promise.resolve().then(()=>(lp(),Wy))]),{functionName:p=""}=r,d={},m=!1,g=new c(e.id,d,m,Ft.CODEFUL,t);up=g.sessionPlayer.codeSessionPlayer.proxy;let f=r.bypassWebpack?{testim:up.wrappedSteps()}:!1;O("before compileFunctionsLibrary",{bypassWebpack:Boolean(r.bypassWebpack)});let h;try{h=await l({fileSystem:RR,bypassWebpack:f},a)}catch(w){return{success:!1,shouldRetry:!1,reason:`Unable to compile functions library. ${w.message}`,extraInfo:w.stack}}let y;if(f?y=h[p]:(global.globalThis.__testim=up.wrappedSteps(),(0,eval)(h),y=globalThis.tdk[p]),O("after hybridFunction obtain and eval"),!y)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(y.type==="selenium"){let{execute:w}=await Promise.resolve().then(()=>(Vy(),Hy));return await w(g,y,r,e,o,a)}if(y.type==="puppeteer"){if(!g.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running puppeteer code requires the remote debugging protocol to be open. Please contact Testim support."};O("before puppeteerPlayback");let{execute:w}=await Promise.resolve().then(()=>(qy(),Gy));try{return await w(g,y,r,e,o,a)}finally{O("after puppeteerPlayback")}}if(y.type==="playwright"){if(!g.driver.cdpUrl)return{success:!1,shouldRetry:!1,reason:"running playwright code requires the remote debugging protocol to be open. Please contact Testim support."};let{execute:w}=await Promise.resolve().then(()=>(Ky(),zy));return await w(g,y,r,e,o,a)}if(y.type==="tdk"||!y.type){let{execute:w}=await Promise.resolve().then(()=>(Xy(),Yy));O("before tdkPlayback");try{return await w(g,y,e,s,n,r,o,a)}finally{O("after tdkPlayback")}}return{success:!1,shouldRetry:!1,reason:`unknown hybrid format ${y.type}`}}catch(c){IR.info("error running hybrid step",{err:c});return}finally{pp.delete(e.stepResultId)}}function dp(r){let e=pp.get(r);if(!e)throw new Error("No such stepResultId");e.abort()}var Qy,RR,IR,pp,up,xR,ca=T(()=>{"use strict";Qy=E(require("memory-fs"));Oe();j();ae();RR=new Qy.default,IR=x("hybrid-step-playback"),pp=new Map,xR=(r,e,t,s)=>{let{step:n,context:o}=e.data;return Rs(n,o,r,s.loginData)}});var mp={};W(mp,{run:()=>kR});var kR,Zy=T(()=>{"use strict";_r();G();kR=async(r,e)=>{let{stepId:t,testResultId:s,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await hs(t,s,n,i,o,a),success:!0}}catch(c){if(c instanceof xt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof te)return{success:!1,code:"timeout"};throw c}}});async function tb(r,e,t,s){try{return await yl(r,e,t,s)}catch{ha.error("failed to report remote step state",{projectId:r,resultId:e,stepId:t});return}}async function CR(r,e,t,s,n){return ha.info("finished to run remote step",{stepId:t,sessionId:n}),await tb(r,e,t,{status:"completed",success:!0,failureReason:null,data:s})}async function eb(r,e,t,s,n){return ha.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:s}),await tb(r,e,t,{status:"completed",success:!1,failureReason:s})}async function rb(r,e,t,s){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o,userData:i}=r,a=t.type,c=e.getSessionId(),l=t.id;ha.info("start play remote step",{stepType:a,stepId:l,sessionId:c});let p=PR[a];if(!p)return await eb(n,s,l,`Failed to find step type ${a}`,c);try{let d=await p.run(e,t,o,i);return await CR(n,s,l,d,c)}catch(d){return await eb(n,s,l,d.message,c)}}var ha,PR,sb=T(()=>{"use strict";yh();ca();we();Zy();j();ha=x("step-playback"),PR={"cli-validation-code-step":cr,"cli-wait-for-code-step":cr,"cli-action-code-step":cr,"cli-api-code-step":cr,"cli-condition-step":cr,"cli-download-code-step":cr,"node-package":mp,"tdk-hybrid":ga}});var fp,nb,Mr,OR,gp,Be,Bn=T(()=>{"use strict";B();Ct();fp=E(require("ws")),nb=require("events");j();le();Mr=x("socket-ng-service"),OR=5e3,gp=class extends nb.EventEmitter{constructor(){super(...arguments);this.clientId=J();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Mr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),OR)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(s){Mr.error("failed to parse or trigger event",{err:s})}}connect(t){let s=this.formatUrl(od);return Xt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new fp.default(`${s}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Mr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Mr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===fp.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Mr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){Mr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(s){Mr.error("failed to stringify message for sending",{err:s})}}listenOnce(t,s,n){let o=i=>{s(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,s,n,o){function i(c){n(c)&&o(c)}(Array.isArray(s)?s:[s]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=i.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let s=this.filterMap[t];this.sendMessage({type:"add-filter",filter:s})})}addFilter(t,s,n,o=!1){return new Promise(i=>{let a=J(),c={query:s,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",l=>l.id===a,i),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,s){Object.keys(this.listeners).length!==0&&s.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,s){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(s)?s:[s];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},Be=new gp});var ib,hp,_R,LR,DR,ob,ya,fr,ba=T(()=>{"use strict";ib=E(require("p-retry")),hp=E(require("socket.io-client"));le();B();j();_R=50,LR=10,DR=5e3,ob=10*1e3,ya=x("base socket service"),fr=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);ya.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let s=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,s)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,s)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}ya.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${s==null?void 0:s.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===LR&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=_R)throw new Error(`Can't connect to Testim Servers.
|
|
414
|
-
Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{ya.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let s={query:{projectId:e},requestTimeout:ob,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=hp.connect(this.url,s),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let s={query:{projectId:e},requestTimeout:ob,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=hp.connect(this.url,s),this.addSocketHandlers()}emitPromise(e,t){let s={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(s[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,ib.default)(()=>ne(n(),DR),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(s).length>0&&ya.error("Bad acknowledge from socket emit",{errorneousEvents:s})}),this.emitPromiseQueue}}});var ab={};W(ab,{remoteStepServiceSocketIO:()=>MR});var yp,MR,cb=T(()=>{"use strict";ba();yp=class extends fr{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,s){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&s(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},MR=new yp});var lb={};W(lb,{remoteStepService:()=>Ps});var bp,$n,Tp,Ps,Ta=T(()=>{"use strict";Bn();ae();be();({REMOTE_STEP_SAVED:bp}=tt),Tp=class{async init(e){N.flags.useNewWSCLI.isEnabled()||($n=(await Promise.resolve().then(()=>(cb(),ab))).remoteStepServiceSocketIO,$n.init(e))}joinToRemoteStep(e){return N.flags.useNewWSCLI.isEnabled()?Be.addFilter(`${e}:remoteStep`,{resultId:e},[bp]):$n.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(N.flags.useNewWSCLI.isEnabled()){Be.listenTo(`${e}:remoteStep`,[bp],s=>s.resultId===e&&s.remoteStep&&s.remoteStep.status==="pending",s=>t(s.remoteStep));return}$n.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return N.flags.useNewWSCLI.isEnabled()?(Be.removeFilter(`${e}:remoteStep`,[bp]),Promise.resolve()):$n.unlistenToRemoteStep(e)}},Ps=new Tp});var wp,Nr,ub=T(()=>{"use strict";ba();wp=class extends fr{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,s,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===s&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,s){return this.emitPromise("testResult:join",{resultId:t,testId:s})}async joinToTestResult(t,s){this.rooms[t]||this.joinRoom(t,s),await this.emitJoinRoom(t,s)}emitLeaveRoom(t,s){return this.emitPromise("testResult:leave",{resultId:t,testId:s})}leaveTestResult(t,s){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,s)):Promise.resolve()}getSocket(){return this._socket}},Nr=new wp});var db={};W(db,{testResultService:()=>Lt});var pb,vp,Lt,wa=T(()=>{"use strict";pb=require("events");Bn();ae();be();ub();vp=class extends pb.EventEmitter{init(e){if(N.flags.useNewWSCLI.isEnabled()){Be.onConnect=()=>this.emit("socket-connected");return}Nr.init(e),Nr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return N.flags.useNewWSCLI.isEnabled()?Be.addFilter(`${e}:testResult`,{resultId:e,testId:t},[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED]):Nr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(N.flags.useNewWSCLI.isEnabled()){Be.removeFilter(`${e}:testResult`,[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED]);return}await Nr.leaveTestResult(e,t)}listenToTestResult(e,t,s){if(N.flags.useNewWSCLI.isEnabled()){Be.listenTo(`${e}:testResult`,[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>s(n));return}Nr.listenToTestResult(e,t,s)}getSocket(){if(!N.flags.useNewWSCLI.isEnabled())return Nr.getSocket()}},Lt=new vp});var fb,gb,hb,ve,NR,yb,mb,va,bb=T(()=>{"use strict";fb=E(require("lodash"));B();le();Oe();cs();Ct();we();sb();gb=E(require("p-retry")),hb=require("url");j();Xo();fs();ae();Ta();wa();be();ve=x("test-run-handler"),NR=3,yb=20*1e3,mb=r=>JSON.stringify(r).length<yb,va=class{constructor(e,t,s,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Ht;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=s.testStatus,this._testId=s.testId,this._testName=s.name,this._testResultId=s.resultId,this._code=s.code,this._baseUrl=n.baseUrl||s.baseUrl||s.testConfig.baseUrl,this._nativeApp=s.nativeApp,this._overrideTestConfigId=(c=s.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=s.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?Ys(n.browser,n.saucelabs,n.browserstack):s.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get automationMode(){return this._code?"codeful":"codeless"}get code(){return this._code}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getBrowserStackAppPath(e){var t;return this.isAppFromDevice?null:e?e.browserStackAppId:(t=this._nativeApp)==null?void 0:t.browserStackAppId}getSauceLabsAppPath(e,t){var s,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(s=this._nativeApp)==null?void 0:s.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getHeadspinAppPath(e){var t;return this.isAppFromDevice?null:e?e.headSpinAppId:(t=this._nativeApp)==null?void 0:t.headSpinAppId}getTdcAppPath(e){var t;return this.isAppFromDevice?null:e?e.testimTdcAppId:(t=this._nativeApp)==null?void 0:t.testimTdcAppId}get androidActivityWait(){var n;let e=this._nativeApp&&"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if((n=e==null?void 0:e.activity)!=null&&n.includes(e.id))return`${e.id}.*`;let{activity:t}=e;if(!t)return null;let s=t.split(".").pop();return t.replace(s,"*")}get isFFAllowAppFromDeviceEnabled(){return N.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return zs(this._nativeApp)}get isAppForIosVirtualDevice(){return Xr(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?po.FROM_DEVICE:po.FROM_LIBRARY}get nativeAppLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}async getNativeAppData(){let{appId:e,baseUrl:t}=this._options;if(t&&!this._nativeApp&&!e){let s=t||this.baseUrl;if(!s)return null;let[n,o]=s.split(":");return{packageName:n,activity:o}}return this._nativeApp&&!e?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var s,n;let t={tokenV3:await Xt(),refreshToken:Lo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:dd,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&&ft("user-disable-mock"),t.lightweightMode&&((s=this._options.lightweightMode)!=null&&s.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=mb(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),ve.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):ve.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${yb} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await fn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return ve.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this.runMode===Y.EXTENSION&&{code:this.code},...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&mb(e))return;let s=async()=>{try{return await bl(this._options.project,this._testId,this._testResultId,e)}catch(i){return ve.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await s();return await this._testRunStatus.waitForExecutionStartedFinished(),hl(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){O("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},s=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&s.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{O("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};O("before Runtime.evaluate"),await(0,gb.default)(async()=>{let{result:p}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!p.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),O("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return O("after Runtime.evaluate"),l.value}catch(i){throw ve.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let s;try{s=new hb.URL(e)}catch{return}let{username:n,password:o}=s;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let s=!1,n=o=>{if(!s){if(this.isRetryKeyMismatch(o)){ve.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"&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),s=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:p}}=this;try{let d=await kr(a,c,p,l);n(d),s||setTimeout(i,3e3)}catch(d){ve.error("failed to check if done",{err:d}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Lt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:s},branch:n}=this;try{let o=await kr(e,t,s,n),i=["running","completed"];if(i.includes(o.status))return ve.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw ve.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(je.TEST_START_TIMEOUT_MSG)}catch(o){throw ve.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(je.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Lt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(s=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),s(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Lt.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,s(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=fb.debounce(async()=>{try{let i=await kr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(ve.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"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,s(i),!0):!1}catch(i){return ve.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Lt.on("socket-connected",async()=>{try{await Lt.joinToTestResult(this._testResultId,this.testId)}catch(i){ve.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await al(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){ve.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Lt.off("socket-connected",e)}}listenToRemoteStep(e){Ps.listenToRemoteStep(this.testResultId,t=>{rb(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:NR;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,s;return Boolean((s=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:s.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=J(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Ea,Tb=T(()=>{"use strict";bb();Ea=class{constructor(e,t,s,n,o,i){this._waitingTests=s.map(a=>new va(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 FR,UR,Wn,Ep=T(()=>{"use strict";ds();j();FR=x("worker-utils"),UR=async(r,e,t)=>{e&&await ru(r,t)},Wn=async(r,e,t,s)=>{FR.info("releasing player",{hasPlayer:Boolean(s)});try{await(s==null?void 0:s.onDone())}finally{await UR(r,e,t)}}});function VR(r,e,t,s){return{testId:r,reason:s,name:e,resultId:t,success:!1}}var Ra,Sb,Rb,Rp,wt,wb,vb,Eb,Hn,jR,Sp,BR,gr,$R,Sa,WR,HR,GR,nt,Vn=T(()=>{"use strict";Ra=E(require("ms")),Sb=E(require("lodash")),Rb=E(require("moment")),Rp=E(require("p-retry"));B();Oe();ds();we();j();Ep();_t();si();be();Ta();wa();Ze();ae();G();wt=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:wb,TEST_START_TIMEOUT_MSG:vb,TEST_COMPLETE_TIMEOUT_MSG:Eb}=je,{SETUP_TIMEOUT:Hn,NETWORK_ERROR:jR,GRID_ERROR:Sp,BROWSER_CLOSED:BR,SELENIUM_ERROR:gr,UNKNOWN_ERROR:$R,MOBILE_SESSION_ERROR:Sa}=Vs,WR=(0,Ra.default)("1s"),HR=1;GR=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],nt=class{constructor(e,t,s,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=s;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=nt.getWorkerId();this.lambdatestService=new ie;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 HR++}async getGridSlot(e,t){let s=await Hf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,s),s}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return X.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Us(!0)}async getBrowserOnce(e,t,s,n){throw new Us(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!ze({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice,s=e.isAppForIosVirtualDevice;if(t||s){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:s}};return this.onTestIgnored(this.id,o),o}}setSessionTimeout(){var e;return this.options.mode===Y.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===F.BROWSERSTACK?Math.max((0,Ra.default)("600s"),this.options.getSessionTimeout):Math.max((0,Ra.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let s=(o=this.userData)==null?void 0:o.projectId,n;try{O("before getSlotOnce retries");let i=0,a=await(0,Rp.default)(async()=>{let p=Date.now();try{return await ne(this.getSlotOnce(e),this.options.getBrowserTimeout,je.GET_BROWSER_TIMEOUT_MSG)}catch(d){let m={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw d instanceof Gr?wt.info("could not get grid slot due to concurrency issue",m):wt.error("error getting grid slot",{error:d,...m}),i++,await se(this.options.getBrowserTimeout-(Date.now()-p)),d}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});O("after getSlotOnce retries"),O("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,Rp.default)(async()=>{let p=Date.now(),d=this.initPlayer(e);try{a=await Vf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let m=this.setSessionTimeout();O("before getBrowserOnce");let g=await ne(this.getBrowserOnce(e,t,d,a),m,je.GET_BROWSER_TIMEOUT_MSG);return O("after getBrowserOnce"),X.onGetBrowserSuccess(this.id,s),d||g}catch(m){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===Y.APPIUM?"device":"browser";throw wt.error(`error getting ${f} from grid`,{error:m,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),X.onGetBrowserFailure(this.id,s,++l),d.onDone(),!(m instanceof Rt)&&this.options.mode!==Y.APPIUM&&await se(this.options.getBrowserTimeout-(Date.now()-p)),m}},{retries:c-1,minTimeout:0,factor:1}),O("after getBrowserOnce retries")}catch(i){throw await Wn(this.id,this.releaseSlotOnTestFinished,s,n),i instanceof Rt?i:i instanceof It?new br(i,Sp):new br(i,gr)}return n}async runTest(e,t,s){var p;O("inside runTest");let n=(p=this.userData)==null?void 0:p.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Ks(this.options)&&this.handleMobileTest(e);if(i)return i;O("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,l)}finally{await Wn(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var m,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var M,$;if(ze(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice)return e();let w=h.sessionId,S=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof br,v=y&&(S(vb)||S(Eb)),_=N.flags.retryOnSeleniumHubError.isEnabled()&&!!f.reason&&h.isSeleniumHubNoMatchSessionError(f.reason)&&!h.ignoreSeleniumHubError,R=v&&h.hasMoreTimeoutRetries(),D=h.hasMoreRetries()&&!b&&!v,C=!f.success&&(D||R||_);try{let V=h.retryKey;f.testRetryKey=V;let Q=h.getAppSource;if(await this.onTestCompleted(this.id,this.testId,f,w,C,Q),this.executionQueue.hasMoreTests()&&!((M=this.options.lightweightMode)!=null&&M.general)&&await se(WR),await this.runTestCleanup(),C){if(R&&await h.startNewTimeoutRetry(),_){wt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:h.testId,retryReason:f.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let Z=($=this.options.projectData)==null?void 0:$.projectId,me=h.testResultId,Gt=h.testId;await Uo(Z,me,Gt,{show:!1}),h.decreaseSeleniumHubRetry(),h.decreaseRetryCount(),await h.startNewRetry()}return D&&!_&&!R&&await h.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:V,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await p(h,C)}return await e()}catch(V){if(V instanceof zt)return;wt.error("failed to process test result",{error:V}),e();return}},s=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
415
|
-
Please make sure the CLI has stable access to the internet. ${yc()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:w}=Ic,S=f instanceof Error?f.message:f;return S.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),S.includes(wb)?{errorType:Hn,reason:"Test couldn't get device"}:S.includes(y)?{errorType:Sa,reason:"app doesn't exist on device"}:S.includes(w)?{errorType:Sa,reason:"app never started, check app permission or app activity"}:S.includes(h)?{errorType:Sa,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Sa,reason:S}},o=(f,h)=>{let y=this.options.mode===Y.APPIUM?"device":"browser";if(!h&&N.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:jR,reason:s()};let w=f instanceof Error?f.message:f;if(w.includes(wb))return{errorType:Hn,reason:`Test couldn't get ${y}`};if(w.includes(vb))return{errorType:Hn,reason:"Test couldn't be started"};if(w.includes(Eb)){if(!this.testRunTimeout)return{errorType:Hn,reason:"Test timeout reached: test is too long"};let S=Rb.default.duration(this.testRunTimeout,"milliseconds"),b=Math.floor(S.asMinutes()),v=S.seconds(),I=b>0?` ${b} min`:"",A=v>0?` ${v} sec`:"";return{errorType:Hn,reason:`Test timeout reached (timeout:${I}${A}): test is too long`}}if(f instanceof br&&f.type){if(f.type===Sp)return{errorType:Sp,reason:`Test couldn't get ${y} from grid - ${f.message}`};if(f.type===gr)return{errorType:gr,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===BR?{errorType:gr,reason:"Session terminated, it is possible that the cli could not connect to the grid to send keep-alive requests for a prolonged period"}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:gr,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(f.message)?{errorType:gr,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(f.message)?{errorType:gr,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(f.message)?{errorType:gr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:$R,reason:w}},i=async(f,h)=>{var v;let y=await hc();!y&&N.flags.warnOnBadNetwork.isEnabled()&&console.warn(s()),wt.warn("error on run",{err:f});let w=(v=this.userData)==null?void 0:v.projectId,{errorType:S,reason:b}=this.options.mode===Y.APPIUM?n(f):o(f,y);Uo(w,this.testResultId,this.testId,{status:Hs.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:h.retryKey,setupStepResult:{status:Hs.COMPLETED,success:!1,reason:b,errorType:S}},h.remoteRunId),await t(VR(this.testId,this.testName,this.testResultId,b),h,f)},a=async(f,h)=>{var v;let y=this.testId,w=this.testResultId,S=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!w||!S||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let I=await kr(y,w,S,b);if(wt.warn("Test failed. Got results via API",{err:f,testResult:Sb.default.omit(I,GR)}),I&&I.status===Hs.COMPLETED)return await t(I,h);throw f}catch(I){return I!==f&&wt.error("Failed to fetch test results from server",{testId:y,resultId:w,projectId:S,branch:b,err:I}),i(f,h)}},c=this.options.disableSockets||((m=this.options.lightweightMode)==null?void 0:m.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),p=async(f,h)=>{try{await Promise.all([!l&&Ps.joinToRemoteStep(this.testResultId),!c&&Lt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Y.APPIUM&&f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),w=await t(y,f);return O("After onRunComplete"),w}catch(y){return a(y,f)}finally{l||Ps.unlistenToRemoteStep(this.testResultId)}},d=this.executionQueue.getNext();return d?(this.testId=d.testId,this.testName=d.testName,this.testResultId=d.testResultId,this.overrideTestConfigId=d.overrideTestConfigId,this.testRunConfig=d.runConfig,this.branch=d.branch,p(d)):this.onQueueCompleted()}}});var Ib={};W(Ib,{WorkerSelenium:()=>Ip});function zR(r){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))r.playbackManager.on(t,()=>O(`Got event ${t}`))}var Ia,qR,Ip,xb=T(()=>{"use strict";B();Oe();Vn();j();_t();Xo();ae();Wu();G();ma();ye();Ia=x("worker-selenium"),qR=1e9,Ip=class extends nt{initPlayer(t){return new Fn(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){O("in WorkerSelenium getBrowserOnce"),X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ws(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,s,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),O("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),O("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,qR),await this.windowUtils.validatePageIsAvailable(),O("in WorkerSelenium after navigate")}catch(l){let p=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof Rt||p||d?new Rt(`Page '${c}' is not available`):(Ia.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,s){var d;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=s,c=n||"runner";X.onWaitToTestComplete(this.id,this.isCodeMode),zR(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await fn(this.options))[this.testId]);let p=async()=>{if(t.automationMode==="codeful"){a.callOrderScheduler?a.callOrderScheduler.schedule(()=>t.waitForExecutionStartedFinished(),{key:`test-result:${this.userData.projectId}:${this.testResultId}`}):await t.waitForExecutionStartedFinished(),O("right before playTestByCode");let g=new Promise((f,h)=>{a.playTestByCode(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,f,!1,this.overrideTestConfigId,this.branch,t.code,t.testName).catch(h)});return ne(g.then(f=>(O("right after playTestByCode"),f)),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG).catch(f=>{var h;throw f instanceof te&&((h=a.stopPlayingOnTestTimeout)==null||h.call(a)),f}).then(f=>(f.resultId=this.testResultId,f))}let m=!1;return ne(new Promise((g,f)=>{a.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,g,!1,this.overrideTestConfigId,this.branch,m,t.remoteRunId,void 0,void 0,l).catch(f)}),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG).catch(g=>{var f;throw g instanceof te&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),g}).then(async g=>{await o.drain(),g.stepsResults=null,g.resultId=this.testResultId,i.isAlive()||(Ia.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),g.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(Ia.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),g.keepAliveIssue=f);let y={...g,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${y.success?"passed":"failed"}`).catch(()=>{}),y})};i.start(),O("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,s),O("right after super.runTestOnce in workerSelenium");let m=await p();return O("right after runSeleniumTest"),m}catch(m){throw Ia.error("failed to run test once",{err:m}),m}}}});var xa,kb=T(()=>{"use strict";xa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var xp,ka,Pb=T(()=>{"use strict";j();xp=x("mobile-frame-locator-mock"),ka=class{foundFrameCallback(){return xp.info("foundFrameCallback-mock invoked"),{}}locate(){return xp.info("locate-mock invoked"),{}}async findFrame(){return xp.info("findFrame-mock invoked"),{}}}});var KR,JR,Cs,kp=T(()=>{"use strict";KR=E(require("webdriverio"));kb();qu();j();zu();Ku();ye();Zu();Pb();ep();JR=x("appium-test-player"),Cs=class{constructor(e,t,s,n,o=KR,i=void 0,a=void 0){this.id=e;this.driver=o;let{SessionPlayer:c,commonConstants:l,StepActionFactory:p,MobileLocateElementPlayer:d}=ee(),m=new Es(this.driver);this.stepActionFactory=new p(m),da(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new ks(Bi()),this.sessionPlayer=new c(e,{tabService:new xa,cookieUtils:void 0,FrameLocator:ka,portSelector:ji,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,PlaybackManagerFactory:n}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){}async onDone(){var e,t,s;try{await((s=(t=(e=this.driver)==null?void 0:e.activeSessions)==null?void 0:t.get(this.id))==null?void 0:s.deleteSession())}catch(n){JR.error("error while deleting appium session",{error:n})}finally{let{commonConstants:n}=ee();this.sessionPlayer.playbackManager.off(n.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e,t,s;return(s=(t=(e=this.driver)==null?void 0:e.activeSessions)==null?void 0:t.get(this.id))==null?void 0:s.sessionId}}});var Ab={};W(Ab,{WorkerLocalTma:()=>Ap});var Cb,Pa,Pp,Cp,Ap,Ob=T(()=>{"use strict";Cb=E(require("jsdom"));Ze();xn();Vn();B();j();_t();kp();ye();ki();Pa=x("worker-appium"),Pp=class extends Error{},Cp=class extends Error{},Ap=class extends nt{initPlayer(t){return new Cs(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){var d;if(X.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{driver:i}=n,a=this.options.projectData.type,c=await t.getNativeAppData(),l=a==="android"?t.androidActivityWait:null,p=t.nativeAppLink;if(this.options.appId){let{project:m,appId:g,authData:{token:f=""}={}}=this.options;p=await ku({appId:g,projectId:m,token:f})}p&&await this.installApp(this.options.localTmaUrl,this.options.deviceUdid,p);try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(d=this.options.projectData)==null?void 0:d.name}-${this.options.project}`},g=Kg({projectType:a,nativeApp:c,appPath:p,androidActivityWait:l,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),f={capabilities:{udid:this.options.deviceUdid,...g}},h=await this.requestNewAppiumSessionFromTma(this.options.localTmaUrl,f);this.sessionData=h;let y=await i.attach({sessionId:h.sessionId,capabilities:g});i.activeSessions||=new Map,i.activeSessions.set(this.id,y),await xi(t,y,this.options),Pa.info(`init new appium session testName: ${this.testName}`,{sessionId:y.sessionId,testResultId:this.testResultId,nativeApp:c})}catch(m){throw Pa.error("failed to start application",{err:m}),m}}async requestNewAppiumSessionFromTma(t,s){var n,o;try{return{...await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:s,timeout:6e4}),env:"local"}}catch(i){let a=(o=(n=i.response)==null?void 0:n.body)==null?void 0:o.message;throw i.status===404&&(a!=null&&a.startsWith("Ensure that the requested device"))?new Pp(`Device not found: ${a}`):i}}async installApp(t,s,n){var o,i;try{let a=await Nt(n);await Ws(`${t}/api/devices/${s}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw new Cp(`Failed to install app: ${c}`,{cause:a})}}async runTestOnce(t,s){let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=s,c=n||"runner";X.onWaitToTestComplete(this.id,this.isCodeMode),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l=new Cb.JSDOM("").window.DOMParser;a.playbackManager.appiumSessionData=this.sessionData,a.playbackManager.appiumApi=new o(this.sessionData.serverAddress,this.sessionData.sessionId,l),i.initialize({serverUrl:this.options.localRCASaver});let p=async()=>{try{let m=await new Promise((f,h)=>a.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,f,!1,this.overrideTestConfigId,this.branch,!1,t.remoteRunId,void 0,void 0,void 0).catch(h));return await i.drain(),m.stepsResults=null,m.resultId=this.testResultId,{...m,...t.seleniumPerfStats.getStats()}}catch(d){throw Pa.error("error while running appium tests",{err:d}),d}};try{return await super.runTestOnce(t,s),await p()}catch(d){throw Pa.error("failed to run test once",{err:d}),d}}}});var Lb={};W(Lb,{WorkerAppium:()=>Op});var _b,Ca,Op,Db=T(()=>{"use strict";_b=E(require("jsdom"));xn();Vn();j();_t();kp();ye();ki();ae();Ca=x("worker-appium"),Op=class extends nt{initPlayer(e){return new Cs(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){var m;X.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=s,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,{appPath:l,isTdcAppIdExists:p,isHSAppIdExists:d}=await Dg({testRunHandler:e,options:this.options});try{let g={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(m=this.options.projectData)==null?void 0:m.name}-${this.options.project}`},f={projectType:i,nativeApp:a,appPath:l,androidActivityWait:c,sessionTags:g,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,isHSAppIdExists:d,isTdcAppIdExists:p},h;if(this.options.skipLoadBalancer&&this.options.deviceUdid){this.options.lockDevice&&await Og(n,this.options.deviceUdid);let y=await Yg(f);h=await o.remote(y)}else{let y=Jg(f);h=await o.remote(y)}o.activeSessions||=new Map,o.activeSessions.set(this.id,h),Object.assign(o,{activeSession:h}),await xi(e,h,this.options),Ca.info(`init new appium session testName: ${this.testName}`,{sessionId:h.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(g){throw Ca.error("failed to start application",{err:g}),g}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:s,type:n}=this.options.gridData;return n===F.TESTIM_HEADSPIN||n===F.TESTIM_TDC?`https://${e}:${t}/v0/${s}/wd/hub`:`https://${e}:${t}/wd/hub`}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:s,directConnectPort:n,directConnectPath:o}=e;if(t&&s&&n&&o)return`${t}://${s}:${n}${o}`}async runTestOnce(e,t){let{manifestVersion:s,AppiumApi:n,localAssetService:o}=ee(),{sessionPlayer:i}=t,a=t.driver,c=s||"runner",l=a.activeSessions.get(this.id);X.onWaitToTestComplete(this.id,this.isCodeMode),i.playbackManager.executionId=e.executionId,i.playbackManager.executionName=e.executionName;let p;if(this.options.skipLoadBalancer){let{protocol:f,hostname:h,port:y,path:w}=await xu(this.options.gridData,this.options.deviceUdid);p=`${f}://${h}:${y}${w}`}else p=this.getDirectAddressConnection(l.capabilities)||this.getServerAddressFromGrid();let d=new _b.JSDOM("").window.DOMParser,m=l.capabilities;i.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:l.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type},i.playbackManager.appiumApi=new n(p,l.sessionId,d),o.initialize({serverUrl:this.options.localRCASaver});let g=async()=>{try{let h=await new Promise((w,S)=>i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,w,!1,this.overrideTestConfigId,this.branch,!1,e.remoteRunId,void 0,void 0,void 0).catch(S));return await o.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...e.seleniumPerfStats.getStats()}}catch(f){throw Ca.error("error while running appium tests",{err:f}),f}};try{return await super.runTestOnce(e,t),await g()}catch(f){throw Ca.error("failed to run test once",{err:f}),f}}}});var Aa,Mb=T(()=>{"use strict";B();An();G();Aa=class{constructor(e){this.id=e;this.driver=new Or}async onDone(){try{await ne(this.driver.end(),12e4)}catch(t){t instanceof te&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Nb,Oa,Fb=T(()=>{"use strict";Nb=E(require("ws"));B();Oa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Nb.default(this._cdpUrl,{timeout:e}),s=ut(o=>{t.once("open",o)}),n=ut(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([s,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),s=this._cdpCallbacks.get(t.id);s&&(this._cdpCallbacks.delete(t.id),t.error?s.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?s.reject(new Error(t.result.exceptionDetails.exception.description)):s.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,s){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return s&&Object.assign(a,{sessionId:s}),n.send(JSON.stringify(a)),i}}});var La,_p,_a,Ub=T(()=>{"use strict";B();La=E(require("chrome-launcher"));xn();Fb();un();_p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}async init(e,t,s,n,o,i,a,c,l,p){var f,h,y,w;let d=Pi(e,t,s,n,o,i,a),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((w=(y=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:w.args)??[],...La.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await La.launch({chromeFlags:m,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await Sr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),as(()=>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}},_a=class{constructor(e){this.id=e;this.sessionId=J();this.driver=new _p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Bb={};W(Bb,{WorkerExtension:()=>Gn});function YR(r){return r instanceof Error&&"type"in r&&typeof r.type=="string"}function jb(r){return YR(r)?r:new Error(r)}var ot,Gn,Lp=T(()=>{"use strict";Oe();G();Vn();B();j();_t();ae();Mb();Ub();ot=x("worker-ext"),Gn=class extends nt{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new Aa(this.id)}async _getBrowserOnce(e,t,s,n){var i;let{driver:o}=s;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw ot.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,s,n){return X.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,s,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,s){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:s}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:s,executionId:n,testId:o}=this;O("WorkerExtension runTestOnce");let i=async p=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ne(e.runTestUsingCDP(p.cdpTestRunner),d,je.TEST_START_TIMEOUT_MSG)}catch(m){if(!(m instanceof te))throw m;return ot.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:s}),await e.checkViaRestAPIIfTestStarted()}},a=async(p,d,m)=>{try{let g=await p.url(d);return m.driverUrlFinished=!0,g}catch(g){throw ot.error("error from driver.url",{err:g,testResultId:s,executionId:n,testId:o,url:d,urlLength:d.length}),g}},c=async p=>{let d=await e.onStarted(this.options.testStartTimeout);return p.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(O("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){X.onWaitToTestStart(this.id),X.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw ot.warn("failed to run test via CDP",{err:f}),f}}let{driver:d}=t,m={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();X.onWaitToTestStart(this.id);try{await ne(Promise.all([a(t.driver,f,m),c(m)]),this.options.testStartTimeout,je.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof te))throw w;ot.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:s,executionId:n,testId:o,...m}),await e.checkViaRestAPIIfTestStarted()}X.onWaitToTestComplete(this.id,this.isCodeMode);let h=new AbortController,y=w=>{e.onCompletedCleanup(),ot.warn("on browser closed error detected",{err:w,testResultId:s,executionId:n,testId:o}),d.unregisterToClosedBrowser(y),w.type=Vs.BROWSER_CLOSED,h.abort(w)};d.registerToClosedBrowser(y);try{let w=ne(e.onCompleted(),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG),S=await lc(w,h.signal);d.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(I){ot.error("Could not update the grid about the test status",{err:I})}d.isAlive()||(ot.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=d.maxKeepAliveGap();return b>=3e4&&(ot.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(w){throw ot.warn("timeout wait until test completed",{err:w,testResultId:s,executionId:n,testId:o}),jb(w)}finally{d.unregisterToClosedBrowser(y)}}catch(f){throw ot.warn("failed to start url",{err:f}),jb(f)}};t.driver.start();try{return await super.runTestOnce(e,t),O("WorkerExtension super.runTestOnce"),await l()}catch(p){throw ot.error("failed to run test",{err:p,testId:e.testId,resultId:e.testResultId}),p}}}});var $b={};W($b,{WorkerExtensionSingleBrowser:()=>Dp});var XR,QR,Dp,Wb=T(()=>{"use strict";Oe();B();j();Ep();_t();Lp();XR=x("base-worker"),QR=500,Dp=class extends Gn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Wn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,s,n,o){return X.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,s,n,o)}async getTestPlayer(t,s){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(XR.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,s)),this.testPlayer}async runTest(t,s,n){let o=this.handleQuarantine(t);if(o)return o;O("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,s);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await se(QR)}}});function ZR(r,e){e===0?r():setTimeout(r,e*ud)}var Mp,Da,Hb=T(()=>{"use strict";An();B();le();Oe();wu();Ct();Uu();G();j();ae();Tb();Mp=x("parallel-worker-manager"),Da=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(xb(),ge(Ib)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(Ob(),ge(Ab)).WorkerLocalTma:(Db(),ge(Lb)).WorkerAppium;default:return Di.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Wb(),ge($b)).WorkerExtensionSingleBrowser:(Lp(),ge(Bb)).WorkerExtension}}createWorkers(e,t,...s){let n=s[0],o=this.getWorkerType(n),i=()=>{try{return O("before new Worker",n.mode),new o(t,...s)}finally{O("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,s,n,o,i,a,c,l){if(e&&e.length===0)return;let p=!1,d=0,m=g=>new Promise(f=>{var vt,jr,P,L,U,q,it;let h=o.project,y=new Ea(s,n,e,o,i,t),w={},S=e.length,b=((vt=o.company)==null?void 0:vt.ucid)||"",v=(jr=o.company)==null?void 0:jr.companyId,I=(P=o.company)==null?void 0:P.name,A=o.source||"cli",_=o.user,R=(L=o.company)==null?void 0:L.planType,D=(U=o.company)==null?void 0:U.isStartUp,C=(q=o.projectData)==null?void 0:q.name,M=(it=o.projectData)==null?void 0:it.type,$=o.lightweightMode,V=wr(o),Q=(Et,at,Te,Ha,qn,Va)=>(d++,og({executionId:s,projectId:h,testId:at,resultId:Te,ucid:b,companyId:v,companyName:I,projectName:C,companyPlan:R,sessionType:V,source:A,user:_,lightweightMode:$,isStartUp:D,projectType:M,appSource:Va}),t.testStartAndReport(Et,s,Te,Ha,qn)),Z=async(Et,at,Te,Ha,qn,Va)=>{var zp,Kp,Jp;d--;let Qe={...($==null?void 0:$.onlyTestIdsNoSuite)&&{show:!0},...Te.seleniumStats&&{seleniumStats:Te.seleniumStats},...Te.gridIssues&&{gridIssues:Te.gridIssues},...Te.keepAliveIssue&&{keepAliveIssue:Te.keepAliveIssue},...o.host&&{gridHost:o.host}};if(Te.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(Te.seleniumPerfMarks),delete Te.seleniumPerfMarks),o.grid||o.gridId?(Qe.gridName=o.grid||((zp=o.gridData)==null?void 0:zp.name),Qe.gridType=(Kp=o.gridData)==null?void 0:Kp.type,Qe.gridProvider=(Jp=o.gridData)==null?void 0:Jp.provider):o.localTmaUrl?(Qe.gridName="local-tma-from-options",Qe.gridType="local-tma"):o.useLocalChromeDriver?(Qe.gridName="local-chrome-driver-from-options",Qe.gridType="local-chrome"):o.useChromeLauncher?(Qe.gridName="chrome-launcher-from-options",Qe.gridType="local-chrome"):o.browserstack?Qe.gridName="browserstack-from-options":o.saucelabs&&(Qe.gridName="saucelabs-from-options"),await t.testEndAndReport(Et,Te,s,Ha,qn,Qe).catch(qT=>Mp.error("testEndAndReport threw an error",{err:qT})),qn)return;w[Te.resultId]=Te,ig({executionId:s,projectId:h,testId:at,resultId:Te.resultId,result:Te,ucid:b,companyId:v,companyName:I,projectName:C,companyPlan:R,sessionType:V,source:A,user:_,lightweightMode:$,logger:Mp,isStartUp:D,projectType:M,appSource:Va}),l&&!Te.success&&(y.stop(),p=!0),(Object.keys(w).length===S||p&&d===0)&&f(w)},me=(Et,at)=>{w[at.resultId]=at,t.onTestIgnored(Et,at.resultId),d--,(Object.keys(w).length===S||p&&d===0)&&f(w)},Gt=(Et,at)=>t.onGridSlot(Et,at);o.userData={loginData:Object.assign({},Bt(),{refreshToken:Lo(),authData:Bt(),token:g}),projectId:o.project,company:o.company,servicesUrl:fe},O("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,s,Q,Z,Gt,me).forEach((Et,at)=>{O("before schedule worker.run after createWorkers"),ZR(()=>{O("right before worker.run"),Et.run()},at)})});try{let g=await Xt(),f=await m(g);if(p)throw new zt;return f}catch(g){throw Mp.error("failed running parallel workers",{executionId:s,err:g}),g}}}});var Ma,Vb=T(()=>{"use strict";ba();Ma=class extends fr{init(e){return super.initNewSocket(e,"real-data")}emitJoinRoom(e,t){this._socket.emit("testResult:listen",{query:`projectId=${t}&runId=${e}`})}joinToTestResultsByRunId(e,t){this.joinRoom(e,t),this.emitJoinRoom(e,t)}stopListenToTestResultsByRunId(e){this.leaveRoom(e),this._socket.emit("testResult:listen:stop",{})}listenToTestResultsByRunId(e){function t(s){e(s.data)}this._socket.on("testResult:changes",t.bind(this))}}});var Np,Fp,Na,Gb=T(()=>{"use strict";Bn();ae();be();Vb();({TEST_RESULT_CREATED:Np,TEST_RESULT_UPDATED:Fp}=tt),Na=class{constructor(){N.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new Ma)}init(e){return N.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(N.flags.useNewWSCLI.isEnabled())return Be.addFilter(e,{runId:e},[Fp,Np],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(N.flags.useNewWSCLI.isEnabled()){Be.removeFilter(e,[Fp,Np]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(N.flags.useNewWSCLI.isEnabled()){Be.listenTo(e,[Fp,Np],s=>s.runId===e,s=>t(s));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function Kb(r,e){var t;if((t=r.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&r.testId)return{tests:[r.testId.map(n=>({testId:n,testConfig:{},resultId:J()}))]};if(r.files.length>0){let{buildCodeTests:s}=await Promise.resolve().then(()=>(sp(),jy)),n={};if(r.webpackConfig){let o=zb.join(process.cwd(),r.webpackConfig);n=require(o)}return s(r.files,n,{baseUrl:r.baseUrl})}return await nl({projectId:r.project,labels:r.label,testIds:r.testId,testNames:r.name,testConfigNames:r.testConfigNames,suiteNames:r.suites,suiteIds:r.suiteIds,branch:e,rerunFailedByRunId:r.rerunFailedByRunId,testConfigIds:r.testConfigIds,intersections:r.intersections})}function Up(r){let e=Object.keys(r).length,t=Object.keys(r).reduce((s,n)=>s+(r[n].success===!0?1:0),0);return e===t}async function jp(r,e){let t=r.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],s=qb.difference(Gs(r,e),t);if(s.length>0)throw ft("invalid-config-run",{browser:s.join(", "),mode:"runner"}),new k(`browser type <${s}> is not supported in ${r.mode} mode.`);return e}var qb,zb,Jb=T(()=>{"use strict";qb=E(require("lodash")),zb=E(require("path"));B();cs();we();G()});var Fr,Yb,Bp,Fa,eI,Ua,Xb=T(()=>{"use strict";Fr=E(require("lodash"));B();j();le();ae();Oe();ds();su();wu();we();Ct();_t();kg();G();Hb();Gb();Jb();({testRunStatus:Yb,CLI_MODE:Bp}=Ut),Fa=x("test-plan-runner"),eI=1e3*60*5,Ua=class{constructor(e){this.startTime=Date.now();this.workerManager=new Da(e)}async runTestAllPhases(e,t,s,n,o,i,a,c){let l={},p=Bt(),d=async()=>{let y=o.beforeParallel||1,w=!0,S=await this.workerManager.runTests(e,c,i,a,o,n,p,y,w);Object.assign(l,S)},m=async()=>{let y=oo||o.parallel,w=!1;O("right before this.workerManager.runTests");let S=await this.workerManager.runTests(t,c,i,a,o,n,p,y,w);O("right after this.workerManager.runTests"),Object.assign(l,S)},g=async()=>{let y=o.afterParallel||1,w=!1,S=await this.workerManager.runTests(s,c,i,a,o,n,p,y,w);Object.assign(l,S)},f=wr(o);ag({executionId:i,projectId:o.project,sessionType:f}),O("right before runBeforeTests");try{return await d(),O("right before runTestPlanTests"),await m(),O("right after runTestPlanTests"),await g(),l}catch(y){if(Fa.error("error running test plan",{err:y}),y instanceof zt)return c.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw y}finally{await h()}async function h(){var w,S,b,v;if((w=o.lightweightMode)!=null&&w.disablePixelValidation)return;if(o.mode===Bp.SELENIUM){let{EyeSdkBuilder:I}=(await Promise.resolve().then(()=>(ye(),Zt))).getSessionPlayer();await I.closeBatch(i);return}let y;try{if(!((v=(b=(S=o.company)==null?void 0:S.activePlan)==null?void 0:b.premiumFeatures)!=null&&v.applitools)||(y=await wl(o.project),Fr.default.isEmpty(y)||!i))return;let{runKey:I,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:I}})}catch{}}}async initRealDataService(e){let t=new Na;return await t.init(e),t}async listenToTestCreatedInFile(e,t,s,n){let o={};e.joinToTestResultsByRunId(s,t);let i=!0;return await new Promise(c=>{let l=p=>{i=!1,c(p)};e.listenToTestResultsByRunId(s,p=>{let d=p.id;if(!n.getTestResult(d)){let f=o[d],h=Fr.default.merge({},f,p,{resultId:d});if(o[d]=h,!f||f.status!==p.status){let w=(n.getTestResult(h.parentResultId)||{workerId:1}).workerId;[Yb.RUNNING].includes(p.status)&&X.onTestStarted(h,w),[Yb.COMPLETED].includes(p.status)&&(h.duration=h.endTime-h.startTime||0,X.onTestFinished(h,w))}}let m=!Object.values(o).some(f=>["QUEUED","RUNNING"].includes(f.runnerStatus)),g=!Object.values(n.getAllTestResults()).some(f=>["QUEUED","RUNNING"].includes(f.status));if(m&&g)return l(Object.values(o));if(g&&!m)return se(1e4).then(()=>{i&&l(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,s){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,s)}async runTestPlan(e,t,s,n,o,i,a,c){var A,_,R;let l=J(),p=n.project;sc(l),e.forEach(D=>Object.assign(D,{isBeforeTestPlan:!0})),s.forEach(D=>Object.assign(D,{isAfterTestPlan:!0}));let d=[...e,...t,...s],m=new Ii(d,n,i,a),g=Fr.default.chain(d).map(D=>{var C;return((C=D.overrideTestConfig)==null?void 0:C.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=n.files.length>0,y=(A=n.lightweightMode)!=null&&A.onlyTestIdsNoSuite?[]:d.map(D=>D.name),w=(_=n.lightweightMode)!=null&&_.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:s}:m.executionStart(l,p,this.startTime,o,y),S;h&&(S=this.initRealDataServiceAndListenToTestsCreatedInFile(p,l,m)),O("before testListInfoPromise");let b=await w;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||X.onTestPlanStarted(b.beforeTests,b.tests,b.afterTests,o,l,c,f,h),O("before runTestAllPhases");let v=await this.runTestAllPhases(b.beforeTests,b.tests,b.afterTests,a,n,l,o||"All Tests",m),I=await ne(S,eI).catch(async()=>{var C;Fa.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:p,executionId:l});let D=await an(p,"testResult",`runId=${l}&sort=runOrder`);return Fr.default.chain(((C=D==null?void 0:D.data)==null?void 0:C.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return O("before executionEnd"),await m.executionEnd(l),O("after executionEnd"),{results:v,executionId:l,testPlanName:o,configName:f,childTestResults:I}}async runTestPlans(e,t){Fa.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function s(p){return Fr.default.flattenDeep(Object.values(p)).reduce((d,m)=>d.concat(m.beforeTests,m.tests,m.afterTests),[])}let n={},o={},i=e.project,a=await sl(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new k(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new k(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Bp.APPIUM&&await jp(e,s(l)),await ce(c,async p=>{let d=p.testPlanId;n[d]={};let m=Object.assign({},e);m.baseUrl=e.baseUrl||p.startUrl,m.host=e.host,m.port=e.port,m.gridId=e.gridId||p.gridId,e.grid&&delete m.gridId,m.gridData=await $f(e,p);let g=m.overrideExecutionName||p.name;return await ce(l[d],async f=>{let h=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,m,g,d,t),y=e.files.length>0;X.onTestPlanFinished(h.results,p.name,this.startTime,h.executionId,!1,y,h.childTestResults),n[d][h.executionId]=h.results;let w=Object.keys(n[d]).map(I=>({executionId:I,status:Up(n[d][I])})),S=Object.keys(n[d]).map(I=>n[d][I]).reduce((I,A)=>Object.assign(I,A),{}),b=Up(S);Object.assign(o,S);let v=b?w[0].executionId:w.find(I=>!I.status).executionId;return await el(i,d,{success:b,executions:w,executionId:v}),h})})}async runAnonymousTestPlan(e,t){var a;Fa.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),O("before getSuite");let s=await Kb(e,t);if(O("after getSuite"),!((a=s==null?void 0:s.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new k("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new k("No tests to run")}t="branch"in s&&s.branch||t;let n=s;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new k("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 O("Right before validateConfig + runAnonymousTestPlan tests map"),await ce(s.tests,async c=>{if(e.resultId){let d=c[0];d.resultId=e.resultId,c=[d]}e.mode!==Bp.APPIUM&&await jp(e,c),O("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);O("right after runTestPlan");let p=e.files.length>0;return await X.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i,p,l.childTestResults),l})}async run(e){let t=bn(),s=[];qs(e)?s=await this.runTestPlans(e,t):s=await this.runAnonymousTestPlan(e,t);let n=Fr.default.flattenDeep(s);return O("right before onAllTestPlansFinished"),await X.onAllTestPlansFinished(n),O("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var eT={};W(eT,{init:()=>TI,run:()=>yI});async function rI(r){let e=r.project,t=await il(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"),pn(r.authData.uid,"execution-quota-surpassed",{projectId:e}),new Fs}function sI(r,e){var o,i,a,c;if(go(e.activePlan)==="free"){let l=r.parallel||1,p=((i=(o=e.activePlan)==null?void 0:o.premiumFeatures)==null?void 0:i.concurrency)||1;if(l>p)throw new k(`Cannot run with parallel ${r.parallel}. Max parallel value is ${p}`)}let s=r.retentionDays;if(!s)return;let n=(c=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:c.resultRetention;if(s>n)throw new k(`Retention days (${s}) cannot be greater than the company's retention days (${n}). Run aborted`)}async function nI(r){var e;if(!((e=r.lightweightMode)!=null&&e.disableQuotaBlocking))try{await rI(r)}catch(t){if([k,Fs].some(s=>t instanceof s))throw t;tI.error("could not validate cli account",{err:t})}}function oI(r){let e=Bt();return Hm({userId:e.uid,name:e.uid,traits:{projectId:r,company:{id:r,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function iI(r,{disableResults:e=!1,disableRemoteStep:t=!1}){if(N.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Be.connect(r);if(!t){let{remoteStepService:s}=await Promise.resolve().then(()=>(Ta(),lb));await s.init(r)}if(!e){let{testResultService:s}=await Promise.resolve().then(()=>(wa(),db));s.init(r)}}function aI(r,e){let{branch:t,autoDetect:s}=r;if(Gf(e,s),!e&&!s)throw new k(`branch ${t} does not exist, run aborted.`)}async function cI(r){let{project:e}=r,t=bn();Zb.get(r,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(r.sfdcCredential=await Qc({projectId:e,branch:t}))}function lI(r,e){let{onprem:t,id:s,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:d,extensionPath:m,ext:g,playerPath:f}=r;if([Y.SELENIUM].includes(d)&&!f)throw new k("in selenium on prem mode --player-path must be provided");if(d==="extension"&&!m&&!g)throw new k("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),p=go(a);p==="free"&&(r.newBrowserWaitTimeout=r.newBrowserWaitTimeout<Qb?Qb:r.newBrowserWaitTimeout),N.setCompanyId(s),N.setIsPOC(c),N.setIsStartUp(l),N.setPlanType(p),Ot.setPlanType(p),r.company={companyId:s,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:p,isPOC:c,isStartUp:l,activePlan:a}}function uI(r,e){if($r){r.editorUrl=$r;return}r.editorUrl=e.editorUrl}function pI(r,e){r.allGrids=e}function dI(r,e){r.authData=e}function mI(r,e){let{id:t,name:s,type:n,defaults:o}=e;N.setProjectId(t),N.setProjectType(n),r.projectData={projectId:t,type:n,name:s,defaults:o}}async function fI(r){r.gridData=await Wf(r)}async function gI(r){let{project:e}=r,t={projectId:e};r.overrideMappingFile&&(ft("user-override-file",t),r.mockNetworkRules=await Om(r.overrideMappingFile))}async function hI(r,e){O("in runner.js runRunner");let{project:t,remoteRunId:s,useLocalChromeDriver:n,useChromeLauncher:o}=r;s||(r.source=n||o?"cli-local":"cli"),await yf(),O("in runner.js after checkNpmVersion"),await nI(r),O("in runRunner before tunnel.connect"),await oi(r),O("in runRunner after tunnel.connect");let a=await new Ua(e).run(r);return O("before tunnel.disconnect"),await ii(r),await hn.end(t),O("after tunnel.disconnect and gridService.keepAlive.end"),a}function bI(r){var e;Ot.shouldShowFreeGridRunWarning((e=r.gridData)==null?void 0:e.type)&&console.log(`
|
|
414
|
+
Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{ya.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let s={query:{projectId:e},requestTimeout:ob,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=hp.connect(this.url,s),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let s={query:{projectId:e},requestTimeout:ob,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=hp.connect(this.url,s),this.addSocketHandlers()}emitPromise(e,t){let s={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(s[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,ib.default)(()=>ne(n(),DR),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(s).length>0&&ya.error("Bad acknowledge from socket emit",{errorneousEvents:s})}),this.emitPromiseQueue}}});var ab={};W(ab,{remoteStepServiceSocketIO:()=>MR});var yp,MR,cb=T(()=>{"use strict";ba();yp=class extends fr{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,s){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&s(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},MR=new yp});var lb={};W(lb,{remoteStepService:()=>Ps});var bp,$n,Tp,Ps,Ta=T(()=>{"use strict";Bn();ae();be();({REMOTE_STEP_SAVED:bp}=tt),Tp=class{async init(e){N.flags.useNewWSCLI.isEnabled()||($n=(await Promise.resolve().then(()=>(cb(),ab))).remoteStepServiceSocketIO,$n.init(e))}joinToRemoteStep(e){return N.flags.useNewWSCLI.isEnabled()?Be.addFilter(`${e}:remoteStep`,{resultId:e},[bp]):$n.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(N.flags.useNewWSCLI.isEnabled()){Be.listenTo(`${e}:remoteStep`,[bp],s=>s.resultId===e&&s.remoteStep&&s.remoteStep.status==="pending",s=>t(s.remoteStep));return}$n.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return N.flags.useNewWSCLI.isEnabled()?(Be.removeFilter(`${e}:remoteStep`,[bp]),Promise.resolve()):$n.unlistenToRemoteStep(e)}},Ps=new Tp});var wp,Nr,ub=T(()=>{"use strict";ba();wp=class extends fr{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,s,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===s&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,s){return this.emitPromise("testResult:join",{resultId:t,testId:s})}async joinToTestResult(t,s){this.rooms[t]||this.joinRoom(t,s),await this.emitJoinRoom(t,s)}emitLeaveRoom(t,s){return this.emitPromise("testResult:leave",{resultId:t,testId:s})}leaveTestResult(t,s){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,s)):Promise.resolve()}getSocket(){return this._socket}},Nr=new wp});var db={};W(db,{testResultService:()=>Lt});var pb,vp,Lt,wa=T(()=>{"use strict";pb=require("events");Bn();ae();be();ub();vp=class extends pb.EventEmitter{init(e){if(N.flags.useNewWSCLI.isEnabled()){Be.onConnect=()=>this.emit("socket-connected");return}Nr.init(e),Nr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return N.flags.useNewWSCLI.isEnabled()?Be.addFilter(`${e}:testResult`,{resultId:e,testId:t},[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED]):Nr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(N.flags.useNewWSCLI.isEnabled()){Be.removeFilter(`${e}:testResult`,[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED]);return}await Nr.leaveTestResult(e,t)}listenToTestResult(e,t,s){if(N.flags.useNewWSCLI.isEnabled()){Be.listenTo(`${e}:testResult`,[tt.TEST_RESULT_UPDATED,tt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>s(n));return}Nr.listenToTestResult(e,t,s)}getSocket(){if(!N.flags.useNewWSCLI.isEnabled())return Nr.getSocket()}},Lt=new vp});var fb,gb,hb,ve,NR,yb,mb,va,bb=T(()=>{"use strict";fb=E(require("lodash"));B();le();Oe();cs();Ct();we();sb();gb=E(require("p-retry")),hb=require("url");j();Xo();fs();ae();Ta();wa();be();ve=x("test-run-handler"),NR=3,yb=20*1e3,mb=r=>JSON.stringify(r).length<yb,va=class{constructor(e,t,s,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Ht;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=s.testStatus,this._testId=s.testId,this._testName=s.name,this._testResultId=s.resultId,this._code=s.code,this._baseUrl=n.baseUrl||s.baseUrl||s.testConfig.baseUrl,this._nativeApp=s.nativeApp,this._overrideTestConfigId=(c=s.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=s.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?Ys(n.browser,n.saucelabs,n.browserstack):s.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get automationMode(){return this._code?"codeful":"codeless"}get code(){return this._code}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getBrowserStackAppPath(e){var t;return this.isAppFromDevice?null:e?e.browserStackAppId:(t=this._nativeApp)==null?void 0:t.browserStackAppId}getSauceLabsAppPath(e,t){var s,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(s=this._nativeApp)==null?void 0:s.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getHeadspinAppPath(e){var t;return this.isAppFromDevice?null:e?e.headSpinAppId:(t=this._nativeApp)==null?void 0:t.headSpinAppId}getTdcAppPath(e){var t;return this.isAppFromDevice?null:e?e.testimTdcAppId:(t=this._nativeApp)==null?void 0:t.testimTdcAppId}get androidActivityWait(){var n;let e=this._nativeApp&&"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp;if((n=e==null?void 0:e.activity)!=null&&n.includes(e.id))return`${e.id}.*`;let{activity:t}=e;if(!t)return null;let s=t.split(".").pop();return t.replace(s,"*")}get isFFAllowAppFromDeviceEnabled(){return N.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return zs(this._nativeApp)}get isAppForIosVirtualDevice(){return Xr(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?po.FROM_DEVICE:po.FROM_LIBRARY}get nativeAppLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}async getNativeAppData(){let{appId:e,baseUrl:t}=this._options;if(t&&!this._nativeApp&&!e){let s=t||this.baseUrl;if(!s)return null;let[n,o]=s.split(":");return{packageName:n,activity:o}}return this._nativeApp&&!e?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var s,n;let t={tokenV3:await Xt(),refreshToken:Lo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:dd,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&&ft("user-disable-mock"),t.lightweightMode&&((s=this._options.lightweightMode)!=null&&s.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=mb(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),ve.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):ve.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${yb} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await fn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return ve.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this.runMode===Y.EXTENSION&&{code:this.code},...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&mb(e))return;let s=async()=>{try{return await bl(this._options.project,this._testId,this._testResultId,e)}catch(i){return ve.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await s();return await this._testRunStatus.waitForExecutionStartedFinished(),hl(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){O("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},s=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&s.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{O("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};O("before Runtime.evaluate"),await(0,gb.default)(async()=>{let{result:p}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!p.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),O("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return O("after Runtime.evaluate"),l.value}catch(i){throw ve.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let s;try{s=new hb.URL(e)}catch{return}let{username:n,password:o}=s;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let s=!1,n=o=>{if(!s){if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),s=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:p}}=this;try{let d=await kr(a,c,p,l);n(d),s||setTimeout(i,3e3)}catch(d){ve.error("failed to check if done",{err:d}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Lt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:s},branch:n}=this;try{let o=await kr(e,t,s,n),i=["running","completed"];if(i.includes(o.status))return ve.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw ve.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(je.TEST_START_TIMEOUT_MSG)}catch(o){throw ve.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(je.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Lt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(s=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),s(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Lt.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,s(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=fb.debounce(async()=>{try{let i=await kr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(ve.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"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,s(i),!0):!1}catch(i){return ve.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Lt.on("socket-connected",async()=>{try{await Lt.joinToTestResult(this._testResultId,this.testId)}catch(i){ve.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await al(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){ve.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Lt.off("socket-connected",e)}}listenToRemoteStep(e){Ps.listenToRemoteStep(this.testResultId,t=>{rb(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:NR;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,s;return Boolean((s=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:s.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=J(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Ea,Tb=T(()=>{"use strict";bb();Ea=class{constructor(e,t,s,n,o,i){this._waitingTests=s.map(a=>new va(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 FR,UR,Wn,Ep=T(()=>{"use strict";ds();j();FR=x("worker-utils"),UR=async(r,e,t)=>{e&&await ru(r,t)},Wn=async(r,e,t,s)=>{FR.info("releasing player",{hasPlayer:Boolean(s)});try{await(s==null?void 0:s.onDone())}finally{await UR(r,e,t)}}});function VR(r,e,t,s){return{testId:r,reason:s,name:e,resultId:t,success:!1}}var Ra,Sb,Rb,Rp,wt,wb,vb,Eb,Hn,jR,Sp,BR,gr,$R,Sa,WR,HR,GR,nt,Vn=T(()=>{"use strict";Ra=E(require("ms")),Sb=E(require("lodash")),Rb=E(require("moment")),Rp=E(require("p-retry"));B();Oe();ds();we();j();Ep();_t();si();be();Ta();wa();Ze();ae();G();wt=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:wb,TEST_START_TIMEOUT_MSG:vb,TEST_COMPLETE_TIMEOUT_MSG:Eb}=je,{SETUP_TIMEOUT:Hn,NETWORK_ERROR:jR,GRID_ERROR:Sp,BROWSER_CLOSED:BR,SELENIUM_ERROR:gr,UNKNOWN_ERROR:$R,MOBILE_SESSION_ERROR:Sa}=Vs,WR=(0,Ra.default)("1s"),HR=1;GR=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],nt=class{constructor(e,t,s,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=s;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=nt.getWorkerId();this.lambdatestService=new ie;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 HR++}async getGridSlot(e,t){let s=await Hf(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,s),s}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return X.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Us(!0)}async getBrowserOnce(e,t,s,n){throw new Us(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!ze({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice,s=e.isAppForIosVirtualDevice;if(t||s){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:s}};return this.onTestIgnored(this.id,o),o}}setSessionTimeout(){var e;return this.options.mode===Y.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===F.BROWSERSTACK?Math.max((0,Ra.default)("600s"),this.options.getSessionTimeout):Math.max((0,Ra.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let s=(o=this.userData)==null?void 0:o.projectId,n;try{O("before getSlotOnce retries");let i=0,a=await(0,Rp.default)(async()=>{let p=Date.now();try{return await ne(this.getSlotOnce(e),this.options.getBrowserTimeout,je.GET_BROWSER_TIMEOUT_MSG)}catch(d){let m={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw d instanceof Gr?wt.info("could not get grid slot due to concurrency issue",m):wt.error("error getting grid slot",{error:d,...m}),i++,await se(this.options.getBrowserTimeout-(Date.now()-p)),d}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});O("after getSlotOnce retries"),O("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,Rp.default)(async()=>{let p=Date.now(),d=this.initPlayer(e);try{a=await Vf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let m=this.setSessionTimeout();O("before getBrowserOnce");let g=await ne(this.getBrowserOnce(e,t,d,a),m,je.GET_BROWSER_TIMEOUT_MSG);return O("after getBrowserOnce"),X.onGetBrowserSuccess(this.id,s),d||g}catch(m){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===Y.APPIUM?"device":"browser";throw wt.error(`error getting ${f} from grid`,{error:m,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),X.onGetBrowserFailure(this.id,s,++l),d.onDone(),!(m instanceof Rt)&&this.options.mode!==Y.APPIUM&&await se(this.options.getBrowserTimeout-(Date.now()-p)),m}},{retries:c-1,minTimeout:0,factor:1}),O("after getBrowserOnce retries")}catch(i){throw await Wn(this.id,this.releaseSlotOnTestFinished,s,n),i instanceof Rt?i:i instanceof It?new br(i,Sp):new br(i,gr)}return n}async runTest(e,t,s){var p;O("inside runTest");let n=(p=this.userData)==null?void 0:p.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Ks(this.options)&&this.handleMobileTest(e);if(i)return i;O("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,s,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,l)}finally{await Wn(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var m,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var M,$;if(ze(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice)return e();let w=h.sessionId,S=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof br,v=y&&(S(vb)||S(Eb)),_=N.flags.retryOnSeleniumHubError.isEnabled()&&!!f.reason&&h.isSeleniumHubNoMatchSessionError(f.reason)&&!h.ignoreSeleniumHubError,R=v&&h.hasMoreTimeoutRetries(),D=h.hasMoreRetries()&&!b&&!v,C=!f.success&&(D||R||_);try{let V=h.retryKey;f.testRetryKey=V;let Q=h.getAppSource;if(await this.onTestCompleted(this.id,this.testId,f,w,C,Q),this.executionQueue.hasMoreTests()&&!((M=this.options.lightweightMode)!=null&&M.general)&&await se(WR),await this.runTestCleanup(),C){if(R&&await h.startNewTimeoutRetry(),_){wt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:h.testId,retryReason:f.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let Z=($=this.options.projectData)==null?void 0:$.projectId,me=h.testResultId,Gt=h.testId;await Uo(Z,me,Gt,{show:!1}),h.decreaseSeleniumHubRetry(),h.decreaseRetryCount(),await h.startNewRetry()}return D&&!_&&!R&&await h.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:V,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await p(h,C)}return await e()}catch(V){if(V instanceof zt)return;wt.error("failed to process test result",{error:V}),e();return}},s=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
415
|
+
Please make sure the CLI has stable access to the internet. ${yc()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:w}=Ic,S=f instanceof Error?f.message:f;return S.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),S.includes(wb)?{errorType:Hn,reason:"Test couldn't get device"}:S.includes(y)?{errorType:Sa,reason:"app doesn't exist on device"}:S.includes(w)?{errorType:Sa,reason:"app never started, check app permission or app activity"}:S.includes(h)?{errorType:Sa,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Sa,reason:S}},o=(f,h)=>{let y=this.options.mode===Y.APPIUM?"device":"browser";if(!h&&N.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:jR,reason:s()};let w=f instanceof Error?f.message:f;if(w.includes(wb))return{errorType:Hn,reason:`Test couldn't get ${y}`};if(w.includes(vb))return{errorType:Hn,reason:"Test couldn't be started"};if(w.includes(Eb)){if(!this.testRunTimeout)return{errorType:Hn,reason:"Test timeout reached: test is too long"};let S=Rb.default.duration(this.testRunTimeout,"milliseconds"),b=Math.floor(S.asMinutes()),v=S.seconds(),I=b>0?` ${b} min`:"",A=v>0?` ${v} sec`:"";return{errorType:Hn,reason:`Test timeout reached (timeout:${I}${A}): test is too long`}}if(f instanceof br&&f.type){if(f.type===Sp)return{errorType:Sp,reason:`Test couldn't get ${y} from grid - ${f.message}`};if(f.type===gr)return{errorType:gr,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===BR?{errorType:gr,reason:"Session terminated, it is possible that the cli could not connect to the grid to send keep-alive requests for a prolonged period"}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:gr,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(f.message)?{errorType:gr,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(f.message)?{errorType:gr,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(f.message)?{errorType:gr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:$R,reason:w}},i=async(f,h)=>{var v;let y=await hc();!y&&N.flags.warnOnBadNetwork.isEnabled()&&console.warn(s()),wt.warn("error on run",{err:f});let w=(v=this.userData)==null?void 0:v.projectId,{errorType:S,reason:b}=this.options.mode===Y.APPIUM?n(f):o(f,y);Uo(w,this.testResultId,this.testId,{status:Hs.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:h.retryKey,setupStepResult:{status:Hs.COMPLETED,success:!1,reason:b,errorType:S}},h.remoteRunId),await t(VR(this.testId,this.testName,this.testResultId,b),h,f)},a=async(f,h)=>{var v;let y=this.testId,w=this.testResultId,S=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!w||!S||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let I=await kr(y,w,S,b);if(wt.warn("Test failed. Got results via API",{err:f,testResult:Sb.default.omit(I,GR)}),I&&I.status===Hs.COMPLETED)return await t(I,h);throw f}catch(I){return I!==f&&wt.error("Failed to fetch test results from server",{testId:y,resultId:w,projectId:S,branch:b,err:I}),i(f,h)}},c=this.options.disableSockets||((m=this.options.lightweightMode)==null?void 0:m.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),p=async(f,h)=>{try{await Promise.all([!l&&Ps.joinToRemoteStep(this.testResultId),!c&&Lt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Y.APPIUM&&f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),w=await t(y,f);return O("After onRunComplete"),w}catch(y){return a(y,f)}finally{l||Ps.unlistenToRemoteStep(this.testResultId)}},d=this.executionQueue.getNext();return d?(this.testId=d.testId,this.testName=d.testName,this.testResultId=d.testResultId,this.overrideTestConfigId=d.overrideTestConfigId,this.testRunConfig=d.runConfig,this.branch=d.branch,p(d)):this.onQueueCompleted()}}});var Ib={};W(Ib,{WorkerSelenium:()=>Ip});function zR(r){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))r.playbackManager.on(t,()=>O(`Got event ${t}`))}var Ia,qR,Ip,xb=T(()=>{"use strict";B();Oe();Vn();j();_t();Xo();ae();Wu();G();ma();ye();Ia=x("worker-selenium"),qR=1e9,Ip=class extends nt{initPlayer(t){return new Fn(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){O("in WorkerSelenium getBrowserOnce"),X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ws(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,s,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),O("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),O("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,qR),await this.windowUtils.validatePageIsAvailable(),O("in WorkerSelenium after navigate")}catch(l){let p=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof Rt||p||d?new Rt(`Page '${c}' is not available`):(Ia.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,s){var d;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=s,c=n||"runner";X.onWaitToTestComplete(this.id,this.isCodeMode),zR(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await fn(this.options))[this.testId]);let p=async()=>{if(t.automationMode==="codeful"){a.callOrderScheduler?a.callOrderScheduler.schedule(()=>t.waitForExecutionStartedFinished(),{key:`test-result:${this.userData.projectId}:${this.testResultId}`}):await t.waitForExecutionStartedFinished(),O("right before playTestByCode");let g=new Promise((f,h)=>{a.playTestByCode(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,f,!1,this.overrideTestConfigId,this.branch,t.code,t.testName).catch(h)});return ne(g.then(f=>(O("right after playTestByCode"),f)),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG).catch(f=>{var h;throw f instanceof te&&((h=a.stopPlayingOnTestTimeout)==null||h.call(a)),f}).then(f=>(f.resultId=this.testResultId,f))}let m=!1;return ne(new Promise((g,f)=>{a.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,g,!1,this.overrideTestConfigId,this.branch,m,t.remoteRunId,void 0,void 0,l).catch(f)}),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG).catch(g=>{var f;throw g instanceof te&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),g}).then(async g=>{await o.drain(),g.stepsResults=null,g.resultId=this.testResultId,i.isAlive()||(Ia.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),g.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(Ia.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),g.keepAliveIssue=f);let y={...g,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${y.success?"passed":"failed"}`).catch(()=>{}),y})};i.start(),O("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,s),O("right after super.runTestOnce in workerSelenium");let m=await p();return O("right after runSeleniumTest"),m}catch(m){throw Ia.error("failed to run test once",{err:m}),m}}}});var xa,kb=T(()=>{"use strict";xa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var xp,ka,Pb=T(()=>{"use strict";j();xp=x("mobile-frame-locator-mock"),ka=class{foundFrameCallback(){return xp.info("foundFrameCallback-mock invoked"),{}}locate(){return xp.info("locate-mock invoked"),{}}async findFrame(){return xp.info("findFrame-mock invoked"),{}}}});var KR,JR,Cs,kp=T(()=>{"use strict";KR=E(require("webdriverio"));kb();qu();j();zu();Ku();ye();Zu();Pb();ep();JR=x("appium-test-player"),Cs=class{constructor(e,t,s,n,o=KR,i=void 0,a=void 0){this.id=e;this.driver=o;let{SessionPlayer:c,commonConstants:l,StepActionFactory:p,MobileLocateElementPlayer:d}=ee(),m=new Es(this.driver);this.stepActionFactory=new p(m),da(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new ks(Bi()),this.sessionPlayer=new c(e,{tabService:new xa,cookieUtils:void 0,FrameLocator:ka,portSelector:ji,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,PlaybackManagerFactory:n}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(s)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=a,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,s,n){}async onDone(){var e,t,s;try{await((s=(t=(e=this.driver)==null?void 0:e.activeSessions)==null?void 0:t.get(this.id))==null?void 0:s.deleteSession())}catch(n){JR.error("error while deleting appium session",{error:n})}finally{let{commonConstants:n}=ee();this.sessionPlayer.playbackManager.off(n.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e,t,s;return(s=(t=(e=this.driver)==null?void 0:e.activeSessions)==null?void 0:t.get(this.id))==null?void 0:s.sessionId}}});var Ab={};W(Ab,{WorkerLocalTma:()=>Ap});var Cb,Pa,Pp,Cp,Ap,Ob=T(()=>{"use strict";Cb=E(require("jsdom"));Ze();xn();Vn();B();j();_t();kp();ye();ki();Pa=x("worker-appium"),Pp=class extends Error{},Cp=class extends Error{},Ap=class extends nt{initPlayer(t){return new Cs(this.id,t.runParams,this.options.shouldMonitorPerformance,t.automationMode,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,s,n,o){var d;if(X.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{driver:i}=n,a=this.options.projectData.type,c=await t.getNativeAppData(),l=a==="android"?t.androidActivityWait:null,p=t.nativeAppLink;if(this.options.appId){let{project:m,appId:g,authData:{token:f=""}={}}=this.options;p=await ku({appId:g,projectId:m,token:f})}p&&await this.installApp(this.options.localTmaUrl,this.options.deviceUdid,p);try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(d=this.options.projectData)==null?void 0:d.name}-${this.options.project}`},g=Kg({projectType:a,nativeApp:c,appPath:p,androidActivityWait:l,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),f={capabilities:{udid:this.options.deviceUdid,...g}},h=await this.requestNewAppiumSessionFromTma(this.options.localTmaUrl,f);this.sessionData=h;let y=await i.attach({sessionId:h.sessionId,capabilities:g});i.activeSessions||=new Map,i.activeSessions.set(this.id,y),await xi(t,y,this.options),Pa.info(`init new appium session testName: ${this.testName}`,{sessionId:y.sessionId,testResultId:this.testResultId,nativeApp:c})}catch(m){throw Pa.error("failed to start application",{err:m}),m}}async requestNewAppiumSessionFromTma(t,s){try{return{...await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:s,timeout:6e4}),env:"local"}}catch(n){throw this.handleDeviceNotFoundError(n),n}}async installApp(t,s,n){var o,i;try{let a=await Nt(n);await Ws(`${t}/api/devices/${s}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Cp(l,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let s=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof s=="string"&&(s!=null&&s.startsWith("Ensure that the requested device")))throw new Pp(`Device not found: Ensure that the requested device ${this.options.deviceUdid} is connected`)}async runTestOnce(t,s){let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=s,c=n||"runner";X.onWaitToTestComplete(this.id,this.isCodeMode),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l=new Cb.JSDOM("").window.DOMParser;a.playbackManager.appiumSessionData=this.sessionData,a.playbackManager.appiumApi=new o(this.sessionData.serverAddress,this.sessionData.sessionId,l),i.initialize({serverUrl:this.options.localRCASaver});let p=async()=>{try{let m=await new Promise((f,h)=>a.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,f,!1,this.overrideTestConfigId,this.branch,!1,t.remoteRunId,void 0,void 0,void 0).catch(h));return await i.drain(),m.stepsResults=null,m.resultId=this.testResultId,{...m,...t.seleniumPerfStats.getStats()}}catch(d){throw Pa.error("error while running appium tests",{err:d}),d}};try{return await super.runTestOnce(t,s),await p()}catch(d){throw Pa.error("failed to run test once",{err:d}),d}}}});var Lb={};W(Lb,{WorkerAppium:()=>Op});var _b,Ca,Op,Db=T(()=>{"use strict";_b=E(require("jsdom"));xn();Vn();j();_t();kp();ye();ki();ae();Ca=x("worker-appium"),Op=class extends nt{initPlayer(e){return new Cs(this.id,e.runParams,this.options.shouldMonitorPerformance,e.automationMode,void 0,e.retryCount,e.previousTestResultId)}async getBrowserOnce(e,t,s,n){var m;X.onGetSession(this.id,this.testName,e.runMode);let{driver:o}=s,i=this.options.projectData.type,a=await e.getNativeAppData(),c=i==="android"?e.androidActivityWait:null,{appPath:l,isTdcAppIdExists:p,isHSAppIdExists:d}=await Dg({testRunHandler:e,options:this.options});try{let g={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(m=this.options.projectData)==null?void 0:m.name}-${this.options.project}`},f={projectType:i,nativeApp:a,appPath:l,androidActivityWait:c,sessionTags:g,gridInfo:n,options:this.options,testRunConfig:this.testRunConfig,isHSAppIdExists:d,isTdcAppIdExists:p},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Og(n,this.options.deviceUdid),h=await Yg(f)):h=Jg(f);let y=await o.remote(h);o.activeSessions||=new Map,o.activeSessions.set(this.id,y),await xi(e,y,this.options),Ca.info(`init new appium session testName: ${this.testName}`,{sessionId:y.sessionId,testResultId:this.testResultId,nativeApp:a})}catch(g){throw Ca.error("failed to start application",{err:g}),g}}getServerAddressFromGrid(){let{host:e,port:t,accessToken:s,type:n}=this.options.gridData;return n===F.TESTIM_HEADSPIN||n===F.TESTIM_TDC?`https://${e}:${t}/v0/${s}/wd/hub`:`https://${e}:${t}/wd/hub`}getDirectAddressConnection(e){let{directConnectProtocol:t,directConnectHost:s,directConnectPort:n,directConnectPath:o}=e;if(t&&s&&n&&o)return`${t}://${s}:${n}${o}`}async runTestOnce(e,t){var f;let{manifestVersion:s,AppiumApi:n,localAssetService:o}=ee(),{sessionPlayer:i}=t,a=t.driver,c=s||"runner",l=a.activeSessions.get(this.id);X.onWaitToTestComplete(this.id,this.isCodeMode),i.playbackManager.executionId=e.executionId,i.playbackManager.executionName=e.executionName;let p;if(this.options.skipLoadBalancer){let{protocol:h,hostname:y,port:w,path:S}=await xu(this.options.gridData,this.options.deviceUdid);p=`${h}://${y}:${w}${S}`}else p=this.getDirectAddressConnection(l.capabilities)||this.getServerAddressFromGrid();let d=new _b.JSDOM("").window.DOMParser,m=l.capabilities;i.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:l.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(f=this.options.company)==null?void 0:f.companyId},i.playbackManager.appiumApi=new n(p,l.sessionId,d),o.initialize({serverUrl:this.options.localRCASaver});let g=async()=>{try{let y=await new Promise((S,b)=>i.playByTestId(this.testId,this.executionId,this.testResultId,this.baseUrl,this.userData,c,S,!1,this.overrideTestConfigId,this.branch,!1,e.remoteRunId,void 0,void 0,void 0).catch(b));return await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...e.seleniumPerfStats.getStats()}}catch(h){throw Ca.error("error while running appium tests",{err:h}),h}};try{return await super.runTestOnce(e,t),await g()}catch(h){throw Ca.error("failed to run test once",{err:h}),h}}}});var Aa,Mb=T(()=>{"use strict";B();An();G();Aa=class{constructor(e){this.id=e;this.driver=new Or}async onDone(){try{await ne(this.driver.end(),12e4)}catch(t){t instanceof te&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Nb,Oa,Fb=T(()=>{"use strict";Nb=E(require("ws"));B();Oa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Nb.default(this._cdpUrl,{timeout:e}),s=ut(o=>{t.once("open",o)}),n=ut(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([s,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),s=this._cdpCallbacks.get(t.id);s&&(this._cdpCallbacks.delete(t.id),t.error?s.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?s.reject(new Error(t.result.exceptionDetails.exception.description)):s.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,s){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return s&&Object.assign(a,{sessionId:s}),n.send(JSON.stringify(a)),i}}});var La,_p,_a,Ub=T(()=>{"use strict";B();La=E(require("chrome-launcher"));xn();Fb();un();_p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}async init(e,t,s,n,o,i,a,c,l,p){var f,h,y,w;let d=Pi(e,t,s,n,o,i,a),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((w=(y=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:w.args)??[],...La.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await La.launch({chromeFlags:m,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await Sr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),as(()=>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}},_a=class{constructor(e){this.id=e;this.sessionId=J();this.driver=new _p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Bb={};W(Bb,{WorkerExtension:()=>Gn});function YR(r){return r instanceof Error&&"type"in r&&typeof r.type=="string"}function jb(r){return YR(r)?r:new Error(r)}var ot,Gn,Lp=T(()=>{"use strict";Oe();G();Vn();B();j();_t();ae();Mb();Ub();ot=x("worker-ext"),Gn=class extends nt{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new Aa(this.id)}async _getBrowserOnce(e,t,s,n){var i;let{driver:o}=s;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw ot.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,s,n){return X.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,s,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,s){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:s}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:s,executionId:n,testId:o}=this;O("WorkerExtension runTestOnce");let i=async p=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ne(e.runTestUsingCDP(p.cdpTestRunner),d,je.TEST_START_TIMEOUT_MSG)}catch(m){if(!(m instanceof te))throw m;return ot.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:s}),await e.checkViaRestAPIIfTestStarted()}},a=async(p,d,m)=>{try{let g=await p.url(d);return m.driverUrlFinished=!0,g}catch(g){throw ot.error("error from driver.url",{err:g,testResultId:s,executionId:n,testId:o,url:d,urlLength:d.length}),g}},c=async p=>{let d=await e.onStarted(this.options.testStartTimeout);return p.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(O("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){X.onWaitToTestStart(this.id),X.onWaitToTestComplete(this.id,this.isCodeMode);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw ot.warn("failed to run test via CDP",{err:f}),f}}let{driver:d}=t,m={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();X.onWaitToTestStart(this.id);try{await ne(Promise.all([a(t.driver,f,m),c(m)]),this.options.testStartTimeout,je.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof te))throw w;ot.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:s,executionId:n,testId:o,...m}),await e.checkViaRestAPIIfTestStarted()}X.onWaitToTestComplete(this.id,this.isCodeMode);let h=new AbortController,y=w=>{e.onCompletedCleanup(),ot.warn("on browser closed error detected",{err:w,testResultId:s,executionId:n,testId:o}),d.unregisterToClosedBrowser(y),w.type=Vs.BROWSER_CLOSED,h.abort(w)};d.registerToClosedBrowser(y);try{let w=ne(e.onCompleted(),this.testRunTimeout,je.TEST_COMPLETE_TIMEOUT_MSG),S=await lc(w,h.signal);d.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(I){ot.error("Could not update the grid about the test status",{err:I})}d.isAlive()||(ot.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=d.maxKeepAliveGap();return b>=3e4&&(ot.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(w){throw ot.warn("timeout wait until test completed",{err:w,testResultId:s,executionId:n,testId:o}),jb(w)}finally{d.unregisterToClosedBrowser(y)}}catch(f){throw ot.warn("failed to start url",{err:f}),jb(f)}};t.driver.start();try{return await super.runTestOnce(e,t),O("WorkerExtension super.runTestOnce"),await l()}catch(p){throw ot.error("failed to run test",{err:p,testId:e.testId,resultId:e.testResultId}),p}}}});var $b={};W($b,{WorkerExtensionSingleBrowser:()=>Dp});var XR,QR,Dp,Wb=T(()=>{"use strict";Oe();B();j();Ep();_t();Lp();XR=x("base-worker"),QR=500,Dp=class extends Gn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Wn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,s,n,o){return X.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,s,n,o)}async getTestPlayer(t,s){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(XR.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,s)),this.testPlayer}async runTest(t,s,n){let o=this.handleQuarantine(t);if(o)return o;O("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,s);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await se(QR)}}});function ZR(r,e){e===0?r():setTimeout(r,e*ud)}var Mp,Da,Hb=T(()=>{"use strict";An();B();le();Oe();wu();Ct();Uu();G();j();ae();Tb();Mp=x("parallel-worker-manager"),Da=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(xb(),ge(Ib)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(Ob(),ge(Ab)).WorkerLocalTma:(Db(),ge(Lb)).WorkerAppium;default:return Di.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Wb(),ge($b)).WorkerExtensionSingleBrowser:(Lp(),ge(Bb)).WorkerExtension}}createWorkers(e,t,...s){let n=s[0],o=this.getWorkerType(n),i=()=>{try{return O("before new Worker",n.mode),new o(t,...s)}finally{O("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,s,n,o,i,a,c,l){if(e&&e.length===0)return;let p=!1,d=0,m=g=>new Promise(f=>{var vt,jr,P,L,U,q,it;let h=o.project,y=new Ea(s,n,e,o,i,t),w={},S=e.length,b=((vt=o.company)==null?void 0:vt.ucid)||"",v=(jr=o.company)==null?void 0:jr.companyId,I=(P=o.company)==null?void 0:P.name,A=o.source||"cli",_=o.user,R=(L=o.company)==null?void 0:L.planType,D=(U=o.company)==null?void 0:U.isStartUp,C=(q=o.projectData)==null?void 0:q.name,M=(it=o.projectData)==null?void 0:it.type,$=o.lightweightMode,V=wr(o),Q=(Et,at,Te,Ha,qn,Va)=>(d++,og({executionId:s,projectId:h,testId:at,resultId:Te,ucid:b,companyId:v,companyName:I,projectName:C,companyPlan:R,sessionType:V,source:A,user:_,lightweightMode:$,isStartUp:D,projectType:M,appSource:Va}),t.testStartAndReport(Et,s,Te,Ha,qn)),Z=async(Et,at,Te,Ha,qn,Va)=>{var zp,Kp,Jp;d--;let Qe={...($==null?void 0:$.onlyTestIdsNoSuite)&&{show:!0},...Te.seleniumStats&&{seleniumStats:Te.seleniumStats},...Te.gridIssues&&{gridIssues:Te.gridIssues},...Te.keepAliveIssue&&{keepAliveIssue:Te.keepAliveIssue},...o.host&&{gridHost:o.host}};if(Te.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(Te.seleniumPerfMarks),delete Te.seleniumPerfMarks),o.grid||o.gridId?(Qe.gridName=o.grid||((zp=o.gridData)==null?void 0:zp.name),Qe.gridType=(Kp=o.gridData)==null?void 0:Kp.type,Qe.gridProvider=(Jp=o.gridData)==null?void 0:Jp.provider):o.localTmaUrl?(Qe.gridName="local-tma-from-options",Qe.gridType="local-tma"):o.useLocalChromeDriver?(Qe.gridName="local-chrome-driver-from-options",Qe.gridType="local-chrome"):o.useChromeLauncher?(Qe.gridName="chrome-launcher-from-options",Qe.gridType="local-chrome"):o.browserstack?Qe.gridName="browserstack-from-options":o.saucelabs&&(Qe.gridName="saucelabs-from-options"),await t.testEndAndReport(Et,Te,s,Ha,qn,Qe).catch(qT=>Mp.error("testEndAndReport threw an error",{err:qT})),qn)return;w[Te.resultId]=Te,ig({executionId:s,projectId:h,testId:at,resultId:Te.resultId,result:Te,ucid:b,companyId:v,companyName:I,projectName:C,companyPlan:R,sessionType:V,source:A,user:_,lightweightMode:$,logger:Mp,isStartUp:D,projectType:M,appSource:Va}),l&&!Te.success&&(y.stop(),p=!0),(Object.keys(w).length===S||p&&d===0)&&f(w)},me=(Et,at)=>{w[at.resultId]=at,t.onTestIgnored(Et,at.resultId),d--,(Object.keys(w).length===S||p&&d===0)&&f(w)},Gt=(Et,at)=>t.onGridSlot(Et,at);o.userData={loginData:Object.assign({},Bt(),{refreshToken:Lo(),authData:Bt(),token:g}),projectId:o.project,company:o.company,servicesUrl:fe},O("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,s,Q,Z,Gt,me).forEach((Et,at)=>{O("before schedule worker.run after createWorkers"),ZR(()=>{O("right before worker.run"),Et.run()},at)})});try{let g=await Xt(),f=await m(g);if(p)throw new zt;return f}catch(g){throw Mp.error("failed running parallel workers",{executionId:s,err:g}),g}}}});var Ma,Vb=T(()=>{"use strict";ba();Ma=class extends fr{init(e){return super.initNewSocket(e,"real-data")}emitJoinRoom(e,t){this._socket.emit("testResult:listen",{query:`projectId=${t}&runId=${e}`})}joinToTestResultsByRunId(e,t){this.joinRoom(e,t),this.emitJoinRoom(e,t)}stopListenToTestResultsByRunId(e){this.leaveRoom(e),this._socket.emit("testResult:listen:stop",{})}listenToTestResultsByRunId(e){function t(s){e(s.data)}this._socket.on("testResult:changes",t.bind(this))}}});var Np,Fp,Na,Gb=T(()=>{"use strict";Bn();ae();be();Vb();({TEST_RESULT_CREATED:Np,TEST_RESULT_UPDATED:Fp}=tt),Na=class{constructor(){N.flags.useNewWSCLI.isEnabled()||(this.realDataServiceSocketIO=new Ma)}init(e){return N.flags.useNewWSCLI.isEnabled()?Promise.resolve():this.realDataServiceSocketIO.init(e)}joinToTestResultsByRunId(e,t){if(N.flags.useNewWSCLI.isEnabled())return Be.addFilter(e,{runId:e},[Fp,Np],!0);this.realDataServiceSocketIO.joinToTestResultsByRunId(e,t)}stopListenToTestResultsByRunId(e){if(N.flags.useNewWSCLI.isEnabled()){Be.removeFilter(e,[Fp,Np]);return}this.realDataServiceSocketIO.stopListenToTestResultsByRunId(e)}listenToTestResultsByRunId(e,t){if(N.flags.useNewWSCLI.isEnabled()){Be.listenTo(e,[Fp,Np],s=>s.runId===e,s=>t(s));return}this.realDataServiceSocketIO.listenToTestResultsByRunId(t)}}});async function Kb(r,e){var t;if((t=r.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&r.testId)return{tests:[r.testId.map(n=>({testId:n,testConfig:{},resultId:J()}))]};if(r.files.length>0){let{buildCodeTests:s}=await Promise.resolve().then(()=>(sp(),jy)),n={};if(r.webpackConfig){let o=zb.join(process.cwd(),r.webpackConfig);n=require(o)}return s(r.files,n,{baseUrl:r.baseUrl})}return await nl({projectId:r.project,labels:r.label,testIds:r.testId,testNames:r.name,testConfigNames:r.testConfigNames,suiteNames:r.suites,suiteIds:r.suiteIds,branch:e,rerunFailedByRunId:r.rerunFailedByRunId,testConfigIds:r.testConfigIds,intersections:r.intersections})}function Up(r){let e=Object.keys(r).length,t=Object.keys(r).reduce((s,n)=>s+(r[n].success===!0?1:0),0);return e===t}async function jp(r,e){let t=r.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],s=qb.difference(Gs(r,e),t);if(s.length>0)throw ft("invalid-config-run",{browser:s.join(", "),mode:"runner"}),new k(`browser type <${s}> is not supported in ${r.mode} mode.`);return e}var qb,zb,Jb=T(()=>{"use strict";qb=E(require("lodash")),zb=E(require("path"));B();cs();we();G()});var Fr,Yb,Bp,Fa,eI,Ua,Xb=T(()=>{"use strict";Fr=E(require("lodash"));B();j();le();ae();Oe();ds();su();wu();we();Ct();_t();kg();G();Hb();Gb();Jb();({testRunStatus:Yb,CLI_MODE:Bp}=Ut),Fa=x("test-plan-runner"),eI=1e3*60*5,Ua=class{constructor(e){this.startTime=Date.now();this.workerManager=new Da(e)}async runTestAllPhases(e,t,s,n,o,i,a,c){let l={},p=Bt(),d=async()=>{let y=o.beforeParallel||1,w=!0,S=await this.workerManager.runTests(e,c,i,a,o,n,p,y,w);Object.assign(l,S)},m=async()=>{let y=oo||o.parallel,w=!1;O("right before this.workerManager.runTests");let S=await this.workerManager.runTests(t,c,i,a,o,n,p,y,w);O("right after this.workerManager.runTests"),Object.assign(l,S)},g=async()=>{let y=o.afterParallel||1,w=!1,S=await this.workerManager.runTests(s,c,i,a,o,n,p,y,w);Object.assign(l,S)},f=wr(o);ag({executionId:i,projectId:o.project,sessionType:f}),O("right before runBeforeTests");try{return await d(),O("right before runTestPlanTests"),await m(),O("right after runTestPlanTests"),await g(),l}catch(y){if(Fa.error("error running test plan",{err:y}),y instanceof zt)return c.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw y}finally{await h()}async function h(){var w,S,b,v;if((w=o.lightweightMode)!=null&&w.disablePixelValidation)return;if(o.mode===Bp.SELENIUM){let{EyeSdkBuilder:I}=(await Promise.resolve().then(()=>(ye(),Zt))).getSessionPlayer();await I.closeBatch(i);return}let y;try{if(!((v=(b=(S=o.company)==null?void 0:S.activePlan)==null?void 0:b.premiumFeatures)!=null&&v.applitools)||(y=await wl(o.project),Fr.default.isEmpty(y)||!i))return;let{runKey:I,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:I}})}catch{}}}async initRealDataService(e){let t=new Na;return await t.init(e),t}async listenToTestCreatedInFile(e,t,s,n){let o={};e.joinToTestResultsByRunId(s,t);let i=!0;return await new Promise(c=>{let l=p=>{i=!1,c(p)};e.listenToTestResultsByRunId(s,p=>{let d=p.id;if(!n.getTestResult(d)){let f=o[d],h=Fr.default.merge({},f,p,{resultId:d});if(o[d]=h,!f||f.status!==p.status){let w=(n.getTestResult(h.parentResultId)||{workerId:1}).workerId;[Yb.RUNNING].includes(p.status)&&X.onTestStarted(h,w),[Yb.COMPLETED].includes(p.status)&&(h.duration=h.endTime-h.startTime||0,X.onTestFinished(h,w))}}let m=!Object.values(o).some(f=>["QUEUED","RUNNING"].includes(f.runnerStatus)),g=!Object.values(n.getAllTestResults()).some(f=>["QUEUED","RUNNING"].includes(f.status));if(m&&g)return l(Object.values(o));if(g&&!m)return se(1e4).then(()=>{i&&l(o)})})})}async initRealDataServiceAndListenToTestsCreatedInFile(e,t,s){let n=await this.initRealDataService(e);return this.listenToTestCreatedInFile(n,e,t,s)}async runTestPlan(e,t,s,n,o,i,a,c){var A,_,R;let l=J(),p=n.project;sc(l),e.forEach(D=>Object.assign(D,{isBeforeTestPlan:!0})),s.forEach(D=>Object.assign(D,{isAfterTestPlan:!0}));let d=[...e,...t,...s],m=new Ii(d,n,i,a),g=Fr.default.chain(d).map(D=>{var C;return((C=D.overrideTestConfig)==null?void 0:C.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=n.files.length>0,y=(A=n.lightweightMode)!=null&&A.onlyTestIdsNoSuite?[]:d.map(D=>D.name),w=(_=n.lightweightMode)!=null&&_.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:s}:m.executionStart(l,p,this.startTime,o,y),S;h&&(S=this.initRealDataServiceAndListenToTestsCreatedInFile(p,l,m)),O("before testListInfoPromise");let b=await w;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||X.onTestPlanStarted(b.beforeTests,b.tests,b.afterTests,o,l,c,f,h),O("before runTestAllPhases");let v=await this.runTestAllPhases(b.beforeTests,b.tests,b.afterTests,a,n,l,o||"All Tests",m),I=await ne(S,eI).catch(async()=>{var C;Fa.warn("timed out waiting for child results on websocket. using REST fallback",{projectId:p,executionId:l});let D=await an(p,"testResult",`runId=${l}&sort=runOrder`);return Fr.default.chain(((C=D==null?void 0:D.data)==null?void 0:C.docs)||[]).groupBy("parentResultId").omit("undefined").values().flatten().value()});return O("before executionEnd"),await m.executionEnd(l),O("after executionEnd"),{results:v,executionId:l,testPlanName:o,configName:f,childTestResults:I}}async runTestPlans(e,t){Fa.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function s(p){return Fr.default.flattenDeep(Object.values(p)).reduce((d,m)=>d.concat(m.beforeTests,m.tests,m.afterTests),[])}let n={},o={},i=e.project,a=await sl(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new k(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new k(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Bp.APPIUM&&await jp(e,s(l)),await ce(c,async p=>{let d=p.testPlanId;n[d]={};let m=Object.assign({},e);m.baseUrl=e.baseUrl||p.startUrl,m.host=e.host,m.port=e.port,m.gridId=e.gridId||p.gridId,e.grid&&delete m.gridId,m.gridData=await $f(e,p);let g=m.overrideExecutionName||p.name;return await ce(l[d],async f=>{let h=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,m,g,d,t),y=e.files.length>0;X.onTestPlanFinished(h.results,p.name,this.startTime,h.executionId,!1,y,h.childTestResults),n[d][h.executionId]=h.results;let w=Object.keys(n[d]).map(I=>({executionId:I,status:Up(n[d][I])})),S=Object.keys(n[d]).map(I=>n[d][I]).reduce((I,A)=>Object.assign(I,A),{}),b=Up(S);Object.assign(o,S);let v=b?w[0].executionId:w.find(I=>!I.status).executionId;return await el(i,d,{success:b,executions:w,executionId:v}),h})})}async runAnonymousTestPlan(e,t){var a;Fa.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),O("before getSuite");let s=await Kb(e,t);if(O("after getSuite"),!((a=s==null?void 0:s.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new k("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new k("No tests to run")}t="branch"in s&&s.branch||t;let n=s;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new k("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 O("Right before validateConfig + runAnonymousTestPlan tests map"),await ce(s.tests,async c=>{if(e.resultId){let d=c[0];d.resultId=e.resultId,c=[d]}e.mode!==Bp.APPIUM&&await jp(e,c),O("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);O("right after runTestPlan");let p=e.files.length>0;return await X.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i,p,l.childTestResults),l})}async run(e){let t=bn(),s=[];qs(e)?s=await this.runTestPlans(e,t):s=await this.runAnonymousTestPlan(e,t);let n=Fr.default.flattenDeep(s);return O("right before onAllTestPlansFinished"),await X.onAllTestPlansFinished(n),O("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var eT={};W(eT,{init:()=>TI,run:()=>yI});async function rI(r){let e=r.project,t=await il(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"),pn(r.authData.uid,"execution-quota-surpassed",{projectId:e}),new Fs}function sI(r,e){var o,i,a,c;if(go(e.activePlan)==="free"){let l=r.parallel||1,p=((i=(o=e.activePlan)==null?void 0:o.premiumFeatures)==null?void 0:i.concurrency)||1;if(l>p)throw new k(`Cannot run with parallel ${r.parallel}. Max parallel value is ${p}`)}let s=r.retentionDays;if(!s)return;let n=(c=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:c.resultRetention;if(s>n)throw new k(`Retention days (${s}) cannot be greater than the company's retention days (${n}). Run aborted`)}async function nI(r){var e;if(!((e=r.lightweightMode)!=null&&e.disableQuotaBlocking))try{await rI(r)}catch(t){if([k,Fs].some(s=>t instanceof s))throw t;tI.error("could not validate cli account",{err:t})}}function oI(r){let e=Bt();return Hm({userId:e.uid,name:e.uid,traits:{projectId:r,company:{id:r,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function iI(r,{disableResults:e=!1,disableRemoteStep:t=!1}){if(N.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Be.connect(r);if(!t){let{remoteStepService:s}=await Promise.resolve().then(()=>(Ta(),lb));await s.init(r)}if(!e){let{testResultService:s}=await Promise.resolve().then(()=>(wa(),db));s.init(r)}}function aI(r,e){let{branch:t,autoDetect:s}=r;if(Gf(e,s),!e&&!s)throw new k(`branch ${t} does not exist, run aborted.`)}async function cI(r){let{project:e}=r,t=bn();Zb.get(r,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(r.sfdcCredential=await Qc({projectId:e,branch:t}))}function lI(r,e){let{onprem:t,id:s,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:d,extensionPath:m,ext:g,playerPath:f}=r;if([Y.SELENIUM].includes(d)&&!f)throw new k("in selenium on prem mode --player-path must be provided");if(d==="extension"&&!m&&!g)throw new k("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),p=go(a);p==="free"&&(r.newBrowserWaitTimeout=r.newBrowserWaitTimeout<Qb?Qb:r.newBrowserWaitTimeout),N.setCompanyId(s),N.setIsPOC(c),N.setIsStartUp(l),N.setPlanType(p),Ot.setPlanType(p),r.company={companyId:s,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:p,isPOC:c,isStartUp:l,activePlan:a}}function uI(r,e){if($r){r.editorUrl=$r;return}r.editorUrl=e.editorUrl}function pI(r,e){r.allGrids=e}function dI(r,e){r.authData=e}function mI(r,e){let{id:t,name:s,type:n,defaults:o}=e;N.setProjectId(t),N.setProjectType(n),r.projectData={projectId:t,type:n,name:s,defaults:o}}async function fI(r){r.gridData=await Wf(r)}async function gI(r){let{project:e}=r,t={projectId:e};r.overrideMappingFile&&(ft("user-override-file",t),r.mockNetworkRules=await Om(r.overrideMappingFile))}async function hI(r,e){O("in runner.js runRunner");let{project:t,remoteRunId:s,useLocalChromeDriver:n,useChromeLauncher:o}=r;s||(r.source=n||o?"cli-local":"cli"),await yf(),O("in runner.js after checkNpmVersion"),await nI(r),O("in runRunner before tunnel.connect"),await oi(r),O("in runRunner after tunnel.connect");let a=await new Ua(e).run(r);return O("before tunnel.disconnect"),await ii(r),await hn.end(t),O("after tunnel.disconnect and gridService.keepAlive.end"),a}function bI(r){var e;Ot.shouldShowFreeGridRunWarning((e=r.gridData)==null?void 0:e.type)&&console.log(`
|
|
416
416
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
417
417
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
418
418
|
`)}async function TI(r){var h,y,w;O("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:s,mode:n,disableSockets:o}=r,i=N.fetch(),a=iI(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(s||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{}),a.catch(()=>{});let{authData:c,editorConfig:l,companyByProjectId:p,projectById:d,branchName:m,allGrids:g}=await cn(r);sI(r,p),await Promise.all([i,a]),O("after featureFlagsReady and socketConnected"),uI(r,l),lI(r,p),mI(r,d),aI(r,m),pI(r,g),dI(r,c),await cI(r),(h=r.lightweightMode)!=null&&h.disableLabs||await Di.loadLabFeatures(d.id,p.activePlan),((y=r.lightweightMode)==null?void 0:y.type)==="turboMode"&&(N.flags.highSpeedMode.getValue()==="disabled"||r.company.planType==="free")&&delete r.lightweightMode,((w=r.lightweightMode)==null?void 0:w.type)==="turboMode"&&console.log(`
|