@checksum-ai/runtime 1.3.1 → 1.3.3

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/index.js CHANGED
@@ -1835,7 +1835,7 @@ This might not be an issue, confirm by checking the response for this request on
1835
1835
  Will perform route.continue() instead.`):Qp.warning(`[ChecksumTimeMachine/preventCrossOriginErrors] Failed to process response for ${_}.
1836
1836
  Will perform route.continue() instead.`,C),o.continue()}})}catch(r){Qp.info("[ChecksumTimeMachine/preventCrossOriginErrors] Error setting up CORS interception",r)}}async start(){await this.timeMachineFrame.evaluate(async()=>{window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})})}setBrowserContext(t){this.timeMachineBrowserContext=t}async executeTask(t,r=void 0,{name:a,beforeTimestamp:o=!1,priority:c=!1}={}){return new Promise((f,_)=>{let b=e(async({shouldGoBack:C,shouldBatch:w}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{if(this.timeMachineFrame.isDetached()&&_(),C){let R=d0t.performance.now();await this.goBack(r,o),this.timeGoingBack+=d0t.performance.now()-R,this.taskQueue.setTimeGoingBack(this.timeGoingBack)}let T=e(R=>async()=>{try{let B=d0t.performance.now(),U=await uD(R(this.timeMachineFrame),this.options.taskTimeout,()=>`Task execution timeout - ${a}, took ${d0t.performance.now()-B}ms with timeout of ${this.options.taskTimeout}ms`);f(U)}catch(B){Qp.error("Task execution error:",B.message),_(B)}},"makeSafeRunTask"),k=[T(t)];if(this.taskQueue.getQueueLength()>0&&w){let R=this.taskQueue.getTasksAtTimestamp(r);k.push(...R.map(({task:B})=>T(()=>B({shouldGoBack:!1,shouldBatch:!1})))),this.taskQueue.removeTasksAtTimestamp(r),k.length&&console.log(`Batching to task "${a}" ${k.length-1} more tasks`)}for(let R of k)await R()},"taskWrapper");this.taskQueue.enqueue({name:a,task:b,timestamp:o?r-1:r,priority:c}),this.runTasks()})}executeReducedHTMLTask(t,{priority:r=!1}={}){if(this.reducedHTMLCache[t]){let a=new edt(this.reducedHTMLCache[t]);return Promise.resolve(a.getRrwebIdsReducedDomString())}return this.executeTask(async a=>{let o="",c=await this.getReducedHTMLWithRetries(a);return o=c==null?void 0:c.reducedHTML,o&&(this.reducedHTMLCache[t]=o),new edt(o).getRrwebIdsReducedDomString()},t,{name:"getReducedHTMLForTimestamp",priority:r})}goBack(t,r=!1){return this.currentBeforeTimestamp===r&&this.currentTimestamp===t?Promise.resolve():(this.currentTimestamp=t,this.currentBeforeTimestamp=r,this.timeMachineFrame.evaluate(({timestamp:a,beforeTimestamp:o})=>a===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(a,{beforeTimestamp:o}),{timestamp:t,beforeTimestamp:r}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}async runTasks(){await this.taskQueue.runTasks(async t=>{await t.task()})}async rrwebEventHandler(t){let r=JSON.stringify(t);try{await this.timeMachineFrame.evaluate(function(a){let o=JSON.parse(a);return window.checksum.timeMachine.handleEvents(o)},r)}catch{}return t=null,r}async makeBrowserContext(){let t=[];this.options.debugPort&&t.push(`--remote-debugging-port=${this.options.debugPort}`);let r=await cOn.chromium.launch({devtools:!1,headless:this.options.headless,args:t});return this.timeMachineBrowserContext=await r.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}subscribeToRrwebEvents(){let t="rrweb";this.frameMsgBroker.subscribeToChannel(t,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler.bind(this)}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(t,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(t){try{await this.timeMachineFrame.evaluate(r=>window.checksum.timeMachine.setShouldHandleEvents(r),t)}catch{}}};e(dRr,"ChecksumTimeMachine");var Sve=dRr;var mRr=require("@playwright/test"),_0t=Jp(require("fs")),lOn=Jp(require("fs/promises")),pOn=Jp(require("readline")),fOn=Jp(require("path")),dOn=Jp(YOt());var tma=1e3,_Rr=class _Rr extends Sve{constructor(r,a,o={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0,recordRRwebEventsToFile:!1,recordRRwebEventsToFilePath:"events.json"}){super(r,a,o);this.options=o;this.rrwebEventsBuffer="";this.didPostProcessRRwebEvents=!1;this.postProcessRRwebEvents=(0,dOn.debounce)(async()=>{return;try{let a=_0t.default.createReadStream(this.options.recordRRwebEventsToFilePath),o=pOn.default.createInterface({input:a,crlfDelay:1/0});for await(let c of o)if(c.trim()!=="")try{let f=JSON.parse(c);Array.isArray(f)?r.push(...f):r.push(f)}catch(f){Nv(`Failed to parse line: ${c}`,f)}_0t.default.writeFileSync(this.options.recordRRwebEventsToFilePath.replace(/([^\/]+)$/,"postprocessed.$1"),JSON.stringify(r)),this.didPostProcessRRwebEvents=!0}catch(a){Nv("Error post-processing RRweb events",a)}},100,{leading:!0,trailing:!0});if(this.options.recordRRwebEventsToFile){let c=this.options.recordRRwebEventsToFilePath,f=fOn.default.dirname(c);_0t.default.mkdirSync(f,{recursive:!0}),_0t.default.writeFileSync(c,"")}}setTimeMachineBrowserContext(r){this.timeMachineBrowserContext=r}getTimeMachineBrowserContext(){return this.timeMachineBrowserContext}async makeBrowserContext(){mRr.chromium._checksumInternal=!0;let r=await mRr.chromium.launch({devtools:!1,headless:this.options.headless});return r._checksumInternal=!0,this.timeMachineBrowserContext=await r.newContext({bypassCSP:!0}),this.timeMachineBrowserContext._checksumInternal=!0,this.timeMachineBrowserContext.tracing.startChunk=async()=>{},this.timeMachineBrowserContext.tracing.stop(),this.timeMachineBrowserContext.tracing.stop=async()=>{},this.timeMachineBrowserContext.tracing.stopChunk=async()=>{},this.timeMachineBrowserContext}async makeFrame(){let r=await this.timeMachineBrowserContext.newPage();r._checksumInternal=!0;let a=r.mainFrame();return a._checksumInternal=!0,a}async rrwebEventHandler(r){let a=await super.rrwebEventHandler(r);if(this.options.recordRRwebEventsToFile){if(this.rrwebEventsBuffer+=a+`
1837
1837
  `,this.rrwebEventsBuffer.length>tma){let o=this.rrwebEventsBuffer;this.rrwebEventsBuffer="",this.flushRRwebEventsToFile(o)}return a}}async flushRRwebEventsToFile(r){if(this.options.recordRRwebEventsToFile){r??(r=this.rrwebEventsBuffer);try{await lOn.default.appendFile(this.options.recordRRwebEventsToFilePath,r)}catch(a){Nv(a)}}}getRRwebFilePath(){return this.options.recordRRwebEventsToFilePath}};e(_Rr,"RuntimeTimeMachine");var EUt=_Rr;var hOn=Jp(require("path"));var mOn=!1,gRr=class gRr{constructor(t,r,a){this.frame=t;this.base=r;this.getAnalytics=a;this.LOCATORS_TIMEOUT=mOn?9999999:5e3;this.HANDLES_TIMEOUT=mOn?9999999:5e3;this.HANDLES_INTERVAL=300;this.locatorsChain=[];this.base||(this.base=this.frame)}setBase(t){this.base=t}setAnalytics(t){this.getAnalytics=t}init(...t){return this.sanitizeArgs(...t),new Proxy(this,{get:e((r,a)=>a==="setBase"?function(...o){this.setBase(o[0])}.bind(this):a==="setAnalytics"?function(...o){this.setAnalytics(o[0])}.bind(this):this.handleLocatorChain(r,a),"get")})}getLocatorSelector(t){if(t)return t._selector}sanitizeArgs(...t){if(t.length===1&&typeof t[0]=="object"){if(!t[0].anchors||typeof t[0].anchors!="function")throw new Error("Invalid compound selector format. Object must contain anchors property with a method value");this.anchorLocatorMethod=t[0].anchors,this.targetLocatorMethod=t[0].target;return}if(typeof t[0]!="function")throw new Error("Invalid compound selector format. First argument must be an object or a function");if(this.anchorLocatorMethod=t[0],t.length===2){if(typeof t[1]!="function")throw new Error("Invalid compound selector format. Second argument must be a function");this.targetLocatorMethod=t[1]}}async resolveLocator(){if(this.resolvedLocator)return this.resolvedLocator;Nv("Waiting for locators..");let t=this.getLocatorsFromMethods();if(t.find(_=>!("_selector"in _)))throw new Error("Can't resolve at least one locator, make sure anchors and target are valid locators or strings");try{await Promise.all(t.map(async _=>uD(_.first().waitFor({bypassChecksum:!0}),this.LOCATORS_TIMEOUT,"Waiting for compound selector locators timeout")))}catch(_){throw new Error(`Error while waiting for locators - ${_.message}`)}let r=await uD(this.getElementHandles(t),this.HANDLES_TIMEOUT);Nv(`Resolved to ${hRr(r)} elements from ${t.length} locators`);let a=this.getLocatorSelector(this.getLocatorsFromMethods(!1,!0,this.frame)[0]),o=await this.frame.evaluate(async({handles:_,targetSelector:b})=>window.checksum.testGenerator.getCompoundSelector().select(_,b),{handles:r,targetSelector:a});if(!o||o.length===0)throw new Error("Could not generate selectors from handles");Nv(`Resolved compound selector to ${o.length} selectors`);let c=this.getBase(),f=c.locator(o[0]);return o.slice(1,50).forEach(_=>{f=f.or(c.locator(_))}),this.locatorsChain.length&&this.locatorsChain.forEach(({name:_,args:b})=>{f=f[_](...b)}),Nv(`Compound locator selector: ${this.getLocatorSelector(f)}`),this.resolvedLocator=f,f}handleLocatorChain(t,r){if(typeof r=="symbol")return;if(r==="constructor")return e(function(...f){return this[r](...f)},"Locator");if(r==="toString")return()=>this.toString();let a=e(()=>new Proxy(t,{get:e((c,f)=>c.handleLocatorChain(c,f),"get")}),"createLocatorProxy");return r==="valueOf"?e(function(){return a()},"Locator"):r==="then"?(c,f)=>{this.resolveLocator().then(_=>c(_)).catch(f)}:Object.values([...Object.values(ime),...Object.values(NQe)]).includes(r)?e(function(...f){return t.locatorsChain.push({name:r,args:f}),a()},"Locator"):e(async function(...f){return this.handleAction(r,f)},"Locator").bind(this)}async handleAction(t,r){var a,o;try{if(typeof t=="symbol")return;if(!this.anchorLocatorMethod)throw new Error("Compound selection is missing anchor locators");let c=await this.resolveLocator();return this.frame.executeLocatorAction?await this.frame.executeLocatorAction(c,t,r):await c[t](...r)}catch(c){throw Nv(`Failed to execute compound selection action: ${c}`),(o=(a=this.getAnalytics)==null?void 0:a.call(this))==null||o.compoundSelectionFailure({error:c.toString(),selector:this.toString()}),c}}async getElementHandles(t){Nv("Resolving compound selector elements");let r,a,o,c,f,_=e(()=>{f=2},"resetSameHandlesCount");do r=a,a=[],await Promise.all(t.map(async b=>{let C=await b.elementHandles({bypassChecksum:!0});if(C.length===0)throw new Error(`No elements found for locator: ${this.getLocatorSelector(b)}`);a.push(C)})),o=hRr(a),c=r?hRr(r):0,Nv(`Handles itteration, previous: ${r?c:"-"}, current: ${o}`),c!==o&&_(),await Hx(this.HANDLES_INTERVAL);while(!r||c!==o||--f>0);return a}getLocatorsFromMethods(t=!0,r=!0,a=this.getBase()){return(t?this.anchorLocatorMethod(a):[]).concat(r&&this.targetLocatorMethod?[this.targetLocatorMethod(a)]:[]).map(o=>typeof o=="string"?a.getByText(o):o)}getBase(){return this.base}toString(){var t;return`CompoundSelection(${this.resolvedLocator?this.getLocatorSelector(this.resolvedLocator):`${this.anchorLocatorMethod.toString()}, ${(t=this.targetLocatorMethod)==null?void 0:t.toString()})`})`}};e(gRr,"CompoundSelectorLocator");var fze=gRr,hRr=e(i=>i.reduce((t,r)=>t+r.length,0),"countHandleElements");var yRr=require("path");var _On=require("fs");var rma=!0,vRr=class vRr{constructor(t){this.options=t;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async t=>{let r=vI(t);if(this.trackedFramesGuid.includes(r))return this.frameNavigationPromises[r]=new Promise(async a=>{await this.loadScript(t),a()}),this.frameNavigationPromises[r]},"onFrameNavigated");this.loadScript=e(async(t,{retriesLeft:r=3,retryWaitMS:a=2e3,useWrapper:o=!0}={})=>{var b,C;if(o&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(t,{retriesLeft:r,retryWaitMS:a,useWrapper:!1}),t);if(!this.addScriptTagOptions){this.log.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(t))return;let c=!1;try{c=this.scriptLoadCheck?await((b=this.scriptLoadCheck)==null?void 0:b.call(this,t)):!1}catch{}if(c||this.isFrameClosed(t))return;this.options.scriptAddWait&&(this.log.log(`Waiting ${this.options.scriptAddWait}[ms] before adding script...`),await Hx(this.options.scriptAddWait),this.log.log("Done waiting before adding script"));try{await t.addScriptTag(await this.makeInjectedScriptOptionsForAddScriptTag())}catch(w){if(r>0)return this.log.warn(`[InjectedScriptManager] Failed to add script to frame ${vI(t)}, trying again in ${a/1e3} seconds, ${r-1} retries left.`,w.message),await Hx(a),this.loadScript(t,{retriesLeft:r-1,retryWaitMS:a,useWrapper:o});throw w}let f=vI(t),_=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[f]=_,this.options.scriptInitWait&&(this.log.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await Hx(this.options.scriptInitWait),this.log.log("Done waiting before onScriptLoad")),!this.isFrameClosed(t)){if(this.navigatingFrames[f]&&this.navigatingFrames[f]!==_)return this.log.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[f];try{await((C=this.scriptLoadCallback)==null?void 0:C.call(this,t))}catch(w){this.log.error("[WebDriver] onScriptLoad error",w)}}},"loadScript");this.log=new Proxy(console,{get:e((t,r)=>(...a)=>{if(!this.options.silenceLogs)return t[r].apply(t,a)},"get")});this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(t){return this.scriptLoadCallback=t,this}setScriptLoadCheck(t){return this.scriptLoadCheck=t,this}setScriptLoadWrapper(t){return this.scriptLoadWrapper=t,this}async addTrackedFrame(t,r=!0){let a="mainFrame"in t?t.mainFrame():t,o=vI(a);if(this.trackedFramesGuid.includes(o)||this.trackedFramesGuid.push(o),r)return this.onFrameNavigated(a)}getNavigationPromise(t){if(!t){this.log.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let r=typeof t=="string"?t:"mainFrame"in t?vI(t.mainFrame()):vI(t);return this.frameNavigationPromises[r]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,yRr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}async makeInjectedScriptOptionsForAddScriptTag(){if(this.options.scriptSource==="url"&&this.addScriptTagOptions.url&&rma){let r=await(await fetch(this.addScriptTagOptions.url)).text(),a=(0,yRr.join)(process.cwd(),"checksumlib.js");return(0,_On.writeFileSync)(a,r),{path:a}}return this.addScriptTagOptions}isFrameClosed(t){return t.isDetached()||t.page().isClosed()}};e(vRr,"InjectedScriptManager");var dze=vRr;var ERr=class ERr{constructor(t){this.options=t}async handleError(t,r,a){let o=`Error in ${r} action during ${t} execution: ${a.message}`;throw new Error(o)}async guardedExecute(){try{return await(this.options.timeout!=null?uD(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(t){return this.handleError(this.options.method,this.constructor.name,t)}}};e(ERr,"Action");var CUt=ERr,CRr=class CRr extends CUt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(CRr,"PlaywrightAction");var bRr=CRr,wRr=class wRr extends CUt{constructor(r,a){super(r);this.pageInteractor=a}};e(wRr,"APIAction");var xRr=wRr,SRr=class SRr extends xRr{constructor(t,r){super(t,r.pageInteractor)}async execute(){try{let{locator:t,args:r}=this.options,[a,o]=r,c=await t.screenshot({timeout:3e4}),_=(await this.pageInteractor.getTextDetection(c)).getRectangleByTextAndSizeRanking(a,o);if(!_)throw new Error("No matching text found");await t.click({position:_.center})}catch(t){throw new Error(`Error in canvas click action: ${t.message}`)}}};e(SRr,"CanvasClickAction");var ARr=SRr,SUt=class SUt{static createAction(t,r){return t.method in this.customActionMap?new this.customActionMap[t.method]({...t,timeout:15e3},r):new bRr(t)}};e(SUt,"ActionFactory"),SUt.customActionMap={canvasClick:ARr};var wUt=SUt;var TUt=class TUt{constructor(t,r,a,o,c,f,_){this.frame=t;this.checksumPage=r;this.isReplMode=a;this.config=o;this.injectedScriptManager=c;this.getPageInteractor=f;this.onExecutionError=_;this.locatorStack=[];this.setFrameProxy(),this.checksumClient=new c$e({apiURL:this.config.apiURL,apiKey:this.config.apiKey})}static init(t,r,a,o,c,f,_=!1){return new TUt(t,r,_,f,a,o,c).proxy}setFrameProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.handleFrameMethod(a)},"get")})}handleFrameMethod(t){if(typeof t!="symbol")return typeof this[t]=="function"?t==="constructor"?this[t]:this[t].bind(this):[...Object.values(ime),...Object.values(NQe)].includes(t)?(this.pushToLocatorStack([{type:t,base:this.frame}]),e(function(a,o){try{return this.executeLocator(a,o)}catch(c){throw this.popLocatorChain(),c}},"Locator").bind(this)):this.frame[t]}page(){return this.checksumPage}compoundSelection(...t){var r;try{let a=this.locatorStack.length?(r=this.getCurrentLocatorInChain())==null?void 0:r.base:this.proxy;return new fze(this.proxy,a).init(...t)}catch{throw new Error("Failed generating compound selector")}}async wrapInternalSteps(t,r=this.frame){try{return r._checksumInternal=!0,await t()}finally{r._checksumInternal=!1}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.frame)}pushToLocatorStack(t){this.locatorStack.push(t)}getCurrentLocatorChain(){return this.locatorStack.length||this.locatorStack.push([]),this.locatorStack[this.locatorStack.length-1]}popLocatorChain(){return this.locatorStack.pop()}getCurrentLocatorInChain(){let t=this.getCurrentLocatorChain();return t==null?void 0:t[t.length-1]}getLocator(t,r){let a=this.getCurrentLocatorInChain();return a.base[a.type](t,r)}executeLocator(t,r){try{Nv(`
