@testim/testim-cli 4.3.3 → 4.4.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 +1 -1
- package/cli.js.map +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -27,7 +27,7 @@ ${((x=n.warnings)==null?void 0:x.join(`
|
|
|
27
27
|
\r`)))}onTestPlanFinished(e,t,s,n,o,i){let a=li(e,i),c=ui(e,i),u=di(e,i),p=c.length,d=u.length,m=a.length,g="",f="";if(Pt.isTestStatusEnabled){let T=ci(e);g=` FAILED-EVALUATING: ${T}`,m-=T,f=` SKIPPED: ${ai(e,this.options)}`}let h=this.buildTestPlanName(o,t,i),y,b=kr[m?"error":"success"],x=`PASSED: ${p} FAILED: ${m}${g} ABORTED: ${d}${f} Duration: ${uo(s)}`;i||h.trim()===""||h.trim()==="Anonymous"?y=`Tests completed. ${x} (Execution ID: ${n})`:y=`Test plan${h} completed ${x} (${n})`,this.printWorkerDivider(),console.log(b(y)),this.printWorkerDivider(),this.printAllFailedTests(a)}buildTestPlanName(e,t,s){if(s)return"";let n=xn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,o=xn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=xn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,a=xn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,c=[i,o,n,a].filter(Boolean).join(", ");return e?` anonymous (${c})`:` '${t}'`}onTestPlanStarted(e,t,s,n,o,i,a,c){let u=m=>{m.forEach((g,f)=>{var b;let h=(b=g.testData)!=null&&b.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=c?"":`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${Je(g,this.options)?"-quarantine":""}`,y,h)})},p=a?`config '${a}'`:"default configs";if(c)console.log(`Run test plan, Project: ${this.options.project} (Execution ID: ${o}):`);else{let m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",g=`${p}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${g} (${o})`)}this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),u(e)),console.log(c?"File list:":"Test list:"),u(t),s.length>0&&(console.log("After all:"),u(s)),this.printWorkerDivider()}onGetSlot(e,t){let s=this.options.grid||this.options.gridId,n=this.options.mode===gi.APPIUM?Df:t;s&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(s)}`)}onGetSession(e,t,s){let n=s===gi.APPIUM?Df:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e,t,s){let n=t?"file":"test";console.log(this.toWorkerIdPrefix(e),`Wait for ${n} complete`),s&&t&&console.log(this.toWorkerIdPrefix(e),`Chrome Debugger available at ${s}`)}onGetBrowserFailure(e,t,s){if(s!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===gi.APPIUM?"device":"browser";if(n)console.log(kr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(kr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===gi.APPIUM?"Appium":"Selenium";console.log(kr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Hv=Jl});var eu={};W(eu,{Reporter:()=>Qv});function zv(r){let e=r.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${r.name}${t}`}function Kv(r){return r.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${r.visitedUrlsList||""}`}function Jv(r){return`${r.visitedUrlsJson||""}`}async function Yv(r,e,t,s,n,o){function i(m){let g=at(r,t,m.testId,m.resultId,s),f={$:{name:zv(m),classname:n,time:gc(m.duration),ownedBy:m.testOwnerName,ownerEmail:m.testOwnerEmail},"system-out":g};if(Rn(m)||ql(m)){let h=`Step Failed: ${m.failureReason||m.reason}`,y=Rn(m)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Hl(m)&&Je(m,o)&&Pt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=Kv(m),f["visited-urls-json"]=Jv(m)),f}function a(m){let{results:g,testPlanName:f,configName:h}=m,y=g||{},x={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:u(y),failure:p(y),timestamp:c(e)};if(Pt.isTestStatusEnabled){x.skipped=ai(y,o);let T=ci(y);x.failure-=T,x["failure-evaluating"]=T}return{$:x,testcase:Object.keys(y).map(T=>i(y[T]))}}function c(m){let g=Object.keys(m).map(h=>m[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function u(m){return Object.keys(m).length}function p(m){return li(m).length+di(m).length}let d={testsuites:{testsuite:e.map(m=>a(m))}};try{return new Zl.Builder().buildObject(d)}catch(m){return Xv(m)}}function Xv(r){let e=new Zl.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:r.message}}}}}};return e.buildObject(t)}var Zl,Nf,Ql,Qv,tu=w(()=>{"use strict";Zl=E(require("xml2js"));U();Nf=require("fs");In();pi();Ql=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,s=this.options.project,n=await Yv(this.options.editorUrl,e,s,this.branchToUse,this.classname,this.options);if(t)try{return await Nf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Qv=Ql});var Mf={};W(Mf,{Reporter:()=>Zv});function gs(r){return r?r.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var ru,su,Zv,Ff=w(()=>{"use strict";j();ru=I("team-city-reporter");su=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},s=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${s}`;return gs(n)}onTestStarted(e,t,s,n,o){if(s){ru.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${o}']`)}onTestFailed(e,t,s,n,o,i){if(o){ru.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${gs(t)}' details='${gs(s)}' flowId='${i}']`)}onTestFinished(e,t,s){if(s){ru.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,s="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${gs(s)}']`)}onTestPlanStarted(e,t,s,n){console.log(`##teamcity[testSuiteStarted name='${gs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${gs(t)}']`)}},Zv=su});var Uf={};W(Uf,{Reporter:()=>eE});var nu,eE,jf=w(()=>{"use strict";nu=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,s,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},eE=nu});var Bf={};W(Bf,{Reporter:()=>tE});var ou,tE,$f=w(()=>{"use strict";U();vl();ou=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e,t,s,n){if(n)return;let o=at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Go(o)}},tE=ou});var rE,iu,Z,Bt=w(()=>{"use strict";Lf();j();rE=I("reporter"),iu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let s=e.reporters;if(this.reporters.push(new fi(e)),s===void 0||s.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Xl(),Yl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(tu(),eu));this.reporters.push(new o(e,t))}}else(await Promise.all([s.includes("teamcity")&&Promise.resolve().then(()=>(Ff(),Mf)),s.includes("console")&&Promise.resolve().then(()=>(Xl(),Yl)),s.includes("junit")&&Promise.resolve().then(()=>(tu(),eu)),s.includes("json")&&Promise.resolve().then(()=>(jf(),Uf)),s.includes("chrome")&&Promise.resolve().then(()=>($f(),Bf))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,s,n,o,i,a){let c={};if(a){let p=Object.values(a);if(p.length>0){for(let d of Object.values(a))c[d.id]=d;for(let d of Object.keys(e))p.some(m=>m.parentResultId!==d)||(c[d]=e[d])}else rE.warn("childTestResults is not array"),c=e}else c=e;let u=Date.now()-(s||0);return[c,t,u,n,o,i,void 0]}onAllTestPlansFinishedMutator(e){for(let t of e)if(t.childTestResults){t.results={};let s=Object.values(t.childTestResults);for(let n of s)t.results[n.id]=n;for(let n of Object.keys(e))s.some(o=>o.parentResultId!==n)||(t.results[n]=e[n])}return[e]}generateHook(e,t){return async(...s)=>{var o;let n=t==null?void 0:t(...s);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||s))}}},Z=new iu});function Gf(r,e){return e!=null&&e.type&&(r[`${e.type}Mode`]=!0),r}function Vf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:u,user:p,lightweightMode:d,isStartUp:m,projectType:g,appSource:f}){let h=Gf({executionId:r,projectId:e,testId:t,resultId:s,companyId:n,companyName:o,projectName:i,companyPlan:a,sessionType:c,source:Wf(u,p),isStartUp:m,projectType:g,...["android","ios"].includes(g)&&f&&{appSource:f}},d);ht("test-run-ci",h)}function qf({executionId:r,projectId:e,testId:t,resultId:s,result:n,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:u,source:p,user:d,lightweightMode:m,logger:g,isStartUp:f,projectType:h,appSource:y}){try{let b=Gf({executionId:r,projectId:e,testId:t,resultId:s,companyId:o,companyName:i,projectName:a,companyPlan:c,sessionType:u,mockNetworkEnabled:n.wasMockNetworkActivated,source:Wf(p,d),isStartUp:f,projectType:h,...["android","ios"].includes(h)&&y&&{appSource:y}},m);if(n.success){ht("test-run-ci-success",b);return}ht("test-run-ci-fail",Object.assign({},b,{failureReason:n.failureReason}))}catch(b){g.error("failed to update test end analytics",{err:b})}}function Hf({executionId:r,projectId:e,sessionType:t}){ht("batch-run-ci",{executionId:r,projectId:e,sessionType:t})}var Wf,au=w(()=>{"use strict";us();Oo();Wf=(r,e)=>r!=="cli"&&r!=="cli-local"?r:is&&e?"ci-with-user":is?"ci":e?"cli-with-user":r});var sE,Kf=w(()=>{"use strict";sE=require("istanbul-lib-report")});var Jf,Yf,nE,Xf,_r,oE,Qf,cu,iE,Zf,eg=w(()=>{"use strict";Jf=E(require("ora")),Yf=E(require("moment")),nE=E(require("test-exclude")),Xf=E(require("fs")),_r=E(require("path")),oE=E(require("istanbul-reports")),Qf=E(require("istanbul-lib-report"));we();q();U();j();bt();Kf();cu=I("test-run-status"),iE=async(r,e,t)=>{let{mergeProcessCovs:n}=await ge("@bcoe/v8-coverage"),o={result:[]},i=new Map,c=(await mn(r,"testResult",`runId=${t}`)).data.docs;return await le(c.flatMap(u=>u.JSCoverageURLS||[]),async u=>{let p=await pn(u,9e4);await le(p,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await(void 0)(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,o=n([o,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:o}},Zf=async(r,e,t,s)=>{if(!r.collectCodeCoverage)return;cu.info("start js coverage process");let n=(0,Jf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=_r.resolve(r.codeCoverageReportPath||"./coverage"),i=_r.resolve(o,`.js/${(0,Yf.default)().format("DDMMYYYYHHmmss")}`),a=r.codeCoverageSourceMapPath?_r.resolve(r.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:u,covUrlMap:p}]=await Promise.all([ge("istanbul-lib-coverage"),iE(r.project,e,s)]);if(u.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}cu.info("start js coverage merge and remap",{numOfFiles:p.size,numMergedCoverages:u.result.length});let d=c.createCoverageMap({}),m={};await le(u.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:b}=p.get(f),x=await(void 0).getSourceMap({sourceMapType:b,url:f,source:y,sourceMapDir:a});m[f]=x;let T=await(void 0).convertV8ToIstanbul(r,{source:y,sourceMap:x,functions:h});d.merge(T)}),await(void 0).remapCoverage(r,i,m);let g=await(void 0).saveCoverageReports(r,d,o,i);return n.succeed(),g}catch(c){let u="Failed to report coverage information";c instanceof P?n.fail(`${u}, missing arg: ${c.message}`):n.fail(u),cu.error(u,{err:c})}}});var tg={};W(tg,{SELENIUM_PERF_MARKS:()=>Ae,SeleniumPerfStats:()=>$t});var Ae,$t,hs=w(()=>{"use strict";U();Ae={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},$t=class{constructor(){this.marks=Object.fromEntries(Object.values(Object.assign({ALL:"ALL"},Ae)).map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=K();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let s=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(s);return}this.marks[t].push(s)}getStats(){let e=Object.entries(this.marks).flatMap(([t,s])=>!Array.isArray(s)||!s.length?[]:[[`${t}_COUNT`,s.length],[`${t}_P50`,fo(s,50)],[`${t}_P95`,fo(s,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var og={};W(og,{initServer:()=>lE,mapFilesToLocalDrive:()=>uu});function uu(r,e){var t;try{r.failurePath=(r.failurePath||[]).map(s=>Object.assign(s,hi[s.id]?{screenshot:hi[s.id]}:{})),Object.keys(ys).forEach(s=>{r.assets||(r.assets={}),r.assets[ng[s]]=ys[s]}),r.assets||(r.assets={}),r.assets.screenshots=Object.values(hi)}catch(s){e&&e.error("failed to map files to local drive",{err:s}),r.failurePath||(r.failurePath=[]),r.assets||(r.assets={}),(t=r.assets).screenshots||(t.screenshots=[])}}async function lE({agentPort:r,agentBind:e,saveRCALocally:t}){let s=await ge("multer"),n=typeof t=="string"?t:aE;await lu.promises.mkdir(n,{recursive:!0});let o=s({storage:s.diskStorage({async destination(c,u,p){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return p(new Error("missing testResultId"),"");let m=Pn.join(n,d.testResultId);try{await lu.promises.mkdir(m,{recursive:!0})}catch(g){return p(g,"")}return p(null,m)},filename(c,u,p){let{fileName:d}=c.body,m=JSON.parse(c.body.metadata||"{}");if(!m.stepId&&!d)return p(new Error("missing stepId or fileName"),"");if(m.stepId){let g=Pn.extname(d);return p(null,`step_${m.stepId}_${m.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return p(null,d)}})}),i=(0,sg.default)();i.post("/",o.single("file"),(c,u)=>{var d;let p=JSON.parse(c.body.metadata||"{}");p.stepId&&(hi[p.stepId]=c.file.path),p.testResultId&&cE.includes(p.subType)&&(ys[d=p.subType]||(ys[d]=[]),ys[p.subType].push(c.file.path)),u.sendStatus(200)}),i.use((c,u)=>u.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,u)=>{let p=a(i);p.listen(r,e),p.on("error",d),p.on("listening",()=>c(p.address()));function d(m){if(m.syscall!=="listen")return u(m);switch(m.code){case"EACCES":case"EPERM":return u(new P(`Port ${r} requires elevated privileges`));case"EADDRINUSE":return u(new P(`Port ${r} is already in use`));default:return u(m)}}})}var lu,rg,Pn,sg,aE,hi,ys,ng,cE,du=w(()=>{"use strict";lu=E(require("fs")),rg=E(require("os")),Pn=E(require("path")),sg=E(require("express"));q();bt();aE=Pn.join(rg.tmpdir(),"testim/rca/"),hi={},ys={},ng={"test-log":"consoleLogs","har-file":"networkLogs"},cE=Object.keys(ng)});var tr,pu,yi,ig=w(()=>{"use strict";tr=E(require("lodash"));U();j();pu=I("override-test-data-builder"),yi=class{constructor(e,t,s){this.params=e;this.testInfoList=t;this.projectId=s}isObjectNotArray(e){return tr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(s=>this.overrideSingleTest(s,e.overrideTestData[s])),delete e.overrideTestData):pu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):pu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:s}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}pu.error("skip override test data to test name",{testName:e,projectId:s}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let s=this.mapTestListToUniqueId(e);if(s.length!==0)return this.createNewTestPerOverrideTestData(s,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return tr.chain(t).map(s=>{if(s.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(s)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:s}=this;return[...new Set(e)].map(n=>{let o=s.map(p=>this.generateTestUniqId(p)),i=o.indexOf(n),a=o.lastIndexOf(n),c=s[i],u=this.createNewTestItems(c,t);return s.splice(i,a-i+1,...u)})}createNewTestItems(e,t){return[].concat(t).map((s,n)=>{let o=K();return Object.assign({},e,{resultId:o,testData:{value:s,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function bi(r,...e){if(!(!r||typeof r!="function"))try{return await r(...e)||{}}catch(t){throw Xe.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Or,Xe,uE,dE,pE,mE,wi,ag=w(()=>{"use strict";Or=E(require("lodash"));U();ae();fs();we();q();j();Bt();hn();eg();hs();du();de();ye();ig();In();Xe=I("test-run-status"),uE=Sr(),dE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,pE=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,mE=ct();wi=class{constructor(e,t,s,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new $t;var a,c,u,p,d;(a=this.options).runParams||(a.runParams={}),this.fileUserParamsData=this.options.userParamsData;let o=Js(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:no||t.parallel||1,browser:o,gitBranch:uE,gitCommit:dE,gitRepoUrl:pE,runnerVersion:mE,gridHost:t.host||((c=t.gridData)==null?void 0:c.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:s,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((u=t.gridData)==null?void 0:u.gridId),gridName:t.grid||((p=t.gridData)==null?void 0:p.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:vr(t)},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:s,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,isTestsContainer:u,testId:p,name:d,testStatus:m,testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:b,testSuites:x,allLabels:T}=a,v={originalTestResultId:t,previousTestResultId:s,config:Or.cloneDeep(c),testId:p,status:"QUEUED",name:d,resultId:e,isTestsContainer:u,retryCount:i,testStatus:m};return this.testRunStatus[e]=Object.assign({},v,{testCreatorName:g,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:y,testLabels:b,testSuites:x,allLabels:T}),il({projectId:n,runId:o,testId:p,newResultId:e,originalTestResultId:t,previousTestResultId:s,testResult:v})}getAllTestResults(){return this.testRunStatus}testStart(e,t,s,n){let o=this.getTestResult(s);o.workerId=e;let i=this.options.files.length>0;return Z.onTestStarted(o,e,n,i,s),o}async updateTestStatusRunning(e,t,s){var u;let{project:n,remoteRunId:o,projectData:i}=this.options;if((u=this.options.lightweightMode)!=null&&u.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Mo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(p){Xe.error("failed to upload test data artifact (runner)",{err:p})}let c=Or.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,as(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:s})}async testStartReport(e,t,s){if(Je(e,this.options))return;let n=this.exportsGlobal;try{let o=await bi(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,s),e}catch(o){throw Xe.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,s,n,o){let i=this.testStart(e,t,s,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let s=this.getTestResult(e);s.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Xe.info("on get grid info",{gridInfo:s.config.gridInfo})}reportTestStatus(e,t,s,n){let{name:o,testId:i,testStatus:a}=s,{resultId:c,success:u}=t;if(a===Ke.EVALUATING&&Pt.isTestStatusEnabled){Z.onTestIgnored(e,s,`test in ${Ke.EVALUATING} status`);return}if(u){Z.onTestPassed(o);return}Z.onTestFailed(s,s.failureReason,at(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let s=this.getTestResult(t);Z.onTestIgnored(e,s,`test in ${Ke.QUARANTINE}`)}monitorMemoryUsage(e){let t=hc();if(t.isOverThreshold){let s=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Xe.info(`using ${s} to parse html`,{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}}testEnd(e,t,s,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&uu(i,Xe),i.resultUrl=at(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||(t.testId=i.testId),t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o);let c=this.options.files.length>0;this.monitorMemoryUsage(i),Z.onTestFinished(i,e,o,c);let u=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=u,i}async testEndReport(e,t,s,n){var i;let o=s.exportsGlobal;try{try{await bi(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Xe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await as(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:s.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Xe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,s,n,o,i){let a=this.testEnd(e,t,s,n,o);return this.testEndReport(a,s,t,i)}calcTestRunStatus(){let{options:e,testInfoList:t}=this,s=e.company.companyId,n=t.map(o=>{var d,m,g,f;let i=e.browser?tn(e.browser,e.saucelabs,e.browserstack):o.runConfig;if(i&&M.flags.dec2022eolBrowsers.isEnabled()&&((d=en(i.browserValue))!=null&&d.eol))throw new P(`Unsupported Browser: ${i.browserName}`);let a=!M.flags.allowAppFromDeviceRuns.isEnabled()&&Xs(o.nativeApp),c=Qs(e)&&(Zr(o.nativeApp)||a),u=Je(o,e)||c,p={testId:o.testId,status:u?pe.SKIPPED:pe.QUEUED,name:o.name,resultId:o.resultId,isTestsContainer:o.isTestsContainer,testStatus:o.testStatus||Ke.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...c&&{reason:Zr(o.nativeApp)?"virtual-build":"app-from-device"},config:Object.assign({},this.execConfig,{companyId:s,testData:((m=o.testData)==null?void 0:m.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((g=o.testData)==null?void 0:g.total)||null,testDataIndex:((f=o.testData)==null?void 0:f.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,p]});return Object.fromEntries(n)}async executionStart(e,t,s,n,o){Xe.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;cs(()=>Promise.all([vn.end(t),Do("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=s||Date.now();let u={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},p=await bi(i.beforeSuite,u),d=new yi(p,Or.cloneDeep(this.testInfoList),t);this.testInfoList=d.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=p;let{testInfoList:m}=this,g=[],f=[],h=[];for(let b of m){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){h.push(b);continue}f.push(b)}let y=async()=>{let b=Or.cloneDeep(this.testRunStatus);await le(Object.keys(b),async R=>{var A;let k=b[R],L=(A=k.config)==null?void 0:A.testData,S=k.testId,O=await Mo(t,S,R,L,c.defaults);O&&(delete k.config.testData,k.config.testDataUrl=O)});let x=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),T={executionId:e,projectId:t,labels:n||[],startTime:s,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:x,intersections:i.intersections},v=Wc(T);return this.executionStartedPromise=v,v.catch(R=>Xe.error(R)),v};try{await y()}catch(b){Xe.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){Or.chain(e).keys().each(t=>{let s=t;this.seleniumPerfStats.marks[s]&&(this.seleniumPerfStats.marks[s]=[...this.seleniumPerfStats.marks[s],...e[s]])}).value()}async executionEnd(e){var p;let t=bc(this.testRunStatus),s=t.length,n=0,o=0,i=0;for(let{status:d,testStatus:m}of t)d===pe.PASSED&&n++,d===pe.SKIPPED&&o++,d===pe.FAILED&&m===Ke.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await bi(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:s,passed:n,skipped:o})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Xe.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let u=await Zf(this.options,this.branchToUse,s,e);if(Object.assign(c,{coverageSummary:u}),!((p=this.options.lightweightMode)!=null&&p.onlyTestIdsNoSuite))try{return await Do("FINISHED",e,this.options.project,s===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Xe.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,s,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await $c(e,["QUEUED"],t,s,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=s,a.success=n}return this.testRunStatus}}});function fE(r){let e=lg(r);return r===re.TESTIM_HEADSPIN?`${e}/lock`:""}function lg(r){return r===re.TESTIM_HEADSPIN?"https://api-dev.headspin.io/v0/devices":""}function ug(r){return{...r.type===re.TESTIM_HEADSPIN&&{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`}}}function gE(r,e){return{...r.type===re.TESTIM_HEADSPIN&&{device_id:e}}}async function dg(r,e){let t=fE(r.type),s=ug(r),n=gE(r,e);try{await tt({url:t,headers:s,body:n})}catch(o){throw cg.debug(`error while locking device ${e}`,{error:o}),o.status===401?new Error(`failed to lock device ${e}, device may be already locked and in use`):o}}async function mu(r,e){let s=`${lg(r.type)}/device_id:${e}/automation-config`;try{let n=await Ot(s,void 0,ug(r));return hE(n,r.accessToken)}catch(n){throw cg.error("error while getting automation config for device",{error:n,deviceId:e}),n}}function hE(r,e){let t=Object.keys(r)[0],s=r[t].driver_url,n=new URL(s);return{hostname:n.hostname,port:Number(n.port),protocol:n.protocol.slice(0,-1),path:`/v0/${e}/wd/hub`}}async function pg(r,e){let t={};return r.type===re.TESTIM_HEADSPIN&&(t=await mu(r,e)),t}async function mg(r,e,t){var g;let{executionId:s,testId:n,testResultId:o}=r,{project:i,projectData:{type:a}={},company:{companyId:c=""}={},gridData:{gridId:u=""}={}}=t,p=await pl({projectId:i,projectType:a,companyId:c,gridId:u,selectors:`device_id:${e.capabilities.udid}`}),m={name:(g=p==null?void 0:p[0])==null?void 0:g.name,model:e.capabilities.deviceModel,osVersion:e.capabilities.platformVersion,udid:e.capabilities.udid,osType:e.capabilities.platformName,scaleFactor:e.capabilities.pixelRatio,virtual:!1};await as(i,s,n,o,"RUNNING",{device:m})}var cg,fu=w(()=>{"use strict";j();ae();we();mt();cg=I("mobile-grid-service")});function bE(r,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(r.desiredCapabilities,t),r}function wu(r){return hg.readFileSync(r,{encoding:"base64"})}function wg(r,e,t){if(!(t!=null&&t.isLambdatestRun()&&Ge(r))&&r){let s=wu(r);bs.info(`adding extension: custom, path: ${r} length: ${s.length} hash: ${bu(s)} current extension count: ${e.length}`),e.push(s)}}function Tg(r,e,t,s,n){if(n!=null&&n.isLambdatestRun())return;if(r.ext||s){let c=typeof r.ext=="string"?r.ext:`${__dirname}/..`,u=s||c,p=`--load-extension=${u}`;bs.info(`adding extension: testim unpacked , path: ${u}`),t.push(p);return}let o=r.canary?"-master.zip":".zip",i=yu.join(process.cwd(),`testim-headless${o}`),a=wu(i);bs.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${bu(a)} current extension count: ${e.length}`),e.push(a)}function wE(r,e,t,s,n,o,i){var h,y;let a=t.seleniumName||t.browserValue,c=[],u=[...bg];e.headless&&u.push("--headless");let p=()=>e.mode!==J.EXTENSION,d={prefs:{"profile.default_content_setting_values.popups":gu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":gu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:p()};hu(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",d.w3c=!0,r.desiredCapabilities.version="latest-1",r.desiredCapabilities["aws:maxDurationSecs"]=2400,r.desiredCapabilities["aws:idleTimeoutSecs"]=60),hu(n)&&a==="MicrosoftEdge"&&(r.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(b=>u.push(`--${b}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=gu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&u.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(h=e.projectData)==null?void 0:h.defaults)!=null&&y.disableChromiumGpu&&u.push("--disable-gpu"),Object.assign(r.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+uc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),wg(s,c,i),e.mode===J.EXTENSION&&Tg(e,c,u,o,i),c.length>0&&(d.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=u;let g={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return X.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(r.desiredCapabilities[g]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(r.desiredCapabilities[`${f}:${g}`]=d),r}function vE(r,e,t){let s={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(s,{"browser.helperApps.neverAsk.saveToDisk":gg.join(","),"browser.helperApps.neverAsk.openFile":gg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(r.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:s}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(r.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===J.EXTENSION)if(e.ext)r.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=yu.join(process.cwd(),`testim-firefox-profile${n}`);r.desiredCapabilities.firefox_profile=wu(o)}return e.headless&&(r.desiredCapabilities["moz:firefoxOptions"].args||(r.desiredCapabilities["moz:firefoxOptions"].args=[]),r.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),r}function EE(r,e,t){let{saucelabs:s}=r;return s!=null&&s.username&&s.accessKey?t?(t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=s.appiumVersion||t.sl.appiumVersion,Object.assign({},t.sl,s,{name:e})):Object.assign({},s,{name:e}):{}}function SE(r,e,t){return wt.isEmpty(r.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,r.browserstack,{name:e})):Object.assign({},r.browserstack,{name:e})}function RE(r){return r.perfecto?r.perfecto:{}}function IE(r,e,t){if(r.experitestToken){let s=e==="safari";return{accessKey:r.experitestToken,browserVersion:"latest",platformName:s?"MAC":"WIN10",seleniumScreenshot:s,newSessionWaitTimeout:t}}return{}}function xE(r,e={}){let{gridData:t={},gridUsername:s,gridPassword:n}=r,o=s||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Ua(o,i)),a}function Ti(r,e,t,s,n,o,i,a=null){var h,y,b,x,T,v;if(s.mode==="local"){let R=[],k=[...bg],L={};return r.headless&&k.push("--headless"),r.silentDebuggerExtensionApi&&k.push("--silent-debugger-extension-api"),r.remoteDebuggingPort!==void 0&&k.push(`--remote-debugging-port=${r.remoteDebuggingPort}`),r.chromeExtraArgs&&r.chromeExtraArgs.forEach(S=>k.push(`--${S}`)),r.chromeBinaryLocation&&(L.binary=r.chromeBinaryLocation),r.mode!=="selenium"&&Tg(r,R,k,null,a),wg(n,R,a),{logLevel:fg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:k,extensions:R,...L},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:u}=r,p=xE(r,s),d={hostname:s.host,host:s.host,port:s.port||4444,path:s.path||"/wd/hub",protocol:s.protocol||"http",logLevel:fg,connectionRetryTimeout:c,connectionRetryCount:u,getSessionTimeout:Math.max(a.getSessionTimeout,r.getSessionTimeout),getSessionRetries:a.getSessionRetries||r.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!wt.isEmpty(p)&&{headers:p},...r.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};hu(s)&&(r.oldCapabilities=!1,r.w3cCapabilities=!0,d.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),r.disableNativeEvents&&(d.desiredCapabilities.nativeEvents=!1),s.user&&s.key&&(s.type==="saucelabs"&&(r.saucelabs||(r.saucelabs={}),(h=r.saucelabs).username||(h.username=s.user),(y=r.saucelabs).accessKey||(y.accessKey=s.key)),s.type==="browserstack"&&(r.browserstack||(r.browserstack={}),(b=r.browserstack)["browserstack.user"]||(b["browserstack.user"]=s.user),(x=r.browserstack)["browserstack.key"]||(x["browserstack.key"]=s.key))),s.key&&s.type==="perfecto"&&(r.perfecto.securityToken=s.key);let m=Number(r.browserTimeout/1e3),g=r.browser||(t==null?void 0:t.browserValue);wt.merge(d.desiredCapabilities,EE(r,e,t),SE(r,e,t),RE(r),IE(r,g,m),a==null?void 0:a.getCapabilities(r,g,o,i,e));let f=null;switch(!r.ext&&!r.extensionPath&&((T=s.host)!=null&&T.endsWith(".testim.io"))&&!r.canary&&r.mode===J.EXTENSION&&(g==="chrome"?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),(v=s.host)!=null&&v.endsWith(".testim.io")&&g==="edge-chromium"&&(d.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":d=TE(d,r,t,n,s,f,a);break;case"firefox":d=vE(d,r,a);break;case"safari":case"safari technology preview":d=bE(d,g);break;default:break}wt.merge(d.desiredCapabilities,r.seleniumCapsFileContent);try{let R={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},k=A=>A[s.provider]||A[d.host]||A[R[d.host]],L=A=>{var N,B;return k(A)||A[(N=d.desiredCapabilities)==null?void 0:N.browserName]||A[(B=d.desiredCapabilities)==null?void 0:B.version]||A||{}},S=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),O=L(L(S));Object.keys(O).length&&(bs.info(`Adding custom capabilities: ${JSON.stringify(O)}`),Object.assign(d.desiredCapabilities,O))}catch(R){bs.error("Failed to load custom capabilities",{error:R,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return d.desiredCapabilities&&!d.capabilities&&(yE(d.desiredCapabilities),d.capabilities={alwaysMatch:d.desiredCapabilities,firstMatch:[{}]},delete d.desiredCapabilities),d.hostname=d.host,d}function vg({nativeApp:r,appPath:e,gridInfo:t}){if(!r&&!e)throw Error("missing mobile app!");if(t.type!==re.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid")}function Eg({projectType:r,nativeApp:e,appPath:t,androidActivityWait:s,sessionTags:n,options:o}){let{fullReset:i,resetAppData:a,resetOnSessionStartOnly:c,skipLoadBalancer:u}=o,p={"headspin:capture":!0,...u&&{"headspin:controlLock":!0},"headspin:retryNewSessionFailure":!1,"headspin:sessionTags":n,...!i&&!a&&{"appium:noReset":!0},...!i&&a&&{"appium:noReset":!1}};switch(r){case"ios":p={...p,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...i&&{"appium:fullReset":i,"appium:resetOnSessionStartOnly":c},...e&&{"appium:bundleId":e.id},...t&&{"appium:app":t}};break;case"android":p={...p,platformName:"Android",...i&&{"appium:fullReset":i},...!i&&a&&{"appium:autoGrantPermissions":!0},"appium:automationName":"UiAutomator2","appium:appWaitActivity":s,...e&&{"appium:appPackage":e.id||e.packageName,"appium:appActivity":e.activity},...t&&{"appium:app":t}};break;default:throw Error(`unsupported mobile project ${r}`)}return p}function Sg({projectType:r,gridInfo:e,nativeApp:t,options:s,appPath:n,androidActivityWait:o,sessionTags:i}){let{deviceModel:a,osVersion:c,deviceUdid:u}=s,p={};vg({nativeApp:t,appPath:n,gridInfo:e});let d={protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`},m=Eg({projectType:r,nativeApp:t,appPath:n,androidActivityWait:o,options:s,sessionTags:i});return a&&(p.model=a),c&&(p.os_version=c),u&&(p.device_id=u,delete p.model,delete p.os_version),wt.isEmpty(p)||(m["headspin:selector"]=p),{...d,desiredCapabilities:m,capabilities:m,connectionRetryCount:0,logLevel:s.appiumLogLevel}}async function Rg({projectType:r,gridInfo:e,nativeApp:t,options:s,appPath:n,androidActivityWait:o,sessionTags:i}){let{deviceUdid:a}=s;vg({nativeApp:t,appPath:n,gridInfo:e});let c=await pg(e,a),u=Eg({projectType:r,nativeApp:t,appPath:n,androidActivityWait:o,options:s,sessionTags:i});return a&&(u["appium:udid"]=a),{...c,desiredCapabilities:u,capabilities:u,connectionRetryCount:0,logLevel:s.appiumLogLevel}}var hg,yu,yg,wt,bs,fg,gu,bg,bu,hu,yE,TE,gg,vi=w(()=>{"use strict";hg=E(require("fs")),yu=E(require("path")),yg=E(require("crypto")),wt=E(require("lodash"));U();de();j();ye();ae();ei();fu();bs=I("testim-desired-capabilities-builder"),fg=so?"debug":"silent",gu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},bg=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],bu=(...r)=>yg.createHash("sha256").update(r.join("")).digest("hex"),hu=r=>r.type===re.DEVICE_FARM||r.type===re.HYBRID&&r.provider==="devicefarm",yE=r=>{Object.prototype.hasOwnProperty.call(r,"version")&&(r.browserVersion=r.version,delete r.version),Object.prototype.hasOwnProperty.call(r,"platform")&&(r.platformName=r.platform,delete r.platform),Object.prototype.hasOwnProperty.call(r,"acceptSslCerts")&&(r.acceptInsecureCerts=r.acceptSslCerts,delete r.acceptSslCerts),Object.prototype.hasOwnProperty.call(r,"unexpectedAlertBehaviour")&&(r.unhandledPromptBehavior=r.unexpectedAlertBehaviour,delete r.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(r,"chromeOptions")&&(r["goog:chromeOptions"]??(r["goog:chromeOptions"]=r.chromeOptions),delete r.chromeOptions),Object.prototype.hasOwnProperty.call(r,"edgeOptions")&&(r["ms:edgeOptions"]??(r["ms:edgeOptions"]=r.edgeOptions),delete r.edgeOptions),Object.prototype.hasOwnProperty.call(r,"firefoxOptions")&&(r["moz:firefoxOptions"]??(r["moz:firefoxOptions"]=r.firefoxOptions),delete r.firefoxOptions);let e;try{e=M.flags.unsupportedCapsFields.getValue();let t=JSON.parse(e);if(!Array.isArray(t))return;t.forEach(s=>{delete r[s]})}catch{bs.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:e})}};TE=wt.memoize(wE,(r,e,t,s,n,o)=>{let i=JSON.stringify(r.desiredCapabilities),a=JSON.stringify(wt.omit(e,"runParams")),c=JSON.stringify(t),u=JSON.stringify(n.type);return bu(i,a,c,s,u,o)}),gg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(r){var e,t,s,n,o,i,a;return((e=r.message)==null?void 0:e.match(/Command not found/))||r.message==="HTTP method not allowed"||r.message==="Unknown error"||((t=r.message)==null?void 0:t.match(/Unknown timeout type/))||r.name==="unknown command"||((s=r.message)==null?void 0:s.match(/did not match a known command/))||((n=r.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=r.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=r.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=r.message)==null?void 0:a.match(/\.\w* is not a function/))}function Ig(r,e,t){if(!e||!r)return r;if(r.includes("%"))return r.replace(/ /g,"%20");try{return decodeURI(r)!==r?r:encodeURI(r)}catch(s){return t&&t.warn("tried to encode url but failed",{err:s,url:r}),r}}async function xg(r){if(!Ei||!Si){let[e,t]=await Promise.all([import("got"),import("webdriverio/node_modules/webdriver/build/utils.js")]);[Ei,Si]=[e.RequestError,t.CustomRequestError]}return!Ei||!Si?!1:r instanceof Ei||r instanceof Si}var Ei,Si,vu=w(()=>{"use strict"});function Eu(r){function e(m){return m?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(m.nodeType):!1}function t(m){return m?s(m.parentNode,e):null}function s(m,g){for(let f=m;f&&f!==m.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(m,g){for(let f=m;f&&f!==m.ownerDocument;f=t(f))if(g(f))return f;return null}function o(m,g){if(!m||!g)return null;m instanceof DocumentFragment&&(m=m.host);let h=window.getComputedStyle(m).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(m);return o(y,g)}function i(m){let g=m.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(m.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(m,"stroke-width");return!!h&&parseInt(h,10)>0}return o(m,"overflow")==="hidden"?!1:Array.from(m.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(m){return o(m,"overflow")==="hidden"}function c(m){return!m||!a(m)||!m.childNodes.length?!1:Array.from(m.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function u(m){var g;return m?(g=m.parentNode)!=null&&g.host?!0:u(m.parentNode):!1}if(!r||!u(r)&&!document.contains(r))return!1;switch(r.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=s(r,f=>f.tagName.toUpperCase()==="SELECT");return Eu(g)}case"INPUT":if(r.type==="hidden")return!1;break;default:break}if(o(r,"visibility")!=="visible")return!1;let p=!!n(r,m=>Number(o(m,"opacity"))===0),d=!!n(r,m=>o(m,"display")==="none");return!(p||d||!i(r)||c(r))}var Pg=w(()=>{"use strict"});var Ag,Cg,An,PE,AE,Ri,kg=w(()=>{"use strict";Ag=E(require("promise-queue")),Cg=E(require("webdriverio"));de();Oe();U();j();Bs();Pg();vu();hs();An=I("WebDriverApi"),PE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},AE={implicit:0,pageLoad:1,script:2},Ri=class{seleniumPerfStats;client;w3cRequests={};get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){return this.capabilities&&"browserName"in this.capabilities&&this.capabilities.browserName.toLocaleLowerCase()||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:s,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw An.warn("error from selenium",{err:e,testResultId:n,testName:s,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof Wa<"u"&&(e=Wa);let t=1/0;this.queue=new Ag.default(e,t)}async addToQueue(e){var s,n;let t=(s=this.seleniumPerfStats)==null?void 0:s.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,s){var o,i;this.testName=t,this.testResultId=s,e.deprecationWarnings=!1,this.initQueueRequests(),_("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ae.GET_BROWSER);try{await this.addToQueue(async()=>{An.info("requesting browser",{testResultId:s,testName:t}),_("before this.client.init"),this.client=await Cg.remote(e)}),_("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ae.GET_BROWSER)}}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){return this.capabilities&&"platformName"in this.capabilities&&this.capabilities.platformName.toLocaleLowerCase()==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if("execute"in this.w3cRequests&&this.w3cRequests.execute)return o();t=t.map(a=>{if(a===null){An.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Fe(a))return this.w3cRequests.execute=!0,o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,t),o=()=>this.client.executeAsyncScript(e,t);if("executeAsync"in this.w3cRequests&&this.w3cRequests.executeAsync)return n();try{return await o()}catch(i){if(Fe(i))return this.w3cRequests.executeAsync=!0,n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let s=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return s!=null&&s.targetInfos?s.targetInfos:[]}async takeScreenshot(){var t,s;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(Ae.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(s=this.seleniumPerfStats)==null||s.markEnd(e,Ae.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ae.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Ne(e)))}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),s=()=>this.execute(Eu,{ELEMENT:e,[qr]:e});if("elementIdDisplayed"in this.w3cRequests&&this.w3cRequests.elementIdDisplayed)return s();try{return await t()}catch(n){if(Fe(n))return this.w3cRequests.elementIdDisplayed=!0,s();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(Ig(e,this.isSafari(),An))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let s=()=>{let o=[];return o[AE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if("timeouts"in this.w3cRequests&&this.w3cRequests.timeouts)return n();try{return await s()}catch(o){if(Fe(o))return this.w3cRequests.timeouts=!0,n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let s=function(n,o){window.scrollTo(n,o)};return this.execute(s,e,t)}async setValue(e,t){return await this.elementIdClear(Ne(e)),await this.elementIdValue(Ne(e),t)}getViewportSize=async e=>{let t=await this.execute(PE);return typeof e=="string"&&e.match(/(width|height)/)?(e=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`,t.value[e]):{width:t.value.screenWidth||0,height:t.value.screenHeight||0}};async keys(e){let t=i=>Ma.hasOwnProperty(i)?[Ma[i]]:i.split(""),s=[];if(typeof e=="string")s=t(e);else if(Array.isArray(e))for(let i of e)s=s.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:s})},o=()=>{let i=s.map(c=>({type:"keyDown",value:c})),a=s.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.w3cRequests.keys)return o();try{return await this.addToQueue(()=>n())}catch(i){if(Fe(i))return this.w3cRequests.keys=!0,o();throw i}}async elementIdValue(e,t){return t=Array.isArray(t)?t.join():t,{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.elementSendKeys(e,t)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(Ne(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),s=await t.$('button[type="submit"]');return await s.isExisting()?s.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,s,n){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:t,y:s,button:n})})}}rightClick(e,t,s){return this.findElementAndPress(e,t,s,"right")}leftClick(e,t,s){return this.findElementAndPress(e,t,s,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.$(e).doubleClick()})}}async dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,s){let n={...typeof t=="number"&&{xOffset:t},...typeof s=="number"&&{yOffset:s}};return this.isSafari()&&!n.hasOwnProperty("yoffset")&&(n.yOffset=1),this.isSafari()&&!n.hasOwnProperty("xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let s=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);s=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.w3cRequests.windowHandleSize)return s();try{return await n()}catch(o){if(Fe(o))return this.w3cRequests.windowHandleSize=!0,s();throw o}})}}setCookie(e,t,s,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:s,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var s;return(await((s=this.client)==null?void 0:s.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){if(this.w3cRequests={},!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.w3cRequests={},!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var s;return(s=this.client)==null?void 0:s.isAppInstalled(e)});return An.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var _g,Og=w(()=>{"use strict";_g=function(r,e){let t=["pointerup","pointerdown","pointermove"],s=getLocatedElement(r.locatedElement);if(!s)throw new Error("element not found");let n=r.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(m){function g(x,T,v){return v>x&&v<T}let f=m.pointerPosition||{},h=s.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,b=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:b}},a=function(m,g){return{screenX:0,screenY:0,clientX:m,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(m,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(m,h)},u=function(m,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(m,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},p=function(){var g;let m=document.activeElement;for(;(g=m.shadowRoot)!=null&&g.activeElement;)m=m.shadowRoot.activeElement;return m},d=function(m){let g=i(m),f=m.event;return t.includes(f)?c(f,g.x,g.y):u(f,g.x,g.y)};try{n.map(g=>d(g)).filter(Boolean).forEach(g=>s.dispatchEvent(g));let m=p();dispatchFocus(r.elementToFocusLocatedElement,m),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(m){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:m.toString(),success:!1})}}});function Lr(r,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function s(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=s();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(r){let o=getLocatedElement(r);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Ii=w(()=>{"use strict"});var Mg={};W(Mg,{WebDriver:()=>Dr});async function OE(r){var e,t;try{let s=(t=(e=r==null?void 0:r.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return s?await kE(s):void 0}catch(s){Ve.info("Error getting cdpAddress",s);return}}var nr,Ng,Ve,rr,CE,Lg,kE,sr,_E,Dg,Dr,Cn=w(()=>{"use strict";nr=E(require("lodash"));U();Oe();vi();Ng=E(require("ua-parser-js"));Bs();j();vu();kg();q();Og();Ii();ye();hs();Ve=I("webdriver"),[rr,CE]=[0,2],{extractElementId:Lg,getCdpAddressForHost:kE}=H,sr=()=>(Ee(),ce(Cr)).getSessionPlayer().codeSnippets,_E=()=>(Ee(),ce(Cr)).getSessionPlayer().locatorBuilderUtils,Dg=()=>(Ee(),ce(Cr)).getSessionPlayer().utils;Dr=class extends Ri{constructor(){super(),this.started=!1,this.keepAliveTimer=null,this.unsupportedActions={},this._isAlive=!1,this._keepAliveRequests=[],this.cdpUrl=void 0,this.browserClosedCallbacks=[],this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=!1}registerToClosedBrowser(e){this.browserClosedCallbacks.push(e)}unregisterToClosedBrowser(e){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(t=>t!==e)}async init(e,t,s,n,o,i,a,c=new $t,u=!1,p){var f,h,y,b,x,T,v,R;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=(y=(h=(f=e==null?void 0:e.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.ignoreHiddenTagsText,this.browserClosedCallbacks=[];let d=Ti(e,t,s,n,o,i,a,p);d.desiredCapabilities&&delete d.desiredCapabilities.marionette,d.capabilities&&delete d.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(p==null?void 0:p.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=c;let m=u?0:1500,g=u?()=>{}:()=>this.executeJS("window.focus()");try{_("before initClient in webdriver.js init");let k=await this.initClient(d,t,a);_("after initResult before getCdpAddress in init"),this.cdpUrl=await OE(k),_("after getCdpAddress in webdriver.js init"),Ve.info(`init new session testName: ${t}`,{sessionId:this.getSessionId(),testResultId:a}),await ne(m),await g(),_("after focus and delay in webdriver.js init")}catch(k){Ve.error("failed to init webdriver",{err:k,capabilities:d});let L=((x=(b=e==null?void 0:e.company)==null?void 0:b.activePlan)==null?void 0:x.plan)==="free";throw(T=k.stack)!=null&&T.includes("at startWebDriverSession")&&((v=k.message)!=null&&v.startsWith("Failed to create session"))&&((R=k.message)!=null&&R.includes("Timeout awaiting 'request'"))&&L?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/capabilit(y|ies)/)?new Ws(k.message):new Error("failed to init client driver")}}initUnsupportedActions(e){e&&(this.unsupportedActions={...this.unsupportedActions,move:!0})}isAlive(){return this._isAlive}maxKeepAliveGap(){let e=n=>nr.zip(nr.dropRight(n,1),nr.drop(n,1)),t=this._keepAliveRequests.map(({start:n})=>n).filter(Boolean),s=e(t).map(([n,o])=>o-n);return Math.max(...s)}async isClosedBrowserError(e){return["session-not-found","no such window"].includes(e==null?void 0:e.name)?!0:await xg(e)?["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(s=>e.message.includes(s)):!1}start(){if(this.started)return;this.started=!0;let e=async()=>{let t=i=>this._keepAliveRequests.push({start:Date.now(),id:i}),s=(i,a)=>{let c=this._keepAliveRequests.find(u=>u.id===a);c&&(c[i]=Date.now())};function n(){var i;return(i=window.getTestimStatus)==null?void 0:i.call(window)}if(this.queue.getQueueLength()>0)return;let o=K();t(o);try{await this.executeJS(n),this._isAlive=!0,s("end",o),this.browserClosedFailedKeepAlives=0}catch(i){if(s("error",o),i.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ve.warn("close unexpected alert open"),await this.alertAccept().catch(a=>Ve.warn("failed to click on alert",{err:a}));return}if(Ve.warn("err while getting testim status",{err:i}),this._isAlive=!1,await this.isClosedBrowserError(i)){this.browserClosedFailedKeepAlives++;let a=3;this.browserClosedFailedKeepAlives>=a&&this.browserClosedCallbacks.forEach(c=>{try{c(i)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(e,1e4)}async switchToLocatedFrame(e){let t=await this.getElement(e),s=Lg(t.value);return await this.switchToFrame({ELEMENT:s,[qr]:s}),t}switchToFrame(e){return this.frame(e)}async switchToTopFrame(){var e;try{return await this.frame()}catch(t){throw(e=t.message)!=null&&e.includes("ECONNREFUSED")?new Gs:t}}async getElement(e){var n;let t=this.seleniumPerfStats.markStart(Ae.GET_ELEMENT);if(typeof e=="string"||typeof e=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${e}']`)}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)}if(((n=e==null?void 0:e.shadowPath)==null?void 0:n.length)||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
28
28
|
var fn = ${sr().getLocatedElementCode};
|
|
29
29
|
return fn.apply(null, arguments);
|
|
30
|
-
`,e)}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${e==null?void 0:e.testimId}']`)}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)}}executeJS(e,...t){return this.execute(e,...t)}async executeCodeAsync(e,t,s){return await this.timeouts("script",t),await this.executeAsync(e,s)}async markDynamicParent(e,t,s){function n(o){let i=o.attributeName,a=o.attributeValue,c=getLocatedElement(o.locatedElement);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(i,a)}return this.executeJS(`
|
|
30
|
+
`,e)}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${e==null?void 0:e.testimId}']`)}finally{this.seleniumPerfStats.markEnd(t,Ae.GET_ELEMENT)}}executeJS(e,...t){return this.execute(e,...t)}executeJSWithArray(e,t){return t.unshift(e),this.execute(...t)}async executeCodeAsync(e,t,s){return await this.timeouts("script",t),await this.executeAsync(e,s)}async markDynamicParent(e,t,s){function n(o){let i=o.attributeName,a=o.attributeValue,c=getLocatedElement(o.locatedElement);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(i,a)}return this.executeJS(`
|
|
31
31
|
var getLocatedElement = ${sr().getLocatedElementCode};
|
|
32
32
|
var setDynamicParentAttribute = ${n.toString()};
|
|
33
33
|
return setDynamicParentAttribute.apply(null, arguments)
|