1838
- Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof t=="string"?`selector ${t}`:"locator"}`);try{t&&typeof t=="object"&&"has"in t&&this.popLocatorChain()}catch{}let a=this.getLocator(t,r);return new Proxy(a,{get:e((o,c)=>this.getLocatorMethod(a,o,c),"get")})}catch(a){Nv("Failed to locate",a)}}getLocatorMethod(t,r,a){return a==="then"?this.handleThen(t,r,a):a==="catch"?this.handleCatch(t,r):a==="finally"?this.handleFinally(t,r):a==="constructor"?e(function(...c){return this.popLocatorChain(),r.constructor(...c)},"Locator"):a in r&&typeof r[a]!="function"||a===Symbol.toPrimitive||a in Object||a==="evaluate"?(this.popLocatorChain(),r[a]):a==="compoundSelection"?function(...o){let c=this.compoundSelection(...o);return c.setBase(t),c}.bind(this):[...Object.values(ime),...Object.values(NQe)].includes(a)?["or","and"].includes(a)?(Nv("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),r[a]):(this.getCurrentLocatorChain().push({type:a,base:t}),e(function(...c){return this.executeLocator(c[0],c[1])},"Locator").bind(this)):a==="page"?()=>(this.popLocatorChain(),this.proxy.page()):e(async function(...c){let f=await this.executeLocatorAction(t,a,c);return this.popLocatorChain(),f},"Locator").bind(this)}async executeLocatorAction(t,r,a){if(a&&Array.from(a).some(_=>(_==null?void 0:_.bypassChecksum)===!0))return t[r](...a);let o=t._selector;Nv("Executing",r,o);let c=r==="_expect"?"assertion":"action";c==="action"&&this.lastLocatorActionType==="action"&&(Nv("Adding minimal wait between consecutive actions..."),await new Promise(_=>setTimeout(_,100))),this.lastLocatorActionType=c,Nv("Running initial locator...");let f;try{return this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{Nv("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{Nv("[executeLocatorAction] checksum libs not loaded")}}),await wUt.createAction({locator:t,method:r,args:a,timeout:this.getLocatorActionTimeout(c,r,a)},{api:this.checksumClient,pageInteractor:this.getPageInteractor()}).guardedExecute();f=new Error("Locator action error")}catch(_){Nv("Failed initial execution. Exception:",_.message),f=_}if(c==="action"&&this.onExecutionError)return this.onExecutionError({error:f,locator:t,method:r,args:a},this.frame);throw f}setExpectConfiguration(t=void 0){this.expectConfiguration=t}getLocatorActionTimeout(t,r,a=[]){var o;if(this.isReplMode)return null;try{if(t==="assertion"){let _=this.getAssertionTimeout(a);return Nv(`Assertion timeout set to ${_}`),_}let c=["fill","dragTo"].includes(r)?1:0,f=(o=a[c])==null?void 0:o.timeout;return isNaN(f)?3e4:f}catch{return 3e4}}getAssertionTimeout(t=[]){var o,c,f,_,b;let r=(o=t[1])==null?void 0:o.timeout;if(r!==void 0)return r;if(((c=this.expectConfiguration)==null?void 0:c.timeout)!==void 0)return(f=this.expectConfiguration)==null?void 0:f.timeout;let a=(b=(_=this.testInfo._projectInternal)==null?void 0:_.expect)==null?void 0:b.timeout;return a!==void 0?a:3e4}handleThen(t,r,a){return(o,c)=>Promise.resolve(t).then(f=>{let _=o?o(f):f;return _ instanceof Promise?_:this.getLocatorMethod(_,r,a)},f=>{if(c)return c(f);throw f})}handleCatch(t,r){return a=>Promise.resolve(t).catch(o=>{if(a)return a(o);throw o})}handleFinally(t,r){return a=>Promise.resolve(t).finally(a)}};e(TUt,"ChecksumFrame");var DUt=TUt;var kUt=class kUt{constructor(t,r,a,o,c){this.page=t;this.config=r;this.getPageInteractor=a;this.injectedScriptManager=o;this._frames={};this.isVTG=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;var f,_;this.setPageProxy(),this.injectedScriptManager||(this.injectedScriptManager=new dze({scriptFile:Xm.checksumScript.path,scriptSource:Xm.checksumScript.source,scriptURL:Xm.checksumScript.url,isScriptFileAbsolute:!0,silenceLogs:!Xm.isDevMode,scriptInitWait:(f=r==null?void 0:r.options)==null?void 0:f.browserScriptInitWait,scriptAddWait:(_=r==null?void 0:r.options)==null?void 0:_.browserScriptAddWait})),this.registerPageEvents(),this.page.frames().forEach(b=>this.registerFrame(b)),c&&(this.variableStore=c.variableStore)}static makePage(t,r,a){let o=IUt();return new kUt(t,o,()=>r,a).proxy}async registerFrame(t){var o;let r=this.getFrameGuid(t);if(t===this.page.mainFrame()&&(this.mainFrameGuid=r),this._frames[r])return;let a=DUt.init(t,this.proxy,this.injectedScriptManager,this.getPageInteractor,(o=this.onExecutionError)==null?void 0:o.bind(this),this.config);this._frames[r]=a}async onExecutionError(t){throw t.error}getFrameGuid(t){return t._guid}registerPageEvents(){this.page.on("frameattached",async t=>{this.registerFrame(t)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getPageMethod(a)},"get")})}getPageMethod(t){if(typeof this[t]=="function")return t==="constructor"?this[t]:this[t].bind(this);switch(t){case"pageInteractor":return this.getPageInteractor();case"variableStore":return this.variableStore}return Object.values(ime).includes(t)?e(function(a,o){try{return this.mainFrame()[t](a,o)}catch(c){throw c}},"Page").bind(this):this.page[t]}mainFrame(){var t;return(t=this._frames)==null?void 0:t[this.mainFrameGuid]}frames(){return Object.values(this._frames)}getFrame(t){if(!this.page.frames().find(a=>this.getFrameGuid(a)===t))throw new Error(`Frame with guid ${t} not found`);return this._frames[t]}async waitForDialog(t){try{return this.getPageInteractor().waitForDialog(!0,t)}catch(r){throw new Error(`Failed to handle native dialog: ${r}`)}}async reauthenticate(t){try{await this.getPageInteractor().reauthenticate(t,this.proxy)}catch(r){throw new Error(`Failed to reauthenticate: ${r}`)}}resolveAssetsFolder(t){return t.map(r=>hOn.join(Tpt(Ane()),r))}compoundSelection(...t){try{return new fze(this.mainFrame()).init(...t)}catch{throw new Error("Failed generating compound selector")}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}setExpectConfiguration(t=void 0){this.expectConfiguration=t,Object.values(this._frames).forEach(r=>r.setExpectConfiguration(t))}};e(kUt,"ChecksumPage");var mze=kUt;uqr();wI();var Jve=class Jve{constructor(){this.toolsMap={}}get addTool(){return this._addTool||(this._addTool=this.buildAddToolFacade()),this._addTool}getToolNames(){return Object.keys(this.toolRecord.names)}get tools(){return this.toolsMap}buildAddToolFacade(){let t={},r=this.toolRecord.tools;for(let a of Object.keys(r))t[a]=o=>this._addSingleTool(a,o);return t}static describeTool(t,r){if(t instanceof Th.ZodObject){let a={},o=t.shape;for(let c of Object.keys(o)){let f=o[c],_=r==null?void 0:r[c];typeof _=="string"?a[c]=f.describe(_):_&&typeof _=="object"?a[c]=Jve.describeTool(f,_):a[c]=f}return Th.object(a).strict()}if(t instanceof Th.ZodArray){let a=t.element;return r&&typeof r=="object"&&r.element?Th.array(Jve.describeTool(a,r.element)):t}return t instanceof Th.ZodOptional?Jve.describeTool(t.unwrap(),r).optional():t instanceof Th.ZodNullable?Jve.describeTool(t.unwrap(),r).nullable():typeof r=="string"?t.describe(r):t}_addSingleTool(t,r){let a=r.name??String(t),c=this.toolRecord.tools[t]._create({...r,name:a,params:r.params,handler:r.handler}),f=this.toolRecord.tools[t],_=Jve.describeTool(f,r.params),C=nqr(e(async w=>{let T=_.parse(w);return r.handler(T)},"validatedHandler"),{name:c.name,description:c.description,schema:_});return this.toolsMap[t]=C,C}_buildOne(t,r){return this._addSingleTool(t,{...r,name:String(t)})}static buildTool(t,r,a){let o=String(r),f=t.tools[r]._create({name:o,description:"",handler:a,params:{}}),_=t.tools[r],b=Jve.describeTool(_,{});return nqr(e(async T=>{let k=b.parse(T);return a(k)},"validatedHandler"),{name:f.name,description:f.description,schema:b})}};e(Jve,"AbstractToolContainer");var R4e=Jve;wI();var zQt=class zQt{constructor(t,r){this.version=t;let a={};for(let c in r)a[c]=c;this.names=a;let o={};for(let c in r){let f=r[c];Object.defineProperty(f,"name",{value:c,configurable:!1,enumerable:!0,writable:!1}),f._create=(_=>b=>{let C=b.name??_;return{...b,name:C}})(c),o[c]=f}this.tools=o}static create(t,r){return new zQt(t,r)}};e(zQt,"ToolProtocol");var VQt=zQt;var yj=VQt.create("v1",{readFile:Th.object({path:Th.string()}),getState:Th.object({thought:Th.string()}),invokeCode:Th.object({code:Th.string().refine(i=>{let t=i.trim();return t.includes("page.getByChecksumId(")||t.includes("page.getByChecksumId(")||t.startsWith("const ")||t.startsWith("let ")||t.startsWith("var ")||t.includes("=")||t.includes("variableStore.")},{message:"Code should use page.getByChecksumId() for element targeting, or be explicit variable assignments/function calls"}),thought:Th.string()}),wait:Th.object({time:Th.number().optional()}),scroll:Th.object({checksumId:Th.string(),thought:Th.string()}),final_result:Th.object({result:Th.enum(["pass","fail"]),thought:Th.string(),visualAnalysis:Th.string().optional()}),getElementScreenshot:Th.object({checksumId:Th.string(),thought:Th.string()}),analyze:Th.object({previousImmediateSteps:Th.string(),currentFailingStep:Th.string(),nextImmediateSteps:Th.string(),testStepToStopAt:Th.string()}),think:Th.object({thought:Th.string()})});var Cqr=Jp(eqn(),1);var Dce=Object.create(null);Dce.open="0";Dce.close="1";Dce.ping="2";Dce.pong="3";Dce.message="4";Dce.upgrade="5";Dce.noop="6";var pmt=Object.create(null);Object.keys(Dce).forEach(i=>{pmt[Dce[i]]=i});var fmt={type:"error",data:"parser error"};var dmt=e(({type:i,data:t},r,a)=>t instanceof ArrayBuffer||ArrayBuffer.isView(t)?a(r?t:"b"+tqn(t,!0).toString("base64")):a(Dce[i]+(t||"")),"encodePacket"),tqn=e((i,t)=>Buffer.isBuffer(i)||i instanceof Uint8Array&&!t?i:i instanceof ArrayBuffer?Buffer.from(i):Buffer.from(i.buffer,i.byteOffset,i.byteLength),"toBuffer"),lqr;function rqn(i,t){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return t(tqn(i.data,!1));dmt(i,!0,r=>{lqr||(lqr=new TextEncoder),t(lqr.encode(r))})}e(rqn,"encodePacketToBinary");var mmt=e((i,t)=>{if(typeof i!="string")return{type:"message",data:nqn(i,t)};let r=i.charAt(0);if(r==="b"){let a=Buffer.from(i.substring(1),"base64");return{type:"message",data:nqn(a,t)}}return pmt[r]?i.length>1?{type:pmt[r],data:i.substring(1)}:{type:pmt[r]}:fmt},"decodePacket"),nqn=e((i,t)=>{switch(t){case"arraybuffer":return i instanceof ArrayBuffer?i:Buffer.isBuffer(i)?i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength):i.buffer;case"nodebuffer":default:return Buffer.isBuffer(i)?i:Buffer.from(i)}},"mapBinary");var iqn="",aqn=e((i,t)=>{let r=i.length,a=new Array(r),o=0;i.forEach((c,f)=>{dmt(c,!1,_=>{a[f]=_,++o===r&&t(a.join(iqn))})})},"encodePayload"),sqn=e((i,t)=>{let r=i.split(iqn),a=[];for(let o=0;o<r.length;o++){let c=mmt(r[o],t);if(a.push(c),c.type==="error")break}return a},"decodePayload");function oqn(){return new TransformStream({transform(i,t){rqn(i,r=>{let a=r.length,o;if(a<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,a);else if(a<65536){o=new Uint8Array(3);let c=new DataView(o.buffer);c.setUint8(0,126),c.setUint16(1,a)}else{o=new Uint8Array(9);let c=new DataView(o.buffer);c.setUint8(0,127),c.setBigUint64(1,BigInt(a))}i.data&&typeof i.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}e(oqn,"createPacketEncoderStream");var pqr;function JQt(i){return i.reduce((t,r)=>t+r.length,0)}e(JQt,"totalLength");function HQt(i,t){if(i[0].length===t)return i.shift();let r=new Uint8Array(t),a=0;for(let o=0;o<t;o++)r[o]=i[0][a++],a===i[0].length&&(i.shift(),a=0);return i.length&&a<i[0].length&&(i[0]=i[0].slice(a)),r}e(HQt,"concatChunks");function uqn(i,t){pqr||(pqr=new TextDecoder);let r=[],a=0,o=-1,c=!1;return new TransformStream({transform(f,_){for(r.push(f);;){if(a===0){if(JQt(r)<1)break;let b=HQt(r,1);c=(b[0]&128)===128,o=b[0]&127,o<126?a=3:o===126?a=1:a=2}else if(a===1){if(JQt(r)<2)break;let b=HQt(r,2);o=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(JQt(r)<8)break;let b=HQt(r,8),C=new DataView(b.buffer,b.byteOffset,b.length),w=C.getUint32(0);if(w>Math.pow(2,21)-1){_.enqueue(fmt);break}o=w*Math.pow(2,32)+C.getUint32(4),a=3}else{if(JQt(r)<o)break;let b=HQt(r,o);_.enqueue(mmt(c?b:pqr.decode(b),t)),a=0}if(o===0||o>i){_.enqueue(fmt);break}}}})}e(uqn,"createPacketDecoderStream");var fqr=4;var Cqn=Jp(SPe(),1);var Hve=process.nextTick,Ez=global,lqn="nodebuffer";function pqn(){return new dqr}e(pqn,"createCookieJar");function mva(i){let t=i.split("; "),r=t[0].indexOf("=");if(r===-1)return;let a=t[0].substring(0,r).trim();if(!a.length)return;let o=t[0].substring(r+1).trim();o.charCodeAt(0)===34&&(o=o.slice(1,-1));let c={name:a,value:o};for(let f=1;f<t.length;f++){let _=t[f].split("=");if(_.length!==2)continue;let b=_[0].trim(),C=_[1].trim();switch(b){case"Expires":c.expires=new Date(C);break;case"Max-Age":let w=new Date;w.setUTCSeconds(w.getUTCSeconds()+parseInt(C,10)),c.expires=w;break;default:}}return c}e(mva,"parse");var mqr=class mqr{constructor(){this._cookies=new Map}parseCookies(t){t&&t.forEach(r=>{let a=mva(r);a&&this._cookies.set(a.name,a)})}get cookies(){let t=Date.now();return this._cookies.forEach((r,a)=>{var o;((o=r.expires)===null||o===void 0?void 0:o.getTime())<t&&this._cookies.delete(a)}),this._cookies.entries()}addCookies(t){let r=[];for(let[a,o]of this.cookies)r.push(`${a}=${o.value}`);r.length&&(t.setDisableHeaderCheck(!0),t.setRequestHeader("cookie",r.join("; ")))}appendCookies(t){for(let[r,a]of this.cookies)t.append("cookie",`${r}=${a.value}`)}};e(mqr,"CookieJar");var dqr=mqr;function WQt(i,...t){return t.reduce((r,a)=>(i.hasOwnProperty(a)&&(r[a]=i[a]),r),{})}e(WQt,"pick");var _va=Ez.setTimeout,hva=Ez.clearTimeout;function Wve(i,t){t.useNativeTimers?(i.setTimeoutFn=_va.bind(Ez),i.clearTimeoutFn=hva.bind(Ez)):(i.setTimeoutFn=Ez.setTimeout.bind(Ez),i.clearTimeoutFn=Ez.clearTimeout.bind(Ez))}e(Wve,"installTimerFunctions");var gva=1.33;function fqn(i){return typeof i=="string"?yva(i):Math.ceil((i.byteLength||i.size)*gva)}e(fqn,"byteLength");function yva(i){let t=0,r=0;for(let a=0,o=i.length;a<o;a++)t=i.charCodeAt(a),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(a++,r+=4);return r}e(yva,"utf8Length");function GQt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}e(GQt,"randomString");function dqn(i){let t="";for(let r in i)i.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(i[r]));return t}e(dqn,"encode");function mqn(i){let t={},r=i.split("&");for(let a=0,o=r.length;a<o;a++){let c=r[a].split("=");t[decodeURIComponent(c[0])]=decodeURIComponent(c[1])}return t}e(mqn,"decode");var wqn=Jp(kPe(),1);var qva=(0,wqn.default)("engine.io-client:transport"),vqr=class vqr extends Error{constructor(t,r,a){super(t),this.description=r,this.context=a,this.type="TransportError"}};e(vqr,"TransportError");var e$t=vqr,bqr=class bqr extends Cqn.Emitter{constructor(t){super(),this.writable=!1,Wve(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,a){return super.emitReserved("error",new e$t(t,r,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"?this.write(t):qva("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){let r=mmt(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){let t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){let r=dqn(t);return r.length?"?"+r:""}};e(bqr,"Transport");var Gve=bqr;var Sqn=Jp(kPe(),1);var Tce=(0,Sqn.default)("engine.io-client:polling"),xqr=class xqr extends Gve{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";let r=e(()=>{Tce("paused"),this.readyState="paused",t()},"pause");if(this._polling||!this.writable){let a=0;this._polling&&(Tce("we are currently polling - waiting to pause"),a++,this.once("pollComplete",function(){Tce("pre-pause polling complete"),--a||r()})),this.writable||(Tce("we are currently writing - waiting to pause"),a++,this.once("drain",function(){Tce("pre-pause writing complete"),--a||r()}))}else r()}_poll(){Tce("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){Tce("polling got data %s",t);let r=e(a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)},"callback");sqn(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Tce('ignoring poll - transport state "%s"',this.readyState))}doClose(){let t=e(()=>{Tce("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(Tce("transport open - closing"),t()):(Tce("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,aqn(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=GQt()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}};e(xqr,"Polling");var hmt=xqr;var Iqn=Jp(SPe(),1);var Dqn=!1;try{Dqn=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Tqn=Dqn;var Pqn=Jp(kPe(),1);var Aqr=(0,Pqn.default)("engine.io-client:polling");function Qva(){}e(Qva,"empty");var Eqr=class Eqr extends hmt{constructor(t){if(super(t),typeof location<"u"){let r=location.protocol==="https:",a=location.port;a||(a=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||a!==t.port}}doWrite(t,r){let a=this.request({method:"POST",data:t});a.on("success",r),a.on("error",(o,c)=>{this.onError("xhr post error",o,c)})}doPoll(){Aqr("xhr poll");let t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,a)=>{this.onError("xhr poll error",r,a)}),this.pollXhr=t}};e(Eqr,"BaseXHR");var t$t=Eqr,sJe=class sJe extends Iqn.Emitter{constructor(t,r,a){super(),this.createRequest=t,Wve(this,a),this._opts=a,this._method=a.method||"GET",this._uri=r,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var t;let r=WQt(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let a=this._xhr=this.createRequest(r);try{Aqr("xhr open %s: %s",this._method,this._uri),a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let o in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(o)&&a.setRequestHeader(o,this._opts.extraHeaders[o])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var o;a.readyState===3&&((o=this._opts.cookieJar)===null||o===void 0||o.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},Aqr("xhr data %s",this._data),a.send(this._data)}catch(o){this.setTimeoutFn(()=>{this._onError(o)},0);return}typeof document<"u"&&(this._index=sJe.requestsCount++,sJe.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Qva,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete sJe.requests[this._index],this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};e(sJe,"Request");var Kve=sJe;Kve.requestsCount=0;Kve.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",kqn);else if(typeof addEventListener=="function"){let i="onpagehide"in Ez?"pagehide":"unload";addEventListener(i,kqn,!1)}}function kqn(){for(let i in Kve.requests)Kve.requests.hasOwnProperty(i)&&Kve.requests[i].abort()}e(kqn,"unloadHandler");var J3s=function(){let i=$va({xdomain:!1});return i&&i.responseType!==null}();function $va(i){let t=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Tqn))return new XMLHttpRequest}catch{}if(!t)try{return new Ez[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}e($va,"newRequest");var Vva=Cqr.default||Cqr,wqr=class wqr extends t$t{request(t={}){var r;return Object.assign(t,{xd:this.xd,cookieJar:(r=this.socket)===null||r===void 0?void 0:r._cookieJar},this.opts),new Kve(a=>new Vva(a),this.uri(),t)}};e(wqr,"XHR");var oJe=wqr;var exa=Jp(Bqn(),1),txa=Jp(jqr(),1),rxa=Jp(qqr(),1),tQr=Jp(Xqr(),1),nxa=Jp(FQn(),1);var NQn=Jp(kPe(),1);var axa=(0,NQn.default)("engine.io-client:websocket"),sxa=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",rQr=class rQr extends Gve{get name(){return"websocket"}doOpen(){let t=this.uri(),r=this.opts.protocols,a=sxa?{}:WQt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,a)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;dmt(a,this.supportsBinary,c=>{try{this.doWrite(a,c)}catch{axa("websocket closed before onclose event")}o&&Hve(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=GQt()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}};e(rQr,"BaseWS");var _$t=rQr,F8s=Ez.WebSocket||Ez.MozWebSocket;var nQr=class nQr extends _$t{createSocket(t,r,a){var o;if(!((o=this.socket)===null||o===void 0)&&o._cookieJar){a.headers=a.headers||{},a.headers.cookie=typeof a.headers.cookie=="string"?[a.headers.cookie]:a.headers.cookie||[];for(let[c,f]of this.socket._cookieJar.cookies)a.headers.cookie.push(`${c}=${f.value}`)}return new tQr.default(t,r,a)}doWrite(t,r){let a={};t.options&&(a.compress=t.options.compress),this.opts.perMessageDeflate&&(typeof r=="string"?Buffer.byteLength(r):r.length)<this.opts.perMessageDeflate.threshold&&(a.compress=!1),this.ws.send(r,a)}};e(nQr,"WS");var fJe=nQr;var OQn=Jp(kPe(),1);var Dmt=(0,OQn.default)("engine.io-client:webtransport"),iQr=class iQr extends Gve{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{Dmt("transport closed gracefully"),this.onClose()}).catch(t=>{Dmt("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{let r=uqn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=t.readable.pipeThrough(r).getReader(),o=oqn();o.readable.pipeTo(t.writable),this._writer=o.writable.getWriter();let c=e(()=>{a.read().then(({done:_,value:b})=>{if(_){Dmt("session is closed");return}Dmt("received chunk: %o",b),this.onPacket(b),c()}).catch(_=>{Dmt("an error occurred while reading: %s",_)})},"read");c();let f={type:"open"};this.query.sid&&(f.data=`{"sid":"${this.query.sid}"}`),this._writer.write(f).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;this._writer.write(a).then(()=>{o&&Hve(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}};e(iQr,"WT");var dJe=iQr;var aQr={websocket:fJe,webtransport:dJe,polling:oJe};var oxa=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,uxa=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mJe(i){if(i.length>8e3)throw"URI too long";let t=i,r=i.indexOf("["),a=i.indexOf("]");r!=-1&&a!=-1&&(i=i.substring(0,r)+i.substring(r,a).replace(/:/g,";")+i.substring(a,i.length));let o=oxa.exec(i||""),c={},f=14;for(;f--;)c[uxa[f]]=o[f]||"";return r!=-1&&a!=-1&&(c.source=t,c.host=c.host.substring(1,c.host.length-1).replace(/;/g,":"),c.authority=c.authority.replace("[","").replace("]","").replace(/;/g,":"),c.ipv6uri=!0),c.pathNames=cxa(c,c.path),c.queryKey=lxa(c,c.query),c}e(mJe,"parse");function cxa(i,t){let r=/\/{2,9}/g,a=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&a.splice(0,1),t.slice(-1)=="/"&&a.splice(a.length-1,1),a}e(cxa,"pathNames");function lxa(i,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,o,c){o&&(r[o]=c)}),r}e(lxa,"queryKey");var BQn=Jp(SPe(),1);var RQn=Jp(kPe(),1);var A7=(0,RQn.default)("engine.io-client:socket"),sQr=typeof addEventListener=="function"&&typeof removeEventListener=="function",Tmt=[];sQr&&addEventListener("offline",()=>{A7("closing %d connection(s) because the network was lost",Tmt.length),Tmt.forEach(i=>i())},!1);var _Je=class _Je extends BQn.Emitter{constructor(t,r){if(super(),this.binaryType=lqn,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let a=mJe(t);r.hostname=a.host,r.secure=a.protocol==="https"||a.protocol==="wss",r.port=a.port,a.query&&(r.query=a.query)}else r.host&&(r.hostname=mJe(r.host).host);Wve(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(a=>{let o=a.prototype.name;this.transports.push(o),this._transportsByName[o]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=mqn(this.opts.query)),sQr&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(A7("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Tmt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=pqn()),this._open()}createTransport(t){A7('creating transport "%s"',t);let r=Object.assign({},this.opts.query);r.EIO=fqr,r.transport=t,this.id&&(r.sid=this.id);let a=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return A7("options: %j",a),new this._transportsByName[t](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&_Je.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){A7("setting transport %s",t.name),this.transport&&(A7("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){A7("socket open"),this.readyState="open",_Je.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(A7('socket receive: type "%s", data "%s"',t.type,t.data),this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}else A7('packet received with socket readyState "%s"',this.readyState)}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();A7("flushing %d packets in socket",t.length),this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let a=0;a<this.writeBuffer.length;a++){let o=this.writeBuffer[a].data;if(o&&(r+=fqn(o)),a>0&&r>this._maxPayload)return A7("only send %d out of %d packets",a,this.writeBuffer.length),this.writeBuffer.slice(0,a);r+=2}return A7("payload size is %d (max: %d)",r,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(A7("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,Hve(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,a){return this._sendPacket("message",t,r,a),this}send(t,r,a){return this._sendPacket("message",t,r,a),this}_sendPacket(t,r,a,o){if(typeof r=="function"&&(o=r,r=void 0),typeof a=="function"&&(o=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;let c={type:t,data:r,options:a};this.emitReserved("packetCreate",c),this.writeBuffer.push(c),o&&this.once("flush",o),this.flush()}close(){let t=e(()=>{this._onClose("forced close"),A7("socket closing - telling transport to close"),this.transport.close()},"close"),r=e(()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},"cleanupAndClose"),a=e(()=>{this.once("upgrade",r),this.once("upgradeError",r)},"waitForUpgrade");return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():t()}):this.upgrading?a():t()),this}_onError(t){if(A7("socket error %j",t),_Je.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return A7("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(A7('socket close with reason: "%s"',t),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),sQr&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let a=Tmt.indexOf(this._offlineEventListener);a!==-1&&(A7("removing listener for the 'offline' event"),Tmt.splice(a,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};e(_Je,"SocketWithoutUpgrade");var OPe=_Je;OPe.protocol=fqr;var oQr=class oQr extends OPe{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){A7("starting upgrade probes");for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}}_probe(t){A7('probing transport "%s"',t);let r=this.createTransport(t),a=!1;OPe.priorWebsocketSuccess=!1;let o=e(()=>{a||(A7('probe transport "%s" opened',t),r.send([{type:"ping",data:"probe"}]),r.once("packet",T=>{if(!a)if(T.type==="pong"&&T.data==="probe"){if(A7('probe transport "%s" pong',t),this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;OPe.priorWebsocketSuccess=r.name==="websocket",A7('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{a||this.readyState!=="closed"&&(A7("changing transport and sending upgrade packet"),w(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{A7('probe transport "%s" failed',t);let k=new Error("probe error");k.transport=r.name,this.emitReserved("upgradeError",k)}}))},"onTransportOpen");function c(){a||(a=!0,w(),r.close(),r=null)}e(c,"freezeTransport");let f=e(T=>{let k=new Error("probe error: "+T);k.transport=r.name,c(),A7('probe transport "%s" failed because of error: %s',t,T),this.emitReserved("upgradeError",k)},"onerror");function _(){f("transport closed")}e(_,"onTransportClose");function b(){f("socket closed")}e(b,"onclose");function C(T){r&&T.name!==r.name&&(A7('"%s" works - aborting "%s"',T.name,r.name),c())}e(C,"onupgrade");let w=e(()=>{r.removeListener("open",o),r.removeListener("error",f),r.removeListener("close",_),this.off("close",b),this.off("upgrading",C)},"cleanup");r.once("open",o),r.once("error",f),r.once("close",_),this.once("close",b),this.once("upgrading",C),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{a||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){let r=[];for(let a=0;a<t.length;a++)~this.transports.indexOf(t[a])&&r.push(t[a]);return r}};e(oQr,"SocketWithUpgrade");var h$t=oQr,uQr=class uQr extends h$t{constructor(t,r={}){let a=typeof t=="object"?t:r;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(o=>aQr[o]).filter(o=>!!o)),super(t,a)}};e(uQr,"Socket");var hJe=uQr;var oTs=hJe.protocol;var QQn=Jp(kmt(),1);var qQn=(0,QQn.default)("socket.io-client:url");function $Qn(i,t="",r){let a=i;r=r||typeof location<"u"&&location,i==null&&(i=r.protocol+"//"+r.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=r.protocol+i:i=r.host+i),/^(https?|wss?):\/\//.test(i)||(qQn("protocol-less url %s",i),typeof r<"u"?i=r.protocol+"//"+i:i="https://"+i),qQn("parse %s",i),a=mJe(i)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";let c=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+c+":"+a.port+t,a.href=a.protocol+"://"+c+(r&&r.port===a.port?"":":"+a.port),a}e($Qn,"url");var vQr={};rj(vQr,{Decoder:()=>gQr,Encoder:()=>hQr,PacketType:()=>FE,protocol:()=>t$n});var ZQn=Jp(SPe(),1);var kxa=typeof ArrayBuffer=="function",Ixa=e(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),VQn=Object.prototype.toString,Pxa=typeof Blob=="function"||typeof Blob<"u"&&VQn.call(Blob)==="[object BlobConstructor]",Fxa=typeof File=="function"||typeof File<"u"&&VQn.call(File)==="[object FileConstructor]";function Pmt(i){return kxa&&(i instanceof ArrayBuffer||Ixa(i))||Pxa&&i instanceof Blob||Fxa&&i instanceof File}e(Pmt,"isBinary");function Imt(i,t){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let r=0,a=i.length;r<a;r++)if(Imt(i[r]))return!0;return!1}if(Pmt(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return Imt(i.toJSON(),!0);for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)&&Imt(i[r]))return!0;return!1}e(Imt,"hasBinary");function zQn(i){let t=[],r=i.data,a=i;return a.data=pQr(r,t),a.attachments=t.length,{packet:a,buffers:t}}e(zQn,"deconstructPacket");function pQr(i,t){if(!i)return i;if(Pmt(i)){let r={_placeholder:!0,num:t.length};return t.push(i),r}else if(Array.isArray(i)){let r=new Array(i.length);for(let a=0;a<i.length;a++)r[a]=pQr(i[a],t);return r}else if(typeof i=="object"&&!(i instanceof Date)){let r={};for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&(r[a]=pQr(i[a],t));return r}return i}e(pQr,"_deconstructPacket");function JQn(i,t){return i.data=fQr(i.data,t),delete i.attachments,i}e(JQn,"reconstructPacket");function fQr(i,t){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<t.length)return t[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let r=0;r<i.length;r++)i[r]=fQr(i[r],t);else if(typeof i=="object")for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(i[r]=fQr(i[r],t));return i}e(fQr,"_reconstructPacket");var e$n=Jp(YQn(),1);var _Qr=(0,e$n.default)("socket.io-parser"),Wxa=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],t$n=5,FE;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(FE||(FE={}));var bQr=class bQr{constructor(t){this.replacer=t}encode(t){return _Qr("encoding packet %j",t),(t.type===FE.EVENT||t.type===FE.ACK)&&Imt(t)?this.encodeAsBinary({type:t.type===FE.EVENT?FE.BINARY_EVENT:FE.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let r=""+t.type;return(t.type===FE.BINARY_EVENT||t.type===FE.BINARY_ACK)&&(r+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(r+=t.nsp+","),t.id!=null&&(r+=t.id),t.data!=null&&(r+=JSON.stringify(t.data,this.replacer)),_Qr("encoded %j as %s",t,r),r}encodeAsBinary(t){let r=zQn(t),a=this.encodeAsString(r.packet),o=r.buffers;return o.unshift(a),o}};e(bQr,"Encoder");var hQr=bQr;function XQn(i){return Object.prototype.toString.call(i)==="[object Object]"}e(XQn,"isObject");var E$t=class E$t extends ZQn.Emitter{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let a=r.type===FE.BINARY_EVENT;a||r.type===FE.BINARY_ACK?(r.type=a?FE.EVENT:FE.ACK,this.reconstructor=new yQr(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(Pmt(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,a={type:Number(t.charAt(0))};if(FE[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===FE.BINARY_EVENT||a.type===FE.BINARY_ACK){let c=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let f=t.substring(c,r);if(f!=Number(f)||t.charAt(r)!=="-")throw new Error("Illegal attachments");a.attachments=Number(f)}if(t.charAt(r+1)==="/"){let c=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););a.nsp=t.substring(c,r)}else a.nsp="/";let o=t.charAt(r+1);if(o!==""&&Number(o)==o){let c=r+1;for(;++r;){let f=t.charAt(r);if(f==null||Number(f)!=f){--r;break}if(r===t.length)break}a.id=Number(t.substring(c,r+1))}if(t.charAt(++r)){let c=this.tryParse(t.substr(r));if(E$t.isPayloadValid(a.type,c))a.data=c;else throw new Error("invalid payload")}return _Qr("decoded %s as %j",t,a),a}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case FE.CONNECT:return XQn(r);case FE.DISCONNECT:return r===void 0;case FE.CONNECT_ERROR:return typeof r=="string"||XQn(r);case FE.EVENT:case FE.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&Wxa.indexOf(r[0])===-1);case FE.ACK:case FE.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};e(E$t,"Decoder");var gQr=E$t,xQr=class xQr{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){let r=JQn(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};e(xQr,"BinaryReconstructor");var yQr=xQr;function gZ(i,t,r){return i.on(t,r),e(function(){i.off(t,r)},"subDestroy")}e(gZ,"on");var r$n=Jp(SPe(),1),n$n=Jp(kmt(),1);var rO=(0,n$n.default)("socket.io-client:socket"),Gxa=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),AQr=class AQr extends r$n.Emitter{constructor(t,r,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=r,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let t=this.io;this.subs=[gZ(t,"open",this.onopen.bind(this)),gZ(t,"packet",this.onpacket.bind(this)),gZ(t,"error",this.onerror.bind(this)),gZ(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var a,o,c;if(Gxa.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;let f={type:FE.EVENT,data:r};if(f.options={},f.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){let w=this.ids++;rO("emitting packet with ack id %d",w);let T=r.pop();this._registerAckCallback(w,T),f.id=w}let _=(o=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||o===void 0?void 0:o.writable,b=this.connected&&!(!((c=this.io.engine)===null||c===void 0)&&c._hasPingExpired());return this.flags.volatile&&!_?rO("discard packet as the transport is not currently writable"):b?(this.notifyOutgoingListeners(f),this.packet(f)):this.sendBuffer.push(f),this.flags={},this}_registerAckCallback(t,r){var a;let o=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(o===void 0){this.acks[t]=r;return}let c=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let _=0;_<this.sendBuffer.length;_++)this.sendBuffer[_].id===t&&(rO("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(_,1));rO("event with ack id %d has timed out after %d ms",t,o),r.call(this,new Error("operation has timed out"))},o),f=e((..._)=>{this.io.clearTimeoutFn(c),r.apply(this,_)},"fn");f.withError=!0,this.acks[t]=f}emitWithAck(t,...r){return new Promise((a,o)=>{let c=e((f,_)=>f?o(f):a(_),"fn");c.withError=!0,r.push(c),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());let a={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...c)=>a!==this._queue[0]?void 0:(o!==null?a.tryCount>this._opts.retries&&(rO("packet [%d] is discarded after %d tries",a.id,a.tryCount),this._queue.shift(),r&&r(o)):(rO("packet [%d] was successfully sent",a.id),this._queue.shift(),r&&r(null,...c)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(t=!1){if(rO("draining queue"),!this.connected||this._queue.length===0)return;let r=this._queue[0];if(r.pending&&!t){rO("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,rO("sending packet [%d] (try n\xB0%d)",r.id,r.tryCount),this.flags=r.flags,this.emit.apply(this,r.args)}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){rO("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:FE.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){rO("close (%s)",t),this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(a=>String(a.id)===t)){let a=this.acks[t];delete this.acks[t],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case FE.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case FE.EVENT:case FE.BINARY_EVENT:this.onevent(t);break;case FE.ACK:case FE.BINARY_ACK:this.onack(t);break;case FE.DISCONNECT:this.ondisconnect();break;case FE.CONNECT_ERROR:this.destroy();let a=new Error(t.data.message);a.data=t.data.data,this.emitReserved("connect_error",a);break}}onevent(t){let r=t.data||[];rO("emitting event %j",r),t.id!=null&&(rO("attaching ack callback to event"),r.push(this.ack(t.id))),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){let r=this._anyListeners.slice();for(let a of r)a.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){let r=this,a=!1;return function(...o){a||(a=!0,rO("sending ack %j",o),r.packet({type:FE.ACK,id:t,data:o}))}}onack(t){let r=this.acks[t.id];if(typeof r!="function"){rO("bad ack %s",t.id);return}delete this.acks[t.id],rO("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){rO("socket connected with id %s",t),this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){rO("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(rO("performing disconnect (%s)",this.nsp),this.packet({type:FE.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){let r=this._anyListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){let r=this._anyOutgoingListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let r=this._anyOutgoingListeners.slice();for(let a of r)a.apply(this,t.data)}}};e(AQr,"Socket");var gJe=AQr;function BPe(i){i=i||{},this.ms=i.min||100,this.max=i.max||1e4,this.factor=i.factor||2,this.jitter=i.jitter>0&&i.jitter<=1?i.jitter:0,this.attempts=0}e(BPe,"Backoff");BPe.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*i);i=Math.floor(t*10)&1?i+r:i-r}return Math.min(i,this.max)|0};BPe.prototype.reset=function(){this.attempts=0};BPe.prototype.setMin=function(i){this.ms=i};BPe.prototype.setMax=function(i){this.max=i};BPe.prototype.setJitter=function(i){this.jitter=i};var i$n=Jp(SPe(),1),a$n=Jp(kmt(),1);var vj=(0,a$n.default)("socket.io-client:manager"),EQr=class EQr extends i$n.Emitter{constructor(t,r){var a;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,Wve(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((a=r.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new BPe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;let o=r.parser||vQr;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(vj("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;vj("opening %s",this.uri),this.engine=new hJe(this.uri,this.opts);let r=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;let o=gZ(r,"open",function(){a.onopen(),t&&t()}),c=e(_=>{vj("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",_),t?t(_):this.maybeReconnectOnOpen()},"onError"),f=gZ(r,"error",c);if(this._timeout!==!1){let _=this._timeout;vj("connect attempt will timeout after %d",_);let b=this.setTimeoutFn(()=>{vj("connect attempt timed out after %d",_),o(),c(new Error("timeout")),r.close()},_);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(o),this.subs.push(f),this}connect(t){return this.open(t)}onopen(){vj("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let t=this.engine;this.subs.push(gZ(t,"ping",this.onping.bind(this)),gZ(t,"data",this.ondata.bind(this)),gZ(t,"error",this.onerror.bind(this)),gZ(t,"close",this.onclose.bind(this)),gZ(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){Hve(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){vj("error",t),this.emitReserved("error",t)}socket(t,r){let a=this.nsps[t];return a?this._autoConnect&&!a.active&&a.connect():(a=new gJe(this,t,r),this.nsps[t]=a),a}_destroy(t){let r=Object.keys(this.nsps);for(let a of r)if(this.nsps[a].active){vj("socket %s is still active, skipping close",a);return}this._close()}_packet(t){vj("writing packet %j",t);let r=this.encoder.encode(t);for(let a=0;a<r.length;a++)this.engine.write(r[a],t.options)}cleanup(){vj("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){vj("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var a;vj("closed due to %s",t),this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let t=this;if(this.backoff.attempts>=this._reconnectionAttempts)vj("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let r=this.backoff.duration();vj("will wait %dms before reconnect attempt",r),this._reconnecting=!0;let a=this.setTimeoutFn(()=>{t.skipReconnect||(vj("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(vj("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):(vj("reconnect success"),t.onreconnect())}))},r);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){let t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}};e(EQr,"Manager");var yJe=EQr;var o$n=Jp(kmt(),1);var s$n=(0,o$n.default)("socket.io-client"),Fmt={};function Nmt(i,t){typeof i=="object"&&(t=i,i=void 0),t=t||{};let r=$Qn(i,t.path||"/socket.io"),a=r.source,o=r.id,c=r.path,f=Fmt[o]&&c in Fmt[o].nsps,_=t.forceNew||t["force new connection"]||t.multiplex===!1||f,b;return _?(s$n("ignoring socket cache for %s",a),b=new yJe(a,t)):(Fmt[o]||(s$n("new io instance for %s",a),Fmt[o]=new yJe(a,t)),b=Fmt[o]),r.query&&!t.query&&(t.query=r.queryKey),b.socket(r.path,t)}e(Nmt,"lookup");Object.assign(Nmt,{Manager:yJe,Socket:gJe,io:Nmt,connect:Nmt});var C$t={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},CQr=class CQr{constructor(t={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=t,this.url=t.url||C$t.URL,this.namespace=t.namespace||C$t.NAMESPACE,this.initializationPromise=this.createInitializationPromise()}createInitializationPromise(){return new Promise((t,r)=>{this.resolveInitialization=a=>t(a),this.rejectInitialization=a=>r(a)}).then(t=>(this.resolution=t,this.log("\u2705 Client initialization successful"),t),t=>{throw this.resolution=t,this.logError("\u274C Client initialization failed:",t),t}).finally(()=>{this.disconnect()})}defineHandlers(t){return t}async startSession(t,r){try{return await this.connect(),this.emit(t,r,a=>{this.resolveInitialization(a)}),this.initializationPromise}catch(a){throw this.logError("\u274C Failed to start session:",a),this.rejectInitialization(a),a}}isConnected(){var t;return((t=this.socket)==null?void 0:t.connected)||!1}getConnectionState(){return this.connectionState}success(t){return{success:!0,data:t}}error(t){return{success:!1,error:t}}log(t,...r){this.options.verbose&&console.log(`[${this.namespace}] ${t}`,...r)}logError(t,...r){this.options.verbose&&console.error(`[${this.namespace}] ${t}`,...r)}async connect(){var t;if(this.connectionPromise)return this.connectionPromise;if(this.connectionState==="connected"&&((t=this.socket)!=null&&t.connected))return Promise.resolve();this.connectionState="connecting",this.connectionPromise=this.establishConnection();try{await this.connectionPromise,this.connectionState="connected"}catch(r){throw this.connectionState="disconnected",this.connectionPromise=null,r}return this.connectionPromise}establishConnection(){return new Promise((t,r)=>{let a=!1;try{let o=`${this.url}/${this.namespace}`;this.log(`\u{1F517} Connecting to socket at: ${o}`),this.socket=Nmt(o,{autoConnect:!0,reconnection:!0,reconnectionAttempts:C$t.RECONNECTION_ATTEMPTS,reconnectionDelay:C$t.RECONNECTION_DELAY,...this.options.path&&{path:this.options.path}}),this.setupConnectionHandlers(t,r,a)}catch(o){this.logError("\u274C Failed to create socket connection:",o),a||r(o)}})}setupConnectionHandlers(t,r,a){if(!this.socket)return;let o={resolve:t,reject:r,connectionResolved:a};this.socket.on("connect",()=>this.handleConnect(o)),this.socket.on("reconnect",()=>this.handleReconnect()),this.socket.on("connect_error",c=>this.handleConnectError(c,o)),this.socket.on("disconnect",c=>this.handleDisconnect(c,o)),this.socket.io.on("reconnect_attempt",c=>this.handleReconnectAttempt(c)),this.socket.io.on("reconnect_error",c=>this.handleReconnectError(c)),this.socket.io.on("reconnect_failed",()=>this.handleReconnectFailed(o))}handleConnect(t){this.log("\u2705 Connected to socket"),this.connectionState="connected",this.setupEventHandlers(),t.connectionResolved||(t.connectionResolved=!0,t.resolve())}handleReconnect(){this.log("\u2705 Reconnected to socket"),this.connectionState="connected"}handleConnectError(t,r){var a;this.logError("\u274C Connection error:",t),this.connectionState="disconnected",!r.connectionResolved&&((a=this.socket)==null?void 0:a.disconnected)!==!1&&(r.connectionResolved=!0,r.reject(t))}handleDisconnect(t,r){this.log("\u{1F50C} Disconnected from socket:",t),this.connectionState="disconnected",this.resolution===null&&t==="io server disconnect"&&this.rejectInitialization(t),!r.connectionResolved&&(t==="io server disconnect"||t==="transport close")&&(r.connectionResolved=!0,r.reject(new Error(t)))}handleReconnectAttempt(t){this.log(`\u{1F504} Reconnection attempt #${t}`),this.connectionState="reconnecting"}handleReconnectError(t){this.logError("\u274C Reconnection attempt failed:",t)}handleReconnectFailed(t){this.logError("\u274C All reconnection attempts failed"),this.connectionState="disconnected",this.resolution===null&&this.rejectInitialization("All reconnection attempts failed"),t.connectionResolved||(t.connectionResolved=!0,t.reject(new Error("All reconnection attempts failed")))}setupEventHandlers(){if(!this.socket){this.logError("\u274C Cannot setup event handlers: socket is null");return}this.log("\u2705 Setting up event handlers"),this.socket.on("__call",this.handleGatewayCall.bind(this))}async handleGatewayCall(t,r){this.log(`\u{1F4E5} Gateway called method: ${t.key} with args:`,t.args);try{let a=this.validateGatewayCall(t);if(a){r(a);return}let o=this.handlers[t.key];if(!o){let f=`No handler registered for method: ${t.key}`;this.logError(`\u274C ${f}`),r(this.error(f));return}let c=await o(...t.args);r(this.success(c))}catch(a){this.logError("\u274C Error handling gateway call:",a),r(this.error(a.message||"Unknown error occurred"))}}validateGatewayCall(t){return t.key?Array.isArray(t.args)?null:(this.logError("\u274C Received call with invalid args"),this.error("Args must be an array")):(this.logError("\u274C Received call with undefined key"),this.error("Key is undefined"))}emit(t,r,a){if(!this.socket){this.logError("\u274C Cannot emit: socket is null");return}this.log(`\u{1F4E4} Emitting event: ${t}`),this.socket.emit(t,r,o=>{a(o)})}disconnect(){this.connectionState!=="shutting_down"&&(this.connectionState="shutting_down",this.log("\u{1F50C} Initiating disconnect"),this.socket&&(this.socket.disconnect(),this.socket=null),this.connectionPromise=null,this.connectionState="disconnected",this.log("\u2705 Disconnected successfully"))}};e(CQr,"AbstractClient");var w$t=CQr;var u$n,c$n,l$n,p$n,f$n,d$n,D$t=class D$t extends(d$n=w$t,f$n=yj.names.getState,p$n=yj.names.invokeCode,l$n=yj.names.final_result,c$n=yj.names.wait,u$n=yj.names.getElementScreenshot,d$n){constructor(r,a){super({verbose:Xm.testRun.autoRecovery.verboseConsoleLog,url:a.config.apiURL,namespace:"auto-recovery",path:"/auto-recovery/socket.io"});this.utils=r;this.initData=a;this.stepsThoughts=[];this.handlers=this.defineHandlers({callLangChainTool:e(async(r,a)=>{if(!this[r])throw new Error(`Tool ${r} not found`);return a.thought&&this.stepsThoughts.push(a.thought),await this[r].invoke(a)},"callLangChainTool"),getStatus:e(async r=>({sessionId:r,status:"active",data:{message:"Status retrieved successfully"}}),"getStatus")});this[f$n]=R4e.buildTool(yj,yj.names.getState,async r=>this.getStateHandler(r));this[p$n]=R4e.buildTool(yj,yj.names.invokeCode,async r=>this.invokeCodeHandler(r));this[l$n]=R4e.buildTool(yj,yj.names.final_result,async r=>this.finalResultHandler(r));this[c$n]=R4e.buildTool(yj,yj.names.wait,async r=>this.waitHandler(r));this[u$n]=R4e.buildTool(yj,yj.names.getElementScreenshot,async r=>this.getElementScreenshotHandler(r))}async init(){let r={...this.initData,version:yj.version};return await this.startSession("initialize",r).catch(a=>{this.utils.analytics.ARError({error:a.message});let o="Auto-Recovery Failed";return this.utils.createChecksumStep({title:o,withError:!0}),{finalThought:o,stepsThoughts:[],result:"failed"}})}static async build(r){let a=await r.buildFallbackData();return new D$t(r,a)}async invokeCodeHandler(r){let a;return await this.utils.runConditionallyWithinStep(!0,r.thought||"Invoke Code",async()=>{try{let o=await this.utils.invokeCode(r.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),a={success:!0,invokeCodeResult:`invokeCodeResult: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}catch(o){this.utils.createChecksumStep({title:"Error while invoking code",withError:!0}),a={success:!1,invokeCodeResult:`Error while invoking code: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}}),a}async getStateHandler(r){return this.utils.createChecksumStep({title:r.thought}),this.utils.analytics.ARGetState(r.thought),{success:!0,appState:(await this.utils.buildFallbackData()).applicationState}}finalResultHandler(r){let a=r.result==="pass",o=this.initData.type==="assertion"?a?"soft_assertion":"hard_assertion":a?"finish":"failed";this.utils.analytics.ARFinalResult({finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts});let c={finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts};this.utils.addAutoRecoveryErrorToReport(r.thought),this.resolveInitialization(c)}async getElementScreenshotHandler(r){return{success:!0,screenshot:await this.utils.getScreenshotForElement(r.checksumId)}}async waitHandler(r){await new Promise(o=>setTimeout(o,r.time||5e3));let a=await this.utils.buildFallbackData();return{success:!0,waitResult:`waited for ${r.time} seconds, the current HTML of the application after the wait is: ${a.applicationState.reducedHTML}`}}};e(D$t,"AutoRecoveryAgent");var S$t=D$t;var m$n=require("fs"),_$n=Jp(require("path"));var wQr=class wQr extends $W{constructor(r,a){let o=$W.getCurrentTestInfo();if(!o)throw new Error("TestRunAnalytics must be initialized with testInfo before FallbackAnalytics can be used");let c=$W.getCurrentInstance();if(!c)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating FallbackAnalytics");let f=c.getTestSuiteRunInfo();super(f,$W.isolatedMode,o);this.sessionId=null;this.fallbackId=r,this.fallbackType=a}updateToSessionId(r){this.sessionId!==r&&(this.sessionId=r,this.analytics&&this.analytics.alias({userId:r,previousId:this.fallbackId}))}get tableName(){return"auto_recovery"}get metadata(){return{...super.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(r){super.trackEventWithTable(r,this.metadata,this.tableName)}setFallbackType(r){this.fallbackType=r}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(r){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...r})}ARGetState(r){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:r})}ARInvokeCode(r,a){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:r,code:a})}ARFinalResult(r){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...r})}autoRecoveryDisconnect(r){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...r})}ARFinish(r){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...r})}ARError(r){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...r})}};e(wQr,"AutoRecoveryAnalytics");var T$t=wQr;var RPe=class RPe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:b,variableStore:C}){this.page=t,this.evaluateWithChecksum=r,this.checksumPage=a,this.pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=b,this.variableStore=C,this._analytics=new T$t(this.sessionId,b.type)}static async start(t){return new RPe({...t})}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,b=!0)=>{if(!_)return"";try{return(0,m$n.readFileSync)(_,b?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:b,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:b,rrwebId:C}},t)}async getReducedHtml(t=RPe.currentChecksumId){let{reducedHTML:r,currentChecksumId:a}=await this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return RPe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async buildFallbackData(){let{reducedHTML:t,currentChecksumId:r}=await this.getReducedHtml();return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:t,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:r,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.runtimeFallbackData.testIdentification.testId,variableStore:this.variableStore.reduce((a,o)=>(a[`variablesStore.${o.name}`]=o.value,a),{})}}async scrollToElement(t){t&&await this.pageInteractor.scrollElementIntoViewByChecksumId(t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelPreset)==null?void 0:a.type)==="anthropic-vertexai"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=_$n.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return f$e.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],b=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,C=(R=t.match(b))==null?void 0:R[1];if(!C)throw new Error("Checksum ID not found in the code");let w=await this.getSelectionDataForChecksumId(C);if(!(w!=null&&w.locator)||w.invalid)throw new Error(`Locator or selector not found for checksumId: ${C}`);a=a.replace(b,w.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(H=>H.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:C,locator:w.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t){let r=this.runtimeFallbackData.thoughts.failing;this.checksumPage.addPwAnnotation({type:`"${r}" auto-recovered`,description:t.replace(/^"(.*)"$/,"$1")}),this.checksumPage.addErrorMessage(this.fallbackData.error,`"${r}" auto-recovered:
1838
+ Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof t=="string"?`selector ${t}`:"locator"}`);try{t&&typeof t=="object"&&"has"in t&&this.popLocatorChain()}catch{}let a=this.getLocator(t,r);return new Proxy(a,{get:e((o,c)=>this.getLocatorMethod(a,o,c),"get")})}catch(a){Nv("Failed to locate",a)}}getLocatorMethod(t,r,a){return a==="then"?this.handleThen(t,r,a):a==="catch"?this.handleCatch(t,r):a==="finally"?this.handleFinally(t,r):a==="constructor"?e(function(...c){return this.popLocatorChain(),r.constructor(...c)},"Locator"):a in r&&typeof r[a]!="function"||a===Symbol.toPrimitive||a in Object||a==="evaluate"?(this.popLocatorChain(),r[a]):a==="compoundSelection"?function(...o){let c=this.compoundSelection(...o);return c.setBase(t),c}.bind(this):[...Object.values(ime),...Object.values(NQe)].includes(a)?["or","and"].includes(a)?(Nv("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),r[a]):(this.getCurrentLocatorChain().push({type:a,base:t}),e(function(...c){return this.executeLocator(c[0],c[1])},"Locator").bind(this)):a==="page"?()=>(this.popLocatorChain(),this.proxy.page()):e(async function(...c){let f=await this.executeLocatorAction(t,a,c);return this.popLocatorChain(),f},"Locator").bind(this)}async executeLocatorAction(t,r,a){if(a&&Array.from(a).some(_=>(_==null?void 0:_.bypassChecksum)===!0))return t[r](...a);let o=t._selector;Nv("Executing",r,o);let c=r==="_expect"?"assertion":"action";c==="action"&&this.lastLocatorActionType==="action"&&(Nv("Adding minimal wait between consecutive actions..."),await new Promise(_=>setTimeout(_,100))),this.lastLocatorActionType=c,Nv("Running initial locator...");let f;try{return this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{Nv("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{Nv("[executeLocatorAction] checksum libs not loaded")}}),await wUt.createAction({locator:t,method:r,args:a,timeout:this.getLocatorActionTimeout(c,r,a)},{api:this.checksumClient,pageInteractor:this.getPageInteractor()}).guardedExecute();f=new Error("Locator action error")}catch(_){Nv("Failed initial execution. Exception:",_.message),f=_}if(c==="action"&&this.onExecutionError)return this.onExecutionError({error:f,locator:t,method:r,args:a},this.frame);throw f}setExpectConfiguration(t=void 0){this.expectConfiguration=t}getLocatorActionTimeout(t,r,a=[]){var o;if(this.isReplMode)return null;try{if(t==="assertion"){let _=this.getAssertionTimeout(a);return Nv(`Assertion timeout set to ${_}`),_}let c=["fill","dragTo"].includes(r)?1:0,f=(o=a[c])==null?void 0:o.timeout;return isNaN(f)?3e4:f}catch{return 3e4}}getAssertionTimeout(t=[]){var o,c,f,_,b;let r=(o=t[1])==null?void 0:o.timeout;if(r!==void 0)return r;if(((c=this.expectConfiguration)==null?void 0:c.timeout)!==void 0)return(f=this.expectConfiguration)==null?void 0:f.timeout;let a=(b=(_=this.testInfo._projectInternal)==null?void 0:_.expect)==null?void 0:b.timeout;return a!==void 0?a:3e4}handleThen(t,r,a){return(o,c)=>Promise.resolve(t).then(f=>{let _=o?o(f):f;return _ instanceof Promise?_:this.getLocatorMethod(_,r,a)},f=>{if(c)return c(f);throw f})}handleCatch(t,r){return a=>Promise.resolve(t).catch(o=>{if(a)return a(o);throw o})}handleFinally(t,r){return a=>Promise.resolve(t).finally(a)}};e(TUt,"ChecksumFrame");var DUt=TUt;var kUt=class kUt{constructor(t,r,a,o,c){this.page=t;this.config=r;this.getPageInteractor=a;this.injectedScriptManager=o;this._frames={};this.isVTG=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;var f,_;this.setPageProxy(),this.injectedScriptManager||(this.injectedScriptManager=new dze({scriptFile:Xm.checksumScript.path,scriptSource:Xm.checksumScript.source,scriptURL:Xm.checksumScript.url,isScriptFileAbsolute:!0,silenceLogs:!Xm.isDevMode,scriptInitWait:(f=r==null?void 0:r.options)==null?void 0:f.browserScriptInitWait,scriptAddWait:(_=r==null?void 0:r.options)==null?void 0:_.browserScriptAddWait})),this.registerPageEvents(),this.page.frames().forEach(b=>this.registerFrame(b)),c&&(this.variableStore=c.variableStore)}static makePage(t,r,a){let o=IUt();return new kUt(t,o,()=>r,a).proxy}async registerFrame(t){var o;let r=this.getFrameGuid(t);if(t===this.page.mainFrame()&&(this.mainFrameGuid=r),this._frames[r])return;let a=DUt.init(t,this.proxy,this.injectedScriptManager,this.getPageInteractor,(o=this.onExecutionError)==null?void 0:o.bind(this),this.config);this._frames[r]=a}async onExecutionError(t){throw t.error}getFrameGuid(t){return t._guid}registerPageEvents(){this.page.on("frameattached",async t=>{this.registerFrame(t)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getPageMethod(a)},"get")})}getPageMethod(t){if(typeof this[t]=="function")return t==="constructor"?this[t]:this[t].bind(this);switch(t){case"pageInteractor":return this.getPageInteractor();case"variableStore":return this.variableStore}return Object.values(ime).includes(t)?e(function(a,o){try{return this.mainFrame()[t](a,o)}catch(c){throw c}},"Page").bind(this):this.page[t]}mainFrame(){var t;return(t=this._frames)==null?void 0:t[this.mainFrameGuid]}frames(){return Object.values(this._frames)}getFrame(t){if(!this.page.frames().find(a=>this.getFrameGuid(a)===t))throw new Error(`Frame with guid ${t} not found`);return this._frames[t]}async waitForDialog(t){try{return this.getPageInteractor().waitForDialog(!0,t)}catch(r){throw new Error(`Failed to handle native dialog: ${r}`)}}async reauthenticate(t){try{await this.getPageInteractor().reauthenticate(t,this.proxy)}catch(r){throw new Error(`Failed to reauthenticate: ${r}`)}}resolveAssetsFolder(t){return t.map(r=>hOn.join(Tpt(Ane()),r))}compoundSelection(...t){try{return new fze(this.mainFrame()).init(...t)}catch{throw new Error("Failed generating compound selector")}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}setExpectConfiguration(t=void 0){this.expectConfiguration=t,Object.values(this._frames).forEach(r=>r.setExpectConfiguration(t))}};e(kUt,"ChecksumPage");var mze=kUt;uqr();wI();var Jve=class Jve{constructor(){this.toolsMap={}}get addTool(){return this._addTool||(this._addTool=this.buildAddToolFacade()),this._addTool}getToolNames(){return Object.keys(this.toolRecord.names)}get tools(){return this.toolsMap}buildAddToolFacade(){let t={},r=this.toolRecord.tools;for(let a of Object.keys(r))t[a]=o=>this._addSingleTool(a,o);return t}static describeTool(t,r){if(t instanceof Th.ZodObject){let a={},o=t.shape;for(let c of Object.keys(o)){let f=o[c],_=r==null?void 0:r[c];typeof _=="string"?a[c]=f.describe(_):_&&typeof _=="object"?a[c]=Jve.describeTool(f,_):a[c]=f}return Th.object(a).strict()}if(t instanceof Th.ZodArray){let a=t.element;return r&&typeof r=="object"&&r.element?Th.array(Jve.describeTool(a,r.element)):t}return t instanceof Th.ZodOptional?Jve.describeTool(t.unwrap(),r).optional():t instanceof Th.ZodNullable?Jve.describeTool(t.unwrap(),r).nullable():typeof r=="string"?t.describe(r):t}_addSingleTool(t,r){let a=r.name??String(t),c=this.toolRecord.tools[t]._create({...r,name:a,params:r.params,handler:r.handler}),f=this.toolRecord.tools[t],_=Jve.describeTool(f,r.params),C=nqr(e(async w=>{let T=_.parse(w);return r.handler(T)},"validatedHandler"),{name:c.name,description:c.description,schema:_});return this.toolsMap[t]=C,C}_buildOne(t,r){return this._addSingleTool(t,{...r,name:String(t)})}static buildTool(t,r,a){let o=String(r),f=t.tools[r]._create({name:o,description:"",handler:a,params:{}}),_=t.tools[r],b=Jve.describeTool(_,{});return nqr(e(async T=>{let k=b.parse(T);return a(k)},"validatedHandler"),{name:f.name,description:f.description,schema:b})}};e(Jve,"AbstractToolContainer");var R4e=Jve;wI();var zQt=class zQt{constructor(t,r){this.version=t;let a={};for(let c in r)a[c]=c;this.names=a;let o={};for(let c in r){let f=r[c];Object.defineProperty(f,"name",{value:c,configurable:!1,enumerable:!0,writable:!1}),f._create=(_=>b=>{let C=b.name??_;return{...b,name:C}})(c),o[c]=f}this.tools=o}static create(t,r){return new zQt(t,r)}};e(zQt,"ToolProtocol");var VQt=zQt;var yj=VQt.create("v1",{readFile:Th.object({path:Th.string()}),getState:Th.object({thought:Th.string()}),invokeCode:Th.object({code:Th.string().refine(i=>{let t=i.trim();return t.includes("page.getByChecksumId(")||t.includes("page.getByChecksumId(")||t.startsWith("const ")||t.startsWith("let ")||t.startsWith("var ")||t.includes("=")||t.includes("variableStore.")},{message:"Code should use page.getByChecksumId() for element targeting, or be explicit variable assignments/function calls"}),thought:Th.string()}),wait:Th.object({time:Th.number().optional()}),scroll:Th.object({checksumId:Th.string(),thought:Th.string()}),final_result:Th.object({result:Th.enum(["pass","fail"]),thought:Th.string(),visualAnalysis:Th.string().optional()}),getElementScreenshot:Th.object({checksumId:Th.string(),thought:Th.string()}),analyze:Th.object({previousImmediateSteps:Th.string(),currentFailingStep:Th.string(),nextImmediateSteps:Th.string(),testStepToStopAt:Th.string()}),think:Th.object({thought:Th.string()})});var Cqr=Jp(eqn(),1);var Dce=Object.create(null);Dce.open="0";Dce.close="1";Dce.ping="2";Dce.pong="3";Dce.message="4";Dce.upgrade="5";Dce.noop="6";var pmt=Object.create(null);Object.keys(Dce).forEach(i=>{pmt[Dce[i]]=i});var fmt={type:"error",data:"parser error"};var dmt=e(({type:i,data:t},r,a)=>t instanceof ArrayBuffer||ArrayBuffer.isView(t)?a(r?t:"b"+tqn(t,!0).toString("base64")):a(Dce[i]+(t||"")),"encodePacket"),tqn=e((i,t)=>Buffer.isBuffer(i)||i instanceof Uint8Array&&!t?i:i instanceof ArrayBuffer?Buffer.from(i):Buffer.from(i.buffer,i.byteOffset,i.byteLength),"toBuffer"),lqr;function rqn(i,t){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return t(tqn(i.data,!1));dmt(i,!0,r=>{lqr||(lqr=new TextEncoder),t(lqr.encode(r))})}e(rqn,"encodePacketToBinary");var mmt=e((i,t)=>{if(typeof i!="string")return{type:"message",data:nqn(i,t)};let r=i.charAt(0);if(r==="b"){let a=Buffer.from(i.substring(1),"base64");return{type:"message",data:nqn(a,t)}}return pmt[r]?i.length>1?{type:pmt[r],data:i.substring(1)}:{type:pmt[r]}:fmt},"decodePacket"),nqn=e((i,t)=>{switch(t){case"arraybuffer":return i instanceof ArrayBuffer?i:Buffer.isBuffer(i)?i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength):i.buffer;case"nodebuffer":default:return Buffer.isBuffer(i)?i:Buffer.from(i)}},"mapBinary");var iqn="",aqn=e((i,t)=>{let r=i.length,a=new Array(r),o=0;i.forEach((c,f)=>{dmt(c,!1,_=>{a[f]=_,++o===r&&t(a.join(iqn))})})},"encodePayload"),sqn=e((i,t)=>{let r=i.split(iqn),a=[];for(let o=0;o<r.length;o++){let c=mmt(r[o],t);if(a.push(c),c.type==="error")break}return a},"decodePayload");function oqn(){return new TransformStream({transform(i,t){rqn(i,r=>{let a=r.length,o;if(a<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,a);else if(a<65536){o=new Uint8Array(3);let c=new DataView(o.buffer);c.setUint8(0,126),c.setUint16(1,a)}else{o=new Uint8Array(9);let c=new DataView(o.buffer);c.setUint8(0,127),c.setBigUint64(1,BigInt(a))}i.data&&typeof i.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}e(oqn,"createPacketEncoderStream");var pqr;function JQt(i){return i.reduce((t,r)=>t+r.length,0)}e(JQt,"totalLength");function HQt(i,t){if(i[0].length===t)return i.shift();let r=new Uint8Array(t),a=0;for(let o=0;o<t;o++)r[o]=i[0][a++],a===i[0].length&&(i.shift(),a=0);return i.length&&a<i[0].length&&(i[0]=i[0].slice(a)),r}e(HQt,"concatChunks");function uqn(i,t){pqr||(pqr=new TextDecoder);let r=[],a=0,o=-1,c=!1;return new TransformStream({transform(f,_){for(r.push(f);;){if(a===0){if(JQt(r)<1)break;let b=HQt(r,1);c=(b[0]&128)===128,o=b[0]&127,o<126?a=3:o===126?a=1:a=2}else if(a===1){if(JQt(r)<2)break;let b=HQt(r,2);o=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(JQt(r)<8)break;let b=HQt(r,8),C=new DataView(b.buffer,b.byteOffset,b.length),w=C.getUint32(0);if(w>Math.pow(2,21)-1){_.enqueue(fmt);break}o=w*Math.pow(2,32)+C.getUint32(4),a=3}else{if(JQt(r)<o)break;let b=HQt(r,o);_.enqueue(mmt(c?b:pqr.decode(b),t)),a=0}if(o===0||o>i){_.enqueue(fmt);break}}}})}e(uqn,"createPacketDecoderStream");var fqr=4;var Cqn=Jp(SPe(),1);var Hve=process.nextTick,Ez=global,lqn="nodebuffer";function pqn(){return new dqr}e(pqn,"createCookieJar");function mva(i){let t=i.split("; "),r=t[0].indexOf("=");if(r===-1)return;let a=t[0].substring(0,r).trim();if(!a.length)return;let o=t[0].substring(r+1).trim();o.charCodeAt(0)===34&&(o=o.slice(1,-1));let c={name:a,value:o};for(let f=1;f<t.length;f++){let _=t[f].split("=");if(_.length!==2)continue;let b=_[0].trim(),C=_[1].trim();switch(b){case"Expires":c.expires=new Date(C);break;case"Max-Age":let w=new Date;w.setUTCSeconds(w.getUTCSeconds()+parseInt(C,10)),c.expires=w;break;default:}}return c}e(mva,"parse");var mqr=class mqr{constructor(){this._cookies=new Map}parseCookies(t){t&&t.forEach(r=>{let a=mva(r);a&&this._cookies.set(a.name,a)})}get cookies(){let t=Date.now();return this._cookies.forEach((r,a)=>{var o;((o=r.expires)===null||o===void 0?void 0:o.getTime())<t&&this._cookies.delete(a)}),this._cookies.entries()}addCookies(t){let r=[];for(let[a,o]of this.cookies)r.push(`${a}=${o.value}`);r.length&&(t.setDisableHeaderCheck(!0),t.setRequestHeader("cookie",r.join("; ")))}appendCookies(t){for(let[r,a]of this.cookies)t.append("cookie",`${r}=${a.value}`)}};e(mqr,"CookieJar");var dqr=mqr;function WQt(i,...t){return t.reduce((r,a)=>(i.hasOwnProperty(a)&&(r[a]=i[a]),r),{})}e(WQt,"pick");var _va=Ez.setTimeout,hva=Ez.clearTimeout;function Wve(i,t){t.useNativeTimers?(i.setTimeoutFn=_va.bind(Ez),i.clearTimeoutFn=hva.bind(Ez)):(i.setTimeoutFn=Ez.setTimeout.bind(Ez),i.clearTimeoutFn=Ez.clearTimeout.bind(Ez))}e(Wve,"installTimerFunctions");var gva=1.33;function fqn(i){return typeof i=="string"?yva(i):Math.ceil((i.byteLength||i.size)*gva)}e(fqn,"byteLength");function yva(i){let t=0,r=0;for(let a=0,o=i.length;a<o;a++)t=i.charCodeAt(a),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(a++,r+=4);return r}e(yva,"utf8Length");function GQt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}e(GQt,"randomString");function dqn(i){let t="";for(let r in i)i.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(i[r]));return t}e(dqn,"encode");function mqn(i){let t={},r=i.split("&");for(let a=0,o=r.length;a<o;a++){let c=r[a].split("=");t[decodeURIComponent(c[0])]=decodeURIComponent(c[1])}return t}e(mqn,"decode");var wqn=Jp(kPe(),1);var qva=(0,wqn.default)("engine.io-client:transport"),vqr=class vqr extends Error{constructor(t,r,a){super(t),this.description=r,this.context=a,this.type="TransportError"}};e(vqr,"TransportError");var e$t=vqr,bqr=class bqr extends Cqn.Emitter{constructor(t){super(),this.writable=!1,Wve(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,a){return super.emitReserved("error",new e$t(t,r,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"?this.write(t):qva("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){let r=mmt(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){let t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){let r=dqn(t);return r.length?"?"+r:""}};e(bqr,"Transport");var Gve=bqr;var Sqn=Jp(kPe(),1);var Tce=(0,Sqn.default)("engine.io-client:polling"),xqr=class xqr extends Gve{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";let r=e(()=>{Tce("paused"),this.readyState="paused",t()},"pause");if(this._polling||!this.writable){let a=0;this._polling&&(Tce("we are currently polling - waiting to pause"),a++,this.once("pollComplete",function(){Tce("pre-pause polling complete"),--a||r()})),this.writable||(Tce("we are currently writing - waiting to pause"),a++,this.once("drain",function(){Tce("pre-pause writing complete"),--a||r()}))}else r()}_poll(){Tce("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){Tce("polling got data %s",t);let r=e(a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)},"callback");sqn(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Tce('ignoring poll - transport state "%s"',this.readyState))}doClose(){let t=e(()=>{Tce("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(Tce("transport open - closing"),t()):(Tce("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,aqn(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=GQt()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}};e(xqr,"Polling");var hmt=xqr;var Iqn=Jp(SPe(),1);var Dqn=!1;try{Dqn=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Tqn=Dqn;var Pqn=Jp(kPe(),1);var Aqr=(0,Pqn.default)("engine.io-client:polling");function Qva(){}e(Qva,"empty");var Eqr=class Eqr extends hmt{constructor(t){if(super(t),typeof location<"u"){let r=location.protocol==="https:",a=location.port;a||(a=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||a!==t.port}}doWrite(t,r){let a=this.request({method:"POST",data:t});a.on("success",r),a.on("error",(o,c)=>{this.onError("xhr post error",o,c)})}doPoll(){Aqr("xhr poll");let t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,a)=>{this.onError("xhr poll error",r,a)}),this.pollXhr=t}};e(Eqr,"BaseXHR");var t$t=Eqr,sJe=class sJe extends Iqn.Emitter{constructor(t,r,a){super(),this.createRequest=t,Wve(this,a),this._opts=a,this._method=a.method||"GET",this._uri=r,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var t;let r=WQt(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let a=this._xhr=this.createRequest(r);try{Aqr("xhr open %s: %s",this._method,this._uri),a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let o in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(o)&&a.setRequestHeader(o,this._opts.extraHeaders[o])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var o;a.readyState===3&&((o=this._opts.cookieJar)===null||o===void 0||o.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},Aqr("xhr data %s",this._data),a.send(this._data)}catch(o){this.setTimeoutFn(()=>{this._onError(o)},0);return}typeof document<"u"&&(this._index=sJe.requestsCount++,sJe.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Qva,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete sJe.requests[this._index],this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};e(sJe,"Request");var Kve=sJe;Kve.requestsCount=0;Kve.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",kqn);else if(typeof addEventListener=="function"){let i="onpagehide"in Ez?"pagehide":"unload";addEventListener(i,kqn,!1)}}function kqn(){for(let i in Kve.requests)Kve.requests.hasOwnProperty(i)&&Kve.requests[i].abort()}e(kqn,"unloadHandler");var J3s=function(){let i=$va({xdomain:!1});return i&&i.responseType!==null}();function $va(i){let t=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Tqn))return new XMLHttpRequest}catch{}if(!t)try{return new Ez[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}e($va,"newRequest");var Vva=Cqr.default||Cqr,wqr=class wqr extends t$t{request(t={}){var r;return Object.assign(t,{xd:this.xd,cookieJar:(r=this.socket)===null||r===void 0?void 0:r._cookieJar},this.opts),new Kve(a=>new Vva(a),this.uri(),t)}};e(wqr,"XHR");var oJe=wqr;var exa=Jp(Bqn(),1),txa=Jp(jqr(),1),rxa=Jp(qqr(),1),tQr=Jp(Xqr(),1),nxa=Jp(FQn(),1);var NQn=Jp(kPe(),1);var axa=(0,NQn.default)("engine.io-client:websocket"),sxa=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",rQr=class rQr extends Gve{get name(){return"websocket"}doOpen(){let t=this.uri(),r=this.opts.protocols,a=sxa?{}:WQt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,a)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;dmt(a,this.supportsBinary,c=>{try{this.doWrite(a,c)}catch{axa("websocket closed before onclose event")}o&&Hve(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=GQt()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}};e(rQr,"BaseWS");var _$t=rQr,F8s=Ez.WebSocket||Ez.MozWebSocket;var nQr=class nQr extends _$t{createSocket(t,r,a){var o;if(!((o=this.socket)===null||o===void 0)&&o._cookieJar){a.headers=a.headers||{},a.headers.cookie=typeof a.headers.cookie=="string"?[a.headers.cookie]:a.headers.cookie||[];for(let[c,f]of this.socket._cookieJar.cookies)a.headers.cookie.push(`${c}=${f.value}`)}return new tQr.default(t,r,a)}doWrite(t,r){let a={};t.options&&(a.compress=t.options.compress),this.opts.perMessageDeflate&&(typeof r=="string"?Buffer.byteLength(r):r.length)<this.opts.perMessageDeflate.threshold&&(a.compress=!1),this.ws.send(r,a)}};e(nQr,"WS");var fJe=nQr;var OQn=Jp(kPe(),1);var Dmt=(0,OQn.default)("engine.io-client:webtransport"),iQr=class iQr extends Gve{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{Dmt("transport closed gracefully"),this.onClose()}).catch(t=>{Dmt("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{let r=uqn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=t.readable.pipeThrough(r).getReader(),o=oqn();o.readable.pipeTo(t.writable),this._writer=o.writable.getWriter();let c=e(()=>{a.read().then(({done:_,value:b})=>{if(_){Dmt("session is closed");return}Dmt("received chunk: %o",b),this.onPacket(b),c()}).catch(_=>{Dmt("an error occurred while reading: %s",_)})},"read");c();let f={type:"open"};this.query.sid&&(f.data=`{"sid":"${this.query.sid}"}`),this._writer.write(f).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;this._writer.write(a).then(()=>{o&&Hve(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}};e(iQr,"WT");var dJe=iQr;var aQr={websocket:fJe,webtransport:dJe,polling:oJe};var oxa=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,uxa=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mJe(i){if(i.length>8e3)throw"URI too long";let t=i,r=i.indexOf("["),a=i.indexOf("]");r!=-1&&a!=-1&&(i=i.substring(0,r)+i.substring(r,a).replace(/:/g,";")+i.substring(a,i.length));let o=oxa.exec(i||""),c={},f=14;for(;f--;)c[uxa[f]]=o[f]||"";return r!=-1&&a!=-1&&(c.source=t,c.host=c.host.substring(1,c.host.length-1).replace(/;/g,":"),c.authority=c.authority.replace("[","").replace("]","").replace(/;/g,":"),c.ipv6uri=!0),c.pathNames=cxa(c,c.path),c.queryKey=lxa(c,c.query),c}e(mJe,"parse");function cxa(i,t){let r=/\/{2,9}/g,a=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&a.splice(0,1),t.slice(-1)=="/"&&a.splice(a.length-1,1),a}e(cxa,"pathNames");function lxa(i,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,o,c){o&&(r[o]=c)}),r}e(lxa,"queryKey");var BQn=Jp(SPe(),1);var RQn=Jp(kPe(),1);var A7=(0,RQn.default)("engine.io-client:socket"),sQr=typeof addEventListener=="function"&&typeof removeEventListener=="function",Tmt=[];sQr&&addEventListener("offline",()=>{A7("closing %d connection(s) because the network was lost",Tmt.length),Tmt.forEach(i=>i())},!1);var _Je=class _Je extends BQn.Emitter{constructor(t,r){if(super(),this.binaryType=lqn,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let a=mJe(t);r.hostname=a.host,r.secure=a.protocol==="https"||a.protocol==="wss",r.port=a.port,a.query&&(r.query=a.query)}else r.host&&(r.hostname=mJe(r.host).host);Wve(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(a=>{let o=a.prototype.name;this.transports.push(o),this._transportsByName[o]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=mqn(this.opts.query)),sQr&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(A7("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Tmt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=pqn()),this._open()}createTransport(t){A7('creating transport "%s"',t);let r=Object.assign({},this.opts.query);r.EIO=fqr,r.transport=t,this.id&&(r.sid=this.id);let a=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return A7("options: %j",a),new this._transportsByName[t](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&_Je.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){A7("setting transport %s",t.name),this.transport&&(A7("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){A7("socket open"),this.readyState="open",_Je.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(A7('socket receive: type "%s", data "%s"',t.type,t.data),this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}else A7('packet received with socket readyState "%s"',this.readyState)}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();A7("flushing %d packets in socket",t.length),this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let a=0;a<this.writeBuffer.length;a++){let o=this.writeBuffer[a].data;if(o&&(r+=fqn(o)),a>0&&r>this._maxPayload)return A7("only send %d out of %d packets",a,this.writeBuffer.length),this.writeBuffer.slice(0,a);r+=2}return A7("payload size is %d (max: %d)",r,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(A7("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,Hve(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,a){return this._sendPacket("message",t,r,a),this}send(t,r,a){return this._sendPacket("message",t,r,a),this}_sendPacket(t,r,a,o){if(typeof r=="function"&&(o=r,r=void 0),typeof a=="function"&&(o=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;let c={type:t,data:r,options:a};this.emitReserved("packetCreate",c),this.writeBuffer.push(c),o&&this.once("flush",o),this.flush()}close(){let t=e(()=>{this._onClose("forced close"),A7("socket closing - telling transport to close"),this.transport.close()},"close"),r=e(()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},"cleanupAndClose"),a=e(()=>{this.once("upgrade",r),this.once("upgradeError",r)},"waitForUpgrade");return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():t()}):this.upgrading?a():t()),this}_onError(t){if(A7("socket error %j",t),_Je.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return A7("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(A7('socket close with reason: "%s"',t),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),sQr&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let a=Tmt.indexOf(this._offlineEventListener);a!==-1&&(A7("removing listener for the 'offline' event"),Tmt.splice(a,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};e(_Je,"SocketWithoutUpgrade");var OPe=_Je;OPe.protocol=fqr;var oQr=class oQr extends OPe{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){A7("starting upgrade probes");for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}}_probe(t){A7('probing transport "%s"',t);let r=this.createTransport(t),a=!1;OPe.priorWebsocketSuccess=!1;let o=e(()=>{a||(A7('probe transport "%s" opened',t),r.send([{type:"ping",data:"probe"}]),r.once("packet",T=>{if(!a)if(T.type==="pong"&&T.data==="probe"){if(A7('probe transport "%s" pong',t),this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;OPe.priorWebsocketSuccess=r.name==="websocket",A7('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{a||this.readyState!=="closed"&&(A7("changing transport and sending upgrade packet"),w(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{A7('probe transport "%s" failed',t);let k=new Error("probe error");k.transport=r.name,this.emitReserved("upgradeError",k)}}))},"onTransportOpen");function c(){a||(a=!0,w(),r.close(),r=null)}e(c,"freezeTransport");let f=e(T=>{let k=new Error("probe error: "+T);k.transport=r.name,c(),A7('probe transport "%s" failed because of error: %s',t,T),this.emitReserved("upgradeError",k)},"onerror");function _(){f("transport closed")}e(_,"onTransportClose");function b(){f("socket closed")}e(b,"onclose");function C(T){r&&T.name!==r.name&&(A7('"%s" works - aborting "%s"',T.name,r.name),c())}e(C,"onupgrade");let w=e(()=>{r.removeListener("open",o),r.removeListener("error",f),r.removeListener("close",_),this.off("close",b),this.off("upgrading",C)},"cleanup");r.once("open",o),r.once("error",f),r.once("close",_),this.once("close",b),this.once("upgrading",C),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{a||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){let r=[];for(let a=0;a<t.length;a++)~this.transports.indexOf(t[a])&&r.push(t[a]);return r}};e(oQr,"SocketWithUpgrade");var h$t=oQr,uQr=class uQr extends h$t{constructor(t,r={}){let a=typeof t=="object"?t:r;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(o=>aQr[o]).filter(o=>!!o)),super(t,a)}};e(uQr,"Socket");var hJe=uQr;var oTs=hJe.protocol;var QQn=Jp(kmt(),1);var qQn=(0,QQn.default)("socket.io-client:url");function $Qn(i,t="",r){let a=i;r=r||typeof location<"u"&&location,i==null&&(i=r.protocol+"//"+r.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=r.protocol+i:i=r.host+i),/^(https?|wss?):\/\//.test(i)||(qQn("protocol-less url %s",i),typeof r<"u"?i=r.protocol+"//"+i:i="https://"+i),qQn("parse %s",i),a=mJe(i)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";let c=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+c+":"+a.port+t,a.href=a.protocol+"://"+c+(r&&r.port===a.port?"":":"+a.port),a}e($Qn,"url");var vQr={};rj(vQr,{Decoder:()=>gQr,Encoder:()=>hQr,PacketType:()=>FE,protocol:()=>t$n});var ZQn=Jp(SPe(),1);var kxa=typeof ArrayBuffer=="function",Ixa=e(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),VQn=Object.prototype.toString,Pxa=typeof Blob=="function"||typeof Blob<"u"&&VQn.call(Blob)==="[object BlobConstructor]",Fxa=typeof File=="function"||typeof File<"u"&&VQn.call(File)==="[object FileConstructor]";function Pmt(i){return kxa&&(i instanceof ArrayBuffer||Ixa(i))||Pxa&&i instanceof Blob||Fxa&&i instanceof File}e(Pmt,"isBinary");function Imt(i,t){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let r=0,a=i.length;r<a;r++)if(Imt(i[r]))return!0;return!1}if(Pmt(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return Imt(i.toJSON(),!0);for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)&&Imt(i[r]))return!0;return!1}e(Imt,"hasBinary");function zQn(i){let t=[],r=i.data,a=i;return a.data=pQr(r,t),a.attachments=t.length,{packet:a,buffers:t}}e(zQn,"deconstructPacket");function pQr(i,t){if(!i)return i;if(Pmt(i)){let r={_placeholder:!0,num:t.length};return t.push(i),r}else if(Array.isArray(i)){let r=new Array(i.length);for(let a=0;a<i.length;a++)r[a]=pQr(i[a],t);return r}else if(typeof i=="object"&&!(i instanceof Date)){let r={};for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&(r[a]=pQr(i[a],t));return r}return i}e(pQr,"_deconstructPacket");function JQn(i,t){return i.data=fQr(i.data,t),delete i.attachments,i}e(JQn,"reconstructPacket");function fQr(i,t){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<t.length)return t[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let r=0;r<i.length;r++)i[r]=fQr(i[r],t);else if(typeof i=="object")for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(i[r]=fQr(i[r],t));return i}e(fQr,"_reconstructPacket");var e$n=Jp(YQn(),1);var _Qr=(0,e$n.default)("socket.io-parser"),Wxa=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],t$n=5,FE;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(FE||(FE={}));var bQr=class bQr{constructor(t){this.replacer=t}encode(t){return _Qr("encoding packet %j",t),(t.type===FE.EVENT||t.type===FE.ACK)&&Imt(t)?this.encodeAsBinary({type:t.type===FE.EVENT?FE.BINARY_EVENT:FE.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let r=""+t.type;return(t.type===FE.BINARY_EVENT||t.type===FE.BINARY_ACK)&&(r+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(r+=t.nsp+","),t.id!=null&&(r+=t.id),t.data!=null&&(r+=JSON.stringify(t.data,this.replacer)),_Qr("encoded %j as %s",t,r),r}encodeAsBinary(t){let r=zQn(t),a=this.encodeAsString(r.packet),o=r.buffers;return o.unshift(a),o}};e(bQr,"Encoder");var hQr=bQr;function XQn(i){return Object.prototype.toString.call(i)==="[object Object]"}e(XQn,"isObject");var E$t=class E$t extends ZQn.Emitter{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let a=r.type===FE.BINARY_EVENT;a||r.type===FE.BINARY_ACK?(r.type=a?FE.EVENT:FE.ACK,this.reconstructor=new yQr(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(Pmt(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,a={type:Number(t.charAt(0))};if(FE[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===FE.BINARY_EVENT||a.type===FE.BINARY_ACK){let c=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let f=t.substring(c,r);if(f!=Number(f)||t.charAt(r)!=="-")throw new Error("Illegal attachments");a.attachments=Number(f)}if(t.charAt(r+1)==="/"){let c=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););a.nsp=t.substring(c,r)}else a.nsp="/";let o=t.charAt(r+1);if(o!==""&&Number(o)==o){let c=r+1;for(;++r;){let f=t.charAt(r);if(f==null||Number(f)!=f){--r;break}if(r===t.length)break}a.id=Number(t.substring(c,r+1))}if(t.charAt(++r)){let c=this.tryParse(t.substr(r));if(E$t.isPayloadValid(a.type,c))a.data=c;else throw new Error("invalid payload")}return _Qr("decoded %s as %j",t,a),a}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case FE.CONNECT:return XQn(r);case FE.DISCONNECT:return r===void 0;case FE.CONNECT_ERROR:return typeof r=="string"||XQn(r);case FE.EVENT:case FE.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&Wxa.indexOf(r[0])===-1);case FE.ACK:case FE.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};e(E$t,"Decoder");var gQr=E$t,xQr=class xQr{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){let r=JQn(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};e(xQr,"BinaryReconstructor");var yQr=xQr;function gZ(i,t,r){return i.on(t,r),e(function(){i.off(t,r)},"subDestroy")}e(gZ,"on");var r$n=Jp(SPe(),1),n$n=Jp(kmt(),1);var rO=(0,n$n.default)("socket.io-client:socket"),Gxa=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),AQr=class AQr extends r$n.Emitter{constructor(t,r,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=r,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let t=this.io;this.subs=[gZ(t,"open",this.onopen.bind(this)),gZ(t,"packet",this.onpacket.bind(this)),gZ(t,"error",this.onerror.bind(this)),gZ(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var a,o,c;if(Gxa.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;let f={type:FE.EVENT,data:r};if(f.options={},f.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){let w=this.ids++;rO("emitting packet with ack id %d",w);let T=r.pop();this._registerAckCallback(w,T),f.id=w}let _=(o=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||o===void 0?void 0:o.writable,b=this.connected&&!(!((c=this.io.engine)===null||c===void 0)&&c._hasPingExpired());return this.flags.volatile&&!_?rO("discard packet as the transport is not currently writable"):b?(this.notifyOutgoingListeners(f),this.packet(f)):this.sendBuffer.push(f),this.flags={},this}_registerAckCallback(t,r){var a;let o=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(o===void 0){this.acks[t]=r;return}let c=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let _=0;_<this.sendBuffer.length;_++)this.sendBuffer[_].id===t&&(rO("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(_,1));rO("event with ack id %d has timed out after %d ms",t,o),r.call(this,new Error("operation has timed out"))},o),f=e((..._)=>{this.io.clearTimeoutFn(c),r.apply(this,_)},"fn");f.withError=!0,this.acks[t]=f}emitWithAck(t,...r){return new Promise((a,o)=>{let c=e((f,_)=>f?o(f):a(_),"fn");c.withError=!0,r.push(c),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());let a={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...c)=>a!==this._queue[0]?void 0:(o!==null?a.tryCount>this._opts.retries&&(rO("packet [%d] is discarded after %d tries",a.id,a.tryCount),this._queue.shift(),r&&r(o)):(rO("packet [%d] was successfully sent",a.id),this._queue.shift(),r&&r(null,...c)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(t=!1){if(rO("draining queue"),!this.connected||this._queue.length===0)return;let r=this._queue[0];if(r.pending&&!t){rO("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,rO("sending packet [%d] (try n\xB0%d)",r.id,r.tryCount),this.flags=r.flags,this.emit.apply(this,r.args)}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){rO("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:FE.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){rO("close (%s)",t),this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(a=>String(a.id)===t)){let a=this.acks[t];delete this.acks[t],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case FE.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case FE.EVENT:case FE.BINARY_EVENT:this.onevent(t);break;case FE.ACK:case FE.BINARY_ACK:this.onack(t);break;case FE.DISCONNECT:this.ondisconnect();break;case FE.CONNECT_ERROR:this.destroy();let a=new Error(t.data.message);a.data=t.data.data,this.emitReserved("connect_error",a);break}}onevent(t){let r=t.data||[];rO("emitting event %j",r),t.id!=null&&(rO("attaching ack callback to event"),r.push(this.ack(t.id))),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){let r=this._anyListeners.slice();for(let a of r)a.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){let r=this,a=!1;return function(...o){a||(a=!0,rO("sending ack %j",o),r.packet({type:FE.ACK,id:t,data:o}))}}onack(t){let r=this.acks[t.id];if(typeof r!="function"){rO("bad ack %s",t.id);return}delete this.acks[t.id],rO("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){rO("socket connected with id %s",t),this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){rO("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(rO("performing disconnect (%s)",this.nsp),this.packet({type:FE.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){let r=this._anyListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){let r=this._anyOutgoingListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let r=this._anyOutgoingListeners.slice();for(let a of r)a.apply(this,t.data)}}};e(AQr,"Socket");var gJe=AQr;function BPe(i){i=i||{},this.ms=i.min||100,this.max=i.max||1e4,this.factor=i.factor||2,this.jitter=i.jitter>0&&i.jitter<=1?i.jitter:0,this.attempts=0}e(BPe,"Backoff");BPe.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*i);i=Math.floor(t*10)&1?i+r:i-r}return Math.min(i,this.max)|0};BPe.prototype.reset=function(){this.attempts=0};BPe.prototype.setMin=function(i){this.ms=i};BPe.prototype.setMax=function(i){this.max=i};BPe.prototype.setJitter=function(i){this.jitter=i};var i$n=Jp(SPe(),1),a$n=Jp(kmt(),1);var vj=(0,a$n.default)("socket.io-client:manager"),EQr=class EQr extends i$n.Emitter{constructor(t,r){var a;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,Wve(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((a=r.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new BPe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;let o=r.parser||vQr;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(vj("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;vj("opening %s",this.uri),this.engine=new hJe(this.uri,this.opts);let r=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;let o=gZ(r,"open",function(){a.onopen(),t&&t()}),c=e(_=>{vj("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",_),t?t(_):this.maybeReconnectOnOpen()},"onError"),f=gZ(r,"error",c);if(this._timeout!==!1){let _=this._timeout;vj("connect attempt will timeout after %d",_);let b=this.setTimeoutFn(()=>{vj("connect attempt timed out after %d",_),o(),c(new Error("timeout")),r.close()},_);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(o),this.subs.push(f),this}connect(t){return this.open(t)}onopen(){vj("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let t=this.engine;this.subs.push(gZ(t,"ping",this.onping.bind(this)),gZ(t,"data",this.ondata.bind(this)),gZ(t,"error",this.onerror.bind(this)),gZ(t,"close",this.onclose.bind(this)),gZ(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){Hve(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){vj("error",t),this.emitReserved("error",t)}socket(t,r){let a=this.nsps[t];return a?this._autoConnect&&!a.active&&a.connect():(a=new gJe(this,t,r),this.nsps[t]=a),a}_destroy(t){let r=Object.keys(this.nsps);for(let a of r)if(this.nsps[a].active){vj("socket %s is still active, skipping close",a);return}this._close()}_packet(t){vj("writing packet %j",t);let r=this.encoder.encode(t);for(let a=0;a<r.length;a++)this.engine.write(r[a],t.options)}cleanup(){vj("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){vj("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var a;vj("closed due to %s",t),this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let t=this;if(this.backoff.attempts>=this._reconnectionAttempts)vj("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let r=this.backoff.duration();vj("will wait %dms before reconnect attempt",r),this._reconnecting=!0;let a=this.setTimeoutFn(()=>{t.skipReconnect||(vj("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(vj("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):(vj("reconnect success"),t.onreconnect())}))},r);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){let t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}};e(EQr,"Manager");var yJe=EQr;var o$n=Jp(kmt(),1);var s$n=(0,o$n.default)("socket.io-client"),Fmt={};function Nmt(i,t){typeof i=="object"&&(t=i,i=void 0),t=t||{};let r=$Qn(i,t.path||"/socket.io"),a=r.source,o=r.id,c=r.path,f=Fmt[o]&&c in Fmt[o].nsps,_=t.forceNew||t["force new connection"]||t.multiplex===!1||f,b;return _?(s$n("ignoring socket cache for %s",a),b=new yJe(a,t)):(Fmt[o]||(s$n("new io instance for %s",a),Fmt[o]=new yJe(a,t)),b=Fmt[o]),r.query&&!t.query&&(t.query=r.queryKey),b.socket(r.path,t)}e(Nmt,"lookup");Object.assign(Nmt,{Manager:yJe,Socket:gJe,io:Nmt,connect:Nmt});var C$t={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},CQr=class CQr{constructor(t={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=t,this.url=t.url||C$t.URL,this.namespace=t.namespace||C$t.NAMESPACE,this.initializationPromise=this.createInitializationPromise()}createInitializationPromise(){return new Promise((t,r)=>{this.resolveInitialization=a=>t(a),this.rejectInitialization=a=>r(a)}).then(t=>(this.resolution=t,this.log("\u2705 Client initialization successful"),t),t=>{throw this.resolution=t,this.logError("\u274C Client initialization failed:",t),t}).finally(()=>{this.disconnect()})}defineHandlers(t){return t}async startSession(t,r){try{return await this.connect(),this.emit(t,r,a=>{this.resolveInitialization(a)}),this.initializationPromise}catch(a){throw this.logError("\u274C Failed to start session:",a),this.rejectInitialization(a),a}}isConnected(){var t;return((t=this.socket)==null?void 0:t.connected)||!1}getConnectionState(){return this.connectionState}success(t){return{success:!0,data:t}}error(t){return{success:!1,error:t}}log(t,...r){this.options.verbose&&console.log(`[${this.namespace}] ${t}`,...r)}logError(t,...r){this.options.verbose&&console.error(`[${this.namespace}] ${t}`,...r)}async connect(){var t;if(this.connectionPromise)return this.connectionPromise;if(this.connectionState==="connected"&&((t=this.socket)!=null&&t.connected))return Promise.resolve();this.connectionState="connecting",this.connectionPromise=this.establishConnection();try{await this.connectionPromise,this.connectionState="connected"}catch(r){throw this.connectionState="disconnected",this.connectionPromise=null,r}return this.connectionPromise}establishConnection(){return new Promise((t,r)=>{let a=!1;try{let o=`${this.url}/${this.namespace}`;this.log(`\u{1F517} Connecting to socket at: ${o}`),this.socket=Nmt(o,{autoConnect:!0,reconnection:!0,reconnectionAttempts:C$t.RECONNECTION_ATTEMPTS,reconnectionDelay:C$t.RECONNECTION_DELAY,...this.options.path&&{path:this.options.path}}),this.setupConnectionHandlers(t,r,a)}catch(o){this.logError("\u274C Failed to create socket connection:",o),a||r(o)}})}setupConnectionHandlers(t,r,a){if(!this.socket)return;let o={resolve:t,reject:r,connectionResolved:a};this.socket.on("connect",()=>this.handleConnect(o)),this.socket.on("reconnect",()=>this.handleReconnect()),this.socket.on("connect_error",c=>this.handleConnectError(c,o)),this.socket.on("disconnect",c=>this.handleDisconnect(c,o)),this.socket.io.on("reconnect_attempt",c=>this.handleReconnectAttempt(c)),this.socket.io.on("reconnect_error",c=>this.handleReconnectError(c)),this.socket.io.on("reconnect_failed",()=>this.handleReconnectFailed(o))}handleConnect(t){this.log("\u2705 Connected to socket"),this.connectionState="connected",this.setupEventHandlers(),t.connectionResolved||(t.connectionResolved=!0,t.resolve())}handleReconnect(){this.log("\u2705 Reconnected to socket"),this.connectionState="connected"}handleConnectError(t,r){var a;this.logError("\u274C Connection error:",t),this.connectionState="disconnected",!r.connectionResolved&&((a=this.socket)==null?void 0:a.disconnected)!==!1&&(r.connectionResolved=!0,r.reject(t))}handleDisconnect(t,r){this.log("\u{1F50C} Disconnected from socket:",t),this.connectionState="disconnected",this.resolution===null&&t==="io server disconnect"&&this.rejectInitialization(t),!r.connectionResolved&&(t==="io server disconnect"||t==="transport close")&&(r.connectionResolved=!0,r.reject(new Error(t)))}handleReconnectAttempt(t){this.log(`\u{1F504} Reconnection attempt #${t}`),this.connectionState="reconnecting"}handleReconnectError(t){this.logError("\u274C Reconnection attempt failed:",t)}handleReconnectFailed(t){this.logError("\u274C All reconnection attempts failed"),this.connectionState="disconnected",this.resolution===null&&this.rejectInitialization("All reconnection attempts failed"),t.connectionResolved||(t.connectionResolved=!0,t.reject(new Error("All reconnection attempts failed")))}setupEventHandlers(){if(!this.socket){this.logError("\u274C Cannot setup event handlers: socket is null");return}this.log("\u2705 Setting up event handlers"),this.socket.on("__call",this.handleGatewayCall.bind(this))}async handleGatewayCall(t,r){this.log(`\u{1F4E5} Gateway called method: ${t.key} with args:`,t.args);try{let a=this.validateGatewayCall(t);if(a){r(a);return}let o=this.handlers[t.key];if(!o){let f=`No handler registered for method: ${t.key}`;this.logError(`\u274C ${f}`),r(this.error(f));return}let c=await o(...t.args);r(this.success(c))}catch(a){this.logError("\u274C Error handling gateway call:",a),r(this.error(a.message||"Unknown error occurred"))}}validateGatewayCall(t){return t.key?Array.isArray(t.args)?null:(this.logError("\u274C Received call with invalid args"),this.error("Args must be an array")):(this.logError("\u274C Received call with undefined key"),this.error("Key is undefined"))}emit(t,r,a){if(!this.socket){this.logError("\u274C Cannot emit: socket is null");return}this.log(`\u{1F4E4} Emitting event: ${t}`),this.socket.emit(t,r,o=>{a(o)})}disconnect(){this.connectionState!=="shutting_down"&&(this.connectionState="shutting_down",this.log("\u{1F50C} Initiating disconnect"),this.socket&&(this.socket.disconnect(),this.socket=null),this.connectionPromise=null,this.connectionState="disconnected",this.log("\u2705 Disconnected successfully"))}};e(CQr,"AbstractClient");var w$t=CQr;var u$n,c$n,l$n,p$n,f$n,d$n,D$t=class D$t extends(d$n=w$t,f$n=yj.names.getState,p$n=yj.names.invokeCode,l$n=yj.names.final_result,c$n=yj.names.wait,u$n=yj.names.getElementScreenshot,d$n){constructor(r,a){super({verbose:Xm.testRun.autoRecovery.verboseConsoleLog,url:a.config.apiURL,namespace:"auto-recovery",path:"/auto-recovery/socket.io"});this.utils=r;this.initData=a;this.stepsThoughts=[];this.handlers=this.defineHandlers({callLangChainTool:e(async(r,a)=>{if(!this[r])throw new Error(`Tool ${r} not found`);return a.thought&&this.stepsThoughts.push(a.thought),await this[r].invoke(a)},"callLangChainTool"),getStatus:e(async r=>({sessionId:r,status:"active",data:{message:"Status retrieved successfully"}}),"getStatus")});this[f$n]=R4e.buildTool(yj,yj.names.getState,async r=>this.getStateHandler(r));this[p$n]=R4e.buildTool(yj,yj.names.invokeCode,async r=>this.invokeCodeHandler(r));this[l$n]=R4e.buildTool(yj,yj.names.final_result,async r=>this.finalResultHandler(r));this[c$n]=R4e.buildTool(yj,yj.names.wait,async r=>this.waitHandler(r));this[u$n]=R4e.buildTool(yj,yj.names.getElementScreenshot,async r=>this.getElementScreenshotHandler(r))}async init(){let r={...this.initData,version:yj.version};return await this.startSession("initialize",r).catch(a=>{this.utils.analytics.ARError({error:a.message});let o="Auto-Recovery Failed";return this.utils.createChecksumStep({title:o,withError:!0}),{finalThought:o,stepsThoughts:[],result:"failed"}})}static async build(r){let a=await r.buildFallbackData();return new D$t(r,a)}async invokeCodeHandler(r){let a;return await this.utils.runConditionallyWithinStep(!0,r.thought||"Invoke Code",async()=>{try{let o=await this.utils.invokeCode(r.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),a={success:!0,invokeCodeResult:`invokeCodeResult: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}catch(o){this.utils.createChecksumStep({title:"Error while invoking code",withError:!0}),a={success:!1,invokeCodeResult:`Error while invoking code: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}}),a}async getStateHandler(r){return this.utils.createChecksumStep({title:r.thought}),this.utils.analytics.ARGetState(r.thought),{success:!0,appState:(await this.utils.buildFallbackData()).applicationState}}finalResultHandler(r){let a=r.result==="pass",o=this.initData.type==="assertion"?a?"soft_assertion":"hard_assertion":a?"finish":"failed";this.utils.analytics.ARFinalResult({finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts});let c={finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts};this.utils.addAutoRecoveryErrorToReport(r.thought,a),this.resolveInitialization(c)}async getElementScreenshotHandler(r){return{success:!0,screenshot:await this.utils.getScreenshotForElement(r.checksumId)}}async waitHandler(r){await new Promise(o=>setTimeout(o,r.time||5e3));let a=await this.utils.buildFallbackData();return{success:!0,waitResult:`waited for ${r.time} seconds, the current HTML of the application after the wait is: ${a.applicationState.reducedHTML}`}}};e(D$t,"AutoRecoveryAgent");var S$t=D$t;var m$n=require("fs"),_$n=Jp(require("path"));var wQr=class wQr extends $W{constructor(r,a){let o=$W.getCurrentTestInfo();if(!o)throw new Error("TestRunAnalytics must be initialized with testInfo before FallbackAnalytics can be used");let c=$W.getCurrentInstance();if(!c)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating FallbackAnalytics");let f=c.getTestSuiteRunInfo();super(f,$W.isolatedMode,o);this.sessionId=null;this.fallbackId=r,this.fallbackType=a}updateToSessionId(r){this.sessionId!==r&&(this.sessionId=r,this.analytics&&this.analytics.alias({userId:r,previousId:this.fallbackId}))}get tableName(){return"auto_recovery"}get metadata(){return{...super.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(r){super.trackEventWithTable(r,this.metadata,this.tableName)}setFallbackType(r){this.fallbackType=r}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(r){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...r})}ARGetState(r){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:r})}ARInvokeCode(r,a){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:r,code:a})}ARFinalResult(r){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...r})}autoRecoveryDisconnect(r){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...r})}ARFinish(r){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...r})}ARError(r){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...r})}};e(wQr,"AutoRecoveryAnalytics");var T$t=wQr;var RPe=class RPe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:b,variableStore:C}){this.page=t,this.evaluateWithChecksum=r,this.checksumPage=a,this.pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=b,this.variableStore=C,this._analytics=new T$t(this.sessionId,b.type)}static async start(t){return new RPe({...t})}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,b=!0)=>{if(!_)return"";try{return(0,m$n.readFileSync)(_,b?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:b,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:b,rrwebId:C}},t)}async getReducedHtml(t=RPe.currentChecksumId){let{reducedHTML:r,currentChecksumId:a}=await this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return RPe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async buildFallbackData(){let{reducedHTML:t,currentChecksumId:r}=await this.getReducedHtml();return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:t,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:r,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.runtimeFallbackData.testIdentification.testId,variableStore:this.variableStore.reduce((a,o)=>(a[`variablesStore.${o.name}`]=o.value,a),{})}}async scrollToElement(t){t&&await this.pageInteractor.scrollElementIntoViewByChecksumId(t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelPreset)==null?void 0:a.type)==="anthropic-vertexai"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=_$n.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return f$e.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],b=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,C=(R=t.match(b))==null?void 0:R[1];if(!C)throw new Error("Checksum ID not found in the code");let w=await this.getSelectionDataForChecksumId(C);if(!(w!=null&&w.locator)||w.invalid)throw new Error(`Locator or selector not found for checksumId: ${C}`);a=a.replace(b,w.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(H=>H.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:C,locator:w.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
1839
1839
  ${t}`)}get createChecksumStep(){return t=>this.checksumPage.createChecksumStep(t)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(t,r,a)=>this.checksumPage.runConditionallyWithinStep(t,r,a)}async getScreenshotForElement(t){var r;try{let a=await this.getSelectionDataForChecksumId(t);if(!a)throw new Error(`Locator not found for checksumId: ${t}`);let o=((r=this.arConfig.modelPreset)==null?void 0:r.type)==="anthropic-vertexai"?"jpeg":"png";return(await this.page.locator(a.selector).screenshot({type:o})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${t}`)}}get analytics(){return this._analytics}};e(RPe,"AutoRecoveryRuntimeIteratorUtils"),RPe.currentChecksumId="0";var k$t=RPe;var vJe=class vJe extends Eme{init(t){return this.initializationData=t,this}canResolve(t){return!0}get failingThought(){return this.initializationData.thoughts.failing}getRecoveryAttemptTitle(){switch(this.initializationData.type){case"action":return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`;case"assertion":return`Checksum Auto-Recovery: trying to verify assertion "${this.failingThought}"...`}}static async registerSession(t){let r=t.config.apiURL,a=t.config.apiKey;return await(await fetch(`${r}${vJe.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:a},body:JSON.stringify({appName:t.testIdentification.testFileName,fallbackData:t})})).json()}async prepareSession(t){let r=await vJe.registerSession(this.initializationData);this.utils=new k$t({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:r.arConfig,sessionId:r.sessionId,runtimeFallbackData:this.initializationData,fallbackData:t,variableStore:this.variables});try{this.agent=await S$t.build(this.utils)}catch{throw new Error("Failed to prepare ARFallback")}}async resolve(t){let r=Date.now();await this.prepareSession(t),this.utils.analytics.ARStart();let a=await this.agent.init();return this.utils.analytics.ARFinish({duration:Date.now()-r}),{fbResult:a.result,thought:a.finalThought,stepsThoughts:a.stepsThoughts,steps:[]}}};e(vJe,"ARFallback"),vJe.API_BASE_ROUTE="/auto-recovery";var tbe=vJe;var SQr=1e3*30;var Omt=class Omt extends mze{constructor(r,a="normal",o,c,f,_,b,C,w,T,k,R){var H,X,ne;super(r,T,()=>this.pageInteractor);this.page=r;this.runMode=a;this.testRunAnalytics=o;this.monitorBridge=c;this.testInfo=f;this.checksumTestId=_;this.test=b;this.options=C;this.isReplMode=w;this.config=T;this.pageInteractorAPI=k;this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.pages={};this.framesMsgBroker=new RQe;this.scriptLoadWrapper=e(async(r,a)=>(!this.isTimeMachineFrame(a)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(r,a.page())),"scriptLoadWrapper");this.scriptLoadCheck=e(async r=>r.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async r=>{await r.evaluate(async({appSpecificRules:a,esraTimeout:o,sessionRecorder:c,showFrontendLogs:f,showTMSeeker:_,filesObserver:b,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T,recordOptions:k})=>{var R;(R=window.checksum)==null||R.testGenerator.init(a,{esraTimeout:o,showFrontendLogs:f,skipElementHighlighting:!0,recordOptions:k},{assertionGenerator:!1,sessionRecorder:c,filesObserver:b,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T});try{_&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:SQr,sessionRecorder:!!(!this.isTimeMachineFrame(r)&&(this.timeMachine||this.isVTG)),showFrontendLogs:Xm.isDevMode,showTMSeeker:this.isTimeMachineFrame(r)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:this.isVTG&&!this.isTimeMachineFrame(r),nativeDialogObserver:this.isVTG&&!this.isTimeMachineFrame(r),assertionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),actionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),recordOptions:this.isVTG?this.getVTGRecordOptions():void 0}),Nv(`[init] init script loaded for ${r.page().url()}`)},"scriptLoadCallback");g$n(C.printLogs),this.isVTG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1,visualComparison:!1},useAutoRecovery:!1,useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1},P$t(this.page)),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let B=rbe({config:this.config,throwIfAuthFailed:!0}),U=this.getPlaywrightProjectConfig();if(this.pageInteractor=new ySe(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Nv,logError:Nv},{navigationTimeout:(H=U.use)==null?void 0:H.navigationTimeout,actionTimeout:(X=U.use)==null?void 0:X.actionTimeout,testAssetsDir:Tpt(Ane()),waitActionDelay:1e3},this.pageInteractorAPI,B),this.checkForActiveTracing(),this.resetFallbacks(),R&&(this.highLevelThoughts=R.highLevelThoughts??[],this.pages=R.pages??{},this.timeMachineBrowserContext=R.timeMachineBrowserContext,this.variableStore=R.variableStore),Xm.testRun.timeMachine.active){let ce=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:DAn(this.checksumTestId,this.testInfo.retry)}:{};this.timeMachine=new EUt(this.framesMsgBroker,this.injectedScriptManager,{...ce,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:Xm.testRun.timeMachine.headless,webProxy:(ne=f.project.use)==null?void 0:ne.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)}this.pages[this.getPageGuid(r)]=this.proxy}static async init(r,a,o,c,f,_,b,C,w=!1){_||(_=HOt(5),console.warn(`Checksum test id was not defined for test "${f.title}" and was auto-generated. Please replace - "${f.title}" with -
1840
1840
  test(defineChecksumTest("${f.title}", "${_}"), async ({ page }) => {...`)),o.addTestInfo(_,f.testId),C.options.useChecksumAI!==void 0&&typeof C.options.useChecksumAI=="boolean"&&(C.options.useChecksumAI={actions:C.options.useChecksumAI,assertions:!1,visualComparison:!1});let T=new l$e(C),k=new Omt(r,C.runMode,a,o,f,_,b,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:C.runMode!=="normal",useMockData:!1,printLogs:!1,...C.options},w,C,T,{variableStore:c});return b._checksum.expect.setPage(k),b._checksum.checksumAI.page=k,c.clearAll(),k.testRunAnalytics.testRunStart(),await k.asyncInit(),k.proxy}async asyncInit(r=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),r||await this.prepareForTestArtifacts();let a=yZ.resolve(__dirname,"mock-auto-heal-agent.js");await this.page.addInitScript({path:a})}async getPage(r){let a=this.page.context().pages()[r];if(!a)throw new Error(`Page with index ${r} not found`);return this.makePage(a)}async makePage(r){let a=this.getPageGuid(r);if(this.pages[a])return this.pages[a];let o=new Omt(r,this.runMode,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,pages:this.pages,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await o.asyncInit(!0),o.proxy}getTimeMachinePage(){var r;return(r=this.timeMachine)==null?void 0:r.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(r){var a;return r===((a=this.timeMachine)==null?void 0:a.getFrame())}shouldRecordRRwebEvents(){return Xm.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}getPageGuid(r){return r._guid}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var o;let a=(o=this.getPlaywrightProjectConfig().use)==null?void 0:o.trace;this.traceMode=typeof a=="string"?a:a==null?void 0:a.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async r=>{this.injectedScriptManager.onFrameNavigated(r)})}checksumSelector(r){return this.checksumStepId=r,this.options.useChecksumSelectors&&this.setSelectorFallback(r),this.proxy}checksumAI(r,a,o){let c=this.addNewThought(r,"action",!!a);return a&&typeof a=="function"?this.test.step(r,async f=>{var _;try{return o!=null&&o.withDialog&&this.pageInteractor.listenToDialog(),await a()}catch(b){if(c.children=[],!this.options.useChecksumAI.actions||o!=null&&o.withDialog||o!=null&&o.skipAIFallback)throw b;this.setAIFallback(r,"action");try{return await this.initiateFallbackSequence({type:"action",error:b,method:void 0,args:[],testInfo:this.testInfo,step:f},{fallbackTypes:[ove,tbe]})}catch(C){throw this.testRunAnalytics.testRunError({failedThought:r,error:(C==null?void 0:C.message)||"Unknown error"}),C}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(_=this.currentThought)==null?void 0:_.parent}}):(this.options.useChecksumAI.actions&&this.setAIFallback(r,"action"),this.proxy)}resolveAssetsFolder(r){return r.map(a=>yZ.join(Tpt(Ane()),a))}getRuntimeOptions(){return this.options}addPwAnnotation(r){this.testInfo.annotations.push({type:r.type,description:`
1841
1841
  ${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let b=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=b}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:SQr};this.pushFallback(this.constructFallback(Yft).init(a)),this.pushFallback(this.constructFallback(Gft).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Kft).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:SQr}))}setAIFallback(r,a){let o=this.options.useAutoRecovery,c=e(()=>{var k,R;let _=this.buildThoughtsChainForFallback(),b={title:this.testInfo.title},C={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},w={previous:_.slice(0,-1),failing:r,next:_.slice(1)},T={storyInfo:b,testIdentification:C,fallbackConfig:{arMode:(k=this.options.useChecksumAI)==null?void 0:k.arMode,overrideOptions:(R=this.options.useChecksumAI)==null?void 0:R.overrideOptions},thoughts:w,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(tbe).init(T)},"createArFallback"),f=e(()=>{var _,b;return this.constructFallback(ove).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:Xm.benchmark,arMode:(_=this.options.useChecksumAI)==null?void 0:_.arMode,overrideOptions:(b=this.options.useChecksumAI)==null?void 0:b.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(c()):this.pushFallback(f()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:Xm.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await uD(c,r.timeout),_=Date.now()-o;r instanceof ove&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof tbe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let b=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${b}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${b}`,withError:!0}),new fft(f.fbResult);if(r instanceof ove&&f.summary&&this.arSummaries.push(f.summary),r instanceof tbe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${b}`}),f.steps.length===1){let C=f.steps[0];C.thought&&(this.currentThought.thought=C.thought)}else this.currentThought.children=f.steps.map((C,w)=>({id:`${this.currentThought.id}.${w+1}`,thought:C.thought,type:C.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){Nv(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof ove);if(o){let _=o.getFailedThought(),b=this.variableStore.getActiveVariables();this.fallbacks.forEach(C=>{C.setThought(_),C.setVariables(b)})}let c=this.fallbacks.find(_=>_ instanceof tbe);if(c){let _=c.failingThought;this.fallbacks.forEach(b=>{b instanceof tbe&&b.setVariables(this.variableStore.getActiveVariables()),b.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((b,C)=>b||_ instanceof C,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let b=_==null?void 0:_.toString();b&&console.log(`Using ${b}`);let C;try{let w=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));C=!0}catch(w){if(C=!1,r.withChecksumAI&&w.message==="fetch failed")throw new Error(WSe);w instanceof fft&&w.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),b&&console.log(`Failed to use ${b}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Xft).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:yZ.basename(r)})}catch(r){Nv("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return Nv("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[Xft,Kft,Yft,Gft,ove];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"})}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=SAn(KOt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?TAn(KOt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=l3r(KOt(this.testInfo.file)),a=yZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Cz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=yZ.join(r,"tmp");(0,Cz.existsSync)(o)||(0,Cz.mkdirSync)(o);let c=(0,Cz.readFileSync)(a),f=await(0,h$n.loadAsync)(c);for(let b of Object.keys(f.files)){let C=await f.file(b).async("string"),w=yZ.join(o,b);(0,Cz.writeFileSync)(w,C),this.unzippedHarData.push(w)}let _=yZ.join(o,"test.har");if(!(0,Cz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Cz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Cz.rmSync)(yZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){Nv("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=yZ.join(IIe(Ane()),"settings.asr");if(!(0,Cz.existsSync)(r)){Nv("Could not find ASR file");return}let{ungzip:a}=c3r();try{let o=await a((0,Cz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){Nv("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(Omt,"RuntimePage");var I$t=Omt;var O$t=require("fs");var q4e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},I5s={defaultMerge:q4e.defaultMerge};function Kxa(i,t){return t}e(Kxa,"defaultMetaDataUpdater");function Yxa(i,t){return i.filter(r=>r!==void 0)}e(Yxa,"defaultFilterValues");var y$n;(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(y$n||(y$n={}));function v$n(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:eAa(i)?1:i instanceof Set?3:i instanceof Map?4:5}e(v$n,"getObjectType");function Xxa(i){let t=new Set;for(let r of i)for(let a of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(a);return t}e(Xxa,"getKeys");function Zxa(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}e(Zxa,"objectHasProperty");function x$n(i){var a;let t=0,r=(a=i[0])==null?void 0:a[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var o;do{if(r===void 0)return{done:!0,value:void 0};let c=r.next();if(c.done===!0){t+=1,r=(o=i[t])==null?void 0:o[Symbol.iterator]();continue}return{done:!1,value:c.value}}while(!0)}}}}}e(x$n,"getIterableOfIterables");var b$n=["[object Object]","[object Module]"];function eAa(i){if(!b$n.includes(Object.prototype.toString.call(i)))return!1;let{constructor:t}=i;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!b$n.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}e(eAa,"isRecord");function tAa(i,t,r){let a={};for(let o of Xxa(i)){let c=[];for(let b of i)Zxa(b,o)&&c.push(b[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=A$n(c,t,f);_!==q4e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}e(tAa,"mergeRecords$1");function rAa(i){return i.flat()}e(rAa,"mergeArrays$1");function nAa(i){return new Set(x$n(i))}e(nAa,"mergeSets$1");function iAa(i){return new Map(x$n(i))}e(iAa,"mergeMaps$1");function aAa(i){return i.at(-1)}e(aAa,"mergeOthers$1");var F$t={mergeRecords:tAa,mergeArrays:rAa,mergeSets:nAa,mergeMaps:iAa,mergeOthers:aAa};function N$t(...i){return sAa({})(...i)}e(N$t,"deepmerge");function sAa(i,t){let r=oAa(i,a);function a(...o){return A$n(o,r,t)}return e(a,"customizedDeepmerge"),a}e(sAa,"deepmergeCustom");function oAa(i,t){return{defaultMergeFunctions:F$t,mergeFunctions:{...F$t,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(F$t,r)).map(([r,a])=>a===!1?[r,F$t.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??Kxa,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??Yxa,actions:q4e}}e(oAa,"getUtils");function A$n(i,t,r){var c;let a=((c=t.filterValues)==null?void 0:c.call(t,i,r))??i;if(a.length===0)return;if(a.length===1)return DQr(a,t,r);let o=v$n(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(v$n(a[f])!==o)return DQr(a,t,r)}switch(o){case 1:return uAa(a,t,r);case 2:return cAa(a,t,r);case 3:return lAa(a,t,r);case 4:return pAa(a,t,r);default:return DQr(a,t,r)}}e(A$n,"mergeUnknowns");function uAa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===q4e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}e(uAa,"mergeRecords");function cAa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===q4e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}e(cAa,"mergeArrays");function lAa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===q4e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}e(lAa,"mergeSets");function pAa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===q4e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}e(pAa,"mergeMaps");function DQr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===q4e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}e(DQr,"mergeOthers");var E$n=!1;function g$n(i){E$n=i}e(g$n,"setLogToConsole");function Nv(...i){E$n&&console.log(...i)}e(Nv,"log");async function pTn(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():uD(o(),a,"Execution timeout")}e(pTn,"executePlaywrightMethodWithTimeout");function Bmt(i,{role:t,environment:r}={},a=!1){var _,b;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:C})=>r===C)),o||(o=(b=i.environments)==null?void 0:b.find(({default:C})=>C)),!o)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let c=o.users,f;if(c&&(t!==void 0&&(f=c.find(C=>C.role===t)),f||(f=c.find(C=>C.default))),!f)throw new Error(`User not found. Please make sure the users array for the "${o.name}" environment is properly defined in the checksum.config.ts file.`);if(r&&o.name!==r){if(a)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&f.role!==t){if(a)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:o,user:f}}e(Bmt,"resolveEnvironment");function fAa(i){let t=`${i??Ane()}/login.ts`;if(!(0,O$t.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}e(fAa,"requireLogin");async function dAa(i,t,{environment:r,user:a,config:o}){try{let c=e(()=>t(i,{environment:r,user:a,config:o}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${a!=null&&a.role?` using ${a.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,c):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checksum-ai/runtime",
3
- "version": "1.3.1",
3
+ "version": "1.3.3",
4
4
  "description": "Checksum.ai test runtime",
5
5
  "main": "index.js",
6
6
  "dependencies": {