@checksum-ai/runtime 2.0.6 → 2.0.7
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/.env +1 -1
- package/checksumlib.js +41 -41
- package/cli.js +1 -1
- package/index.js +1 -1
- package/package.json +1 -1
- package/vtg-build/asset-manifest.json +3 -3
- package/vtg-build/index.html +1 -1
- package/vtg-build/static/js/main.ea43b3f2.js +3 -0
- package/vtg-build/static/js/{main.fd8a9311.js.map → main.ea43b3f2.js.map} +1 -1
- package/vtg-pw-bridge-runner.js +1 -1
- package/vtg-build/static/js/main.fd8a9311.js +0 -3
- /package/vtg-build/static/js/{main.fd8a9311.js.LICENSE.txt → main.ea43b3f2.js.LICENSE.txt} +0 -0
package/vtg-pw-bridge-runner.js
CHANGED
|
@@ -1845,7 +1845,7 @@ ${this.executedSteps.map(c=>{switch(c.type){case"action":return c.thought;case"a
|
|
|
1845
1845
|
`)}`))}async getReductionComponents(r){var a,o;return r.interruptionEvent==="didRequestMoreItemsEvent"?{reducedHTML:(o=(a=r.payload)==null?void 0:a.promptData)==null?void 0:o.reducedHTML,reducedDomHTMLElement:this.lastReducedDOM,flashingHTML:[],elementsForNodeInterpretation:[],currentChecksumId:t_e.currentChecksumId}:this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t_e.currentChecksumId})}getErrorFileContent(r){try{let a=LLr.default.dirname(this.fallbackData.testInfo.config.configFile);return Bze.toString(r,a)}catch{throw new Error("Error while getting error file content for AI fallback")}}async getPageScreenshot(){try{return this.checksumPage.wrapInternalSteps(async()=>{var c,f;let r=await this.page.screenshot({fullPage:!0,type:((f=(c=this.arConfig)==null?void 0:c.modelPreset)==null?void 0:f.type)==="anthropic-vertexai"?"jpeg":"png"}),a=4e3;return(await(0,qRn.default)(r).resize(a,a,{fit:"inside",withoutEnlargement:!0}).toBuffer()).toString("base64")})}catch{return}}getMatcherResultFileData(){let r=this.fallbackData.error.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,b=!0)=>{if(!_)return"";try{return(0,Q0t.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 this.log("[AIFallback] No expected file found for 'toHaveScreenshot'"),new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async prepareDataForCurrentIteration(){let r=await this.getPreviousActionOverview(),a=this.getMatcherResultFileData(),{reducedHTML:o,flashingHTML:c,elementsForNodeInterpretation:f,currentChecksumId:_}=await this.getReductionComponents(r),b=await this.getPageScreenshot();this.lastReducedDOM=new URn.JSDOM(o),t_e.currentChecksumId=_;let C=(()=>{let w=this.executedSteps[this.executedSteps.length-1];if(w&&w.type==="action")return w.locator})();return{reducedHTML:o,flashingHTML:c,elementsForNodeInterpretation:f,previousActionOverview:r,screenshot:b,matcherResult:a,fallbackActionErrorMessage:this.fallbackData.error.message,locatorUsed:C}}async iterate(){this.hasPreviousActionFailed=!1;let r=this.CLIENT_MAX_ITERATIONS;for(;r-- >0;){if(this.didCancel)return this.aiFallbackAnalytics.aiFallbackEnd({result:"failed",avgDuration:0,failMessage:"User canceled"}),{result:"failed",thought:"Fallback Canceled"};let a=await this.prepareDataForCurrentIteration(),o=Date.now(),c=await this.getIterationResponse(a),f=Date.now()-o,{thought:_,command:b,changedVariables:C}=c;if(this.traceAIFallbackIterationNew({thought:_,command:b,duration:f}),this.handleChangedVariables(C),this.fallbackData.type==="assertion"){let R=c.payload;if(b==="scroll"){await this.scrollToElement(R.checksumId);continue}return this.handleAssertionResponse(R)}let w=c.payload;if(this.didCancel)return this.aiFallbackAnalytics.aiFallbackEnd({result:"failed",avgDuration:0,failMessage:"User canceled"}),{result:"failed",thought:"Fallback Canceled"};let T=this.getStopIterationResult(b);if(T)return{result:T.result,summary:w.summary??void 0,thought:_};let k=Date.now();try{let R=await this.pageInteractor.translateActionResponseToAgentPotentialAction(w);await this.executeFallbackAction(w,R),this.trackActionExecution(w,R,Date.now()-k)}catch(R){this.log("[AIFallback] Error while executing selector",R.message),this.hasPreviousActionFailed=!0,this.trackActionExecutionFailure(w,Date.now()-k,R.message);continue}}return this.errorMessage="maximum repetition reached",this.log(`[AIFallback] ${this.errorMessage}`),{result:"failed",thought:"Fallback failed to recover action"}}trackActionExecution(r,a,o){this.aiFallbackAnalytics.aiFallbackActionExecution({thought:r.thought,duration:o,command:r.action.type,checksumId:r.action.checksumid,type:r.action.type,selector:a.selector,locator:a.locator,fillValue:a.fillValue,getMoreItemsId:a.getMoreItemsId})}trackActionExecutionFailure(r,a,o){this.aiFallbackAnalytics.aiFallbackActionExecutionFailure({thought:r.thought,duration:a,command:r.action.type,checksumId:r.action.checksumid,error:o})}getStopIterationResult(r){if(r==="fail")return this.log("[AIFallback] Received fail signal, will quit"),this.errorMessage="Received fail signal",{result:"failed"};if(r==="finish")return this.log("[AIFallback] Received finish step"),{result:"finish"}}handleAssertionResponse(r){if(this.log(`[AIFallback] for assertion returned with value: ${r.command}, feedback: ${r.analysis}`),this.didCancel)return{result:"failed",thought:"Fallback Canceled"};let a=r.command,o=["irrelevant","pass","soft_reject","soft_pass","soft_assertion"].includes(r.command);this.aiFallbackAnalytics.aiFallbackAssertion({duration:0,command:r.command,thought:r.thought}),this.executedSteps.push({type:"assertion",feedback:r.analysis,response:r.command});let c={response:r.command,feedback:r.analysis};if(this.stepsPayload.push(c),r.command==="recovery"){let _={description:r.analysis,reason:r.thought};return{result:"switch_to_fallback_action",assertionToActionData:_,summary:r.summary,thought:r.thought}}return r.command==="hard_assertion"?{result:"hard_assertion",thought:r.thought}:{result:o?"soft_assertion":"failed",summary:r.summary,thought:r.thought}}async scrollToElement(r){if(!r){this.log("[AIFallback] No checksumId provided for scroll");return}await this.pageInteractor.scrollElementIntoViewByChecksumId(r),await FE(1e3)}async executeFallbackAction(r,a){let o=Date.now();try{await this.checksumPage.step(`AI: ${a.thought}`,async()=>await this.pageInteractor.performAction(a),void 0,{noLocation:!0})}catch(c){let f=Date.now()-o;throw this.aiFallbackAnalytics.aiFallbackActionExecutionFailure({thought:a.thought,command:r.action.type,duration:f,checksumId:r.action.checksumid,error:c.message}),this.fallbackData.error=c,new Error("Action failed")}this.hasPreviousActionFailed=!1,this.executedSteps.push({type:"action",...a}),this.aiFallbackAnalytics.aiFallbackActionExecution({thought:r.thought,duration:Date.now()-o,command:r.action.type,checksumId:r.action.checksumid,type:r.action.type,selector:a.selector,locator:a.locator,fillValue:a.fillValue,getMoreItemsId:a.getMoreItemsId}),this.addActionStepPayload(r,a),await FE(1e3)}addActionStepPayload(r,a){let{thought:o,action:{checksumid:c,type:f}}=r,{selector:_,locator:b,fillValue:C,getMoreItemsId:w}=a,T={thought:o,checksumid:c,type:f,selector:_,locator:b,fillValue:C,getMoreItemsId:w};return this.stepsPayload.push(T),T}handleMockServer(){return this.finish?{thought:"finish",command:"finish",payload:{thought:"finish"},changedVariables:[]}:(--this.actionsCounter===0&&(this.finish=!0),{thought:"mock-thought",changedVariables:[],command:"click",payload:{thought:"mock-thought",action:{type:"click",checksumid:"10"}}})}handleChangedVariables(r){r.forEach(({name:a,value:o})=>{this.checksumPage.variableStore.setVariable(a,o)})}async getIterationResponse({reducedHTML:r,flashingHTML:a,elementsForNodeInterpretation:o,previousActionOverview:c,screenshot:f,codeTrace:_,fallbackActionErrorMessage:b,locatorUsed:C}){let{apiKey:w}=this;if(this.mockServer)return this.handleMockServer();let T={reduction:{reducedHTML:r,flashingHTML:a,elementsForNodeInterpretation:o},currentURL:this.page.url(),previousActionOverview:c,resolvesSmartAssertion:this.withChecksumAI,variables:this.variables,screenshot:f,fallbackActionErrorMessage:b,locatorUsed:C};try{let k=await qze(async()=>await fetch(`${this.getAPIBaseURL()}/iterate`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify({appName:w,sessionId:this.sessionId,iterationData:T})}));if(k.status!==201)throw new Error("Failed to get next iteration");let R=await k.json();return this.log("[AIFallback] Received next action",R),this.sanitizeIterationResponse(R)}catch(k){throw this.log("[AIFallback] Error calling iterate",k),k}}sanitizeIterationResponse(r){var a;return this.fallbackType==="assertion"?{thought:r.thought,command:r.command,payload:r,changedVariables:r.changedVariables??[]}:{thought:r.thought,command:(a=r.action)==null?void 0:a.type,payload:r,changedVariables:r.changedVariables??[]}}async getPreviousActionOverview(){let r=await this.pageInteractor.handleFileChooserEvent();return{success:!this.hasPreviousActionFailed,...this.hasPreviousActionFailed?{failureEvent:"generalExecutionFailureError"}:{},...this.getPreviousWaitActionOverview(),...r,...await this.getPreviousGetMoreItemsActionOverview()}}getExecutedActions(){return this.executedSteps.filter(r=>r.type==="action")}async getPreviousGetMoreItemsActionOverview(){let r=this.getExecutedActions(),a=r[r.length-1];if((a==null?void 0:a.eventCode)!=="get_more_items"||!this.lastReducedDOM)return{};try{return await this.pageInteractor.addMoreItemsToDom(this.lastReducedDOM.window.document.body,a.getMoreItemsId),{interruptionEvent:"didRequestMoreItemsEvent",payload:{promptData:{reducedHTML:this.lastReducedDOM.serialize()},getMoreItemsId:a.getMoreItemsId}}}catch{return{}}}getPreviousWaitActionOverview(){var o;let r=this.getExecutedActions();if(((o=r[r.length-1])==null?void 0:o.eventCode)!=="wait")return{};let a=0;return r.slice().reverse().every(c=>c.eventCode==="wait"?(a++,!0):!1,0),{payload:{waitCount:a}}}async initSession(){let{apiKey:r,goal:a,thoughts:o}=this;if(this.log("[AIFallback] Calling init session...",{appName:r,goal:a,thoughts:o}),!r){let b="Missing Checksum API key, will not run AI fallback";throw Z5r(b),new Error(b)}if(this.mockServer){this.sessionId="mock-session-id";return}let c=this.getErrorFileContent(this.fallbackData.error),f={name:this.fallbackData.error.name??"Error",message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},_={type:this.fallbackData.type,resolveSmartAssertion:this.withChecksumAI,storyTitle:a,testSuiteId:this.testSuiteId,testId:this.testId,thoughtsAndActions:{previous:o.slice(0,Math.max(o.length-1,0)).map(b=>({thought:b})),failing:{thought:o[o.length-1]},next:[]},testFileName:this.testFile.split("/").pop()??"",error:f,errorFileContent:c,matcherResult:this.getMatcherResultFileData(),assertionToActionData:this.fallbackData.type==="recovery"||this.fallbackData.type==="action"?this.fallbackData.assertionToActionData:void 0,arMode:this.arMode,overrideOptions:this.arOverrideOptions};this.aiFallbackAnalytics.aiFallbackStart({error:this.fallbackData.error.message,failedThought:this.getFailedThought()});try{let b=await qze(async()=>await fetch(`${this.getAPIBaseURL()}/init`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify({appName:r,data:_,format:"json"})}));if(b.status!==201)throw new Error("Failed to init session after 3 retries");let{sessionId:C,arConfig:w}=await b.json();this.sessionId=C,this.arConfig=w,this.aiFallbackAnalytics.aiFallbackConfig({config:w}),this.log("[AIFallback] Session ID",this.sessionId)}catch(b){throw this.withChecksumAI&&b.message==="fetch failed"&&(this.checksumPage.step(q0t,async()=>{throw new Error(q0t)}),Z5r(q0t)),this.aiFallbackAnalytics.aiFallbackEnd({result:"failed",avgDuration:this.iterationSteps.length>0?this.iterationSteps.reduce((C,w)=>C+w.duration,0)/this.iterationSteps.length:0,failMessage:b==null?void 0:b.message}),this.log("[AIFallback] Error calling init session",b),b}}getReleaseIterationResultIfExists(r){if(this.fallbackType==="assertion"){if(r==="soft_assertion")return{result:"soft_assertion"}}else{if(r==="finish")return{result:"finish"};if(r==="fail")return{result:"failed"}}}translateExecutedActionToFallbackAction(r){return{type:"action",esraMetadata:r.esraMetadata,generatedLocator:r.locator,selector:r.selector,parentFramesSelectors:r.parentFramesSelectors,method:this.getMethodForPotentialAction(r),thought:r.thought}}getMethodForPotentialAction(r){return{name:this.actionEventCodeToMethodName[r.eventCode],args:e(()=>{switch(r.eventCode){case"click":case"double_click":return[{position:r.clickOffset}];case"drag_and_drop":return[this.pageInteractor.makeLocator(r.dropTarget.selector,r.dropTarget.parentFramesSelectors)];case"input":case"click_and_type":case"clear_and_type":case"selectoption":case"keystroke":case"navigation":return[this.pageInteractor.getActionFillValue(r,!1)];case"upload_files":return r.files;default:return}},"makeArgs")()}}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}getAnalyticsPayload(){return{fallbackType:"ai",error:this.errorMessage,thought:this.getFailedThought(),sessionId:this.sessionId,steps:this.stepsPayload.map(r=>JSON.stringify(r))}}getFailedThought(){return this.thoughts[this.thoughts.length-1]}traceAIFallbackIterationNew(r){this.aiFallbackAnalytics.aiFallbackIterationResponse({duration:r.duration,command:r.command,thought:r.thought}),this.iterationSteps.push({thought:r.thought,command:r.command,duration:r.duration})}toString(){return`Checksum AI ("${this.getFailedThought()}")`}get fallbackType(){return this.fallbackData.type}get fallbackAnalyticsPayload(){return{previousThoughts:this.thoughts,iterationSteps:this.iterationSteps}}};e(t_e,"AIFallback"),t_e.alreadyTriggered=!1,t_e.currentChecksumId="0";var MLr=t_e;var jLr=class jLr extends Wve{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/esra-fallback"}init(r){let{apiKey:a,testId:o,apiURL:c,checksumId:f,fileName:_,timeout:b}=r;return this.data={...this.data,testId:o,checksumId:f,fileName:_},this.apiKey=a,c&&(this.API_BASE_DOMAIN=c.replace(/\/$/,"")),b&&(this.timeout=b),this.checksumRootFolder=process.env.CHECKSUM_ROOT_FOLDER??bDn(xDn(this.data.fileName),this.data.fileName),this}getRecoveryAttemptTitle(r){return`Checksum auto-heal: trying to locate the element using checksumSelector("${this.data.checksumId}")...`}async sendLog(r){let a=this.getLogPayload(r);try{fetch(`${this.getAPIBaseURL()}/log`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify(a)}).catch(o=>this.log("[ESRAFallback] Error sending log"))}catch(o){this.log("[ESRAFallback] Error sending log",o)}}getLogPayload(r){let a=process.env.CHECKSUM_TEST_SUITE_ID??"",{selector:o}=r,{checksumId:c,testId:f}=this.data;return this.logPayload={testSuiteId:a,testId:f,selector:o,checksumId:c,thought:this.thought},this.logPayload}async getMetadataForTestId(){return yDn(this.checksumRootFolder,this.data.testId)}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}};e(jLr,"MetadataBaseFallback");var Vze=jLr;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends Vze{constructor(){super(...arguments);this.timeout=5*1e3}init(t){return super.init(t),this}async resolve(params){var t;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let r=await this.getMetadataForTestId();if(!(checksumId in r)||!r[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=r[checksumId].alternateLocators.locators}catch(r){throw super.log(`Could not read alternate selector metadata file, ${r.message}`),r}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(aj(locatorExpression,"this.page"));try{await dT(locator.first().waitFor({bypassChecksum:!0}),5e3),(await dT(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(a=>{elementsMap.has(a)?elementsMap.set(a,elementsMap.get(a)+1):elementsMap.set(a,1)})}catch(r){return}}));let majorityElementHandle=(t=Array.from(elementsMap.entries()))==null?void 0:t.reduce((r,a)=>r[1]>a[1]?r:a)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((r,a)=>r+a,0),elementSelector=await this.evaluateWithChecksum(async({element:r})=>window.playwright.selector(r),{element:majorityElementHandle});this.log(`Resolved alternate selector: ${elementSelector}' With majority vote of ${elementsMap.get(majorityElementHandle)} out of ${totalElements} elements`),await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(this.page.locator(elementSelector),method,args));let fallbackResult={selector:elementSelector,generatedLocator:`locator("${elementSelector}")`,esraMetadata:void 0};return this.sendLog(fallbackResult),this.logPayload=this.logPayload.concat({mejorityVote:`${elementsMap.get(majorityElementHandle)}/${totalElements}`}),this.checksumPage.addErrorMessage(params.error,`${this.thought?`"${this.thought}" auto-recovered`:"Auto-recovered"} using alternative selector "${elementSelector}"`),{steps:[{type:"action",...fallbackResult}]}}catch(r){throw new Error(`Failed to execute compound selection fallback action: ${r.message}`)}}catch(r){this.errorMessage=r.message,this.log(this.errorMessage);return}}getAnalyticsPayload(){return{fallbackType:"alternative-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum alternative selector (${this.data.checksumId})`}};e(_AlternateSelectorFallback,"AlternateSelectorFallback");var ULr=_AlternateSelectorFallback;var ama=require("@playwright/test");var sma=kf(xLt());var VRn=kf(require("path"));var QRn=!1,QLr=class QLr{constructor(t,r,a){this.frame=t;this.base=r;this.getAnalytics=a;this.LOCATORS_TIMEOUT=QRn?9999999:5e3;this.HANDLES_TIMEOUT=QRn?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;CS("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 _=>dT(_.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 dT(this.getElementHandles(t),this.HANDLES_TIMEOUT);CS(`Resolved to ${qLr(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");CS(`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)}),CS(`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(Vme),...Object.values(oze)]).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 CS(`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){CS("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=qLr(a),c=r?qLr(r):0,CS(`Handles itteration, previous: ${r?c:"-"}, current: ${o}`),c!==o&&_(),await FE(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(QLr,"CompoundSelectorLocator");var zze=QLr,qLr=e(i=>i.reduce((t,r)=>t+r.length,0),"countHandleElements");var $Lr=require("path");var $Rn=require("fs");var oma=!0,VLr=class VLr{constructor(t){this.options=t;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async t=>{let r=AI(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 FE(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 ${AI(t)}, trying again in ${a/1e3} seconds, ${r-1} retries left.`,w.message),await FE(a),this.loadScript(t,{retriesLeft:r-1,retryWaitMS:a,useWrapper:o});throw w}let f=AI(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 FE(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=AI(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?AI(t.mainFrame()):AI(t);return this.frameNavigationPromises[r]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,$Lr.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&&oma){let r=await(await fetch(this.addScriptTagOptions.url)).text(),a=(0,$Lr.join)(process.cwd(),"checksumlib.js");return(0,$Rn.writeFileSync)(a,r),{path:a}}return this.addScriptTagOptions}isFrameClosed(t){return t.isDetached()||t.page().isClosed()}};e(VLr,"InjectedScriptManager");var Jze=VLr;var HLr=class HLr{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?dT(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(t){return this.handleError(this.options.method,this.constructor.name,t)}}};e(HLr,"Action");var Tqt=HLr,GLr=class GLr extends Tqt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(GLr,"PlaywrightAction");var zLr=GLr,KLr=class KLr extends Tqt{constructor(r,a){super(r);this.pageInteractor=a}};e(KLr,"APIAction");var JLr=KLr,YLr=class YLr extends JLr{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(YLr,"CanvasClickAction");var WLr=YLr,Iqt=class Iqt{static createAction(t,r){return t.method in this.customActionMap?new this.customActionMap[t.method]({...t,timeout:15e3},r):new zLr(t)}};e(Iqt,"ActionFactory"),Iqt.customActionMap={canvasClick:WLr};var kqt=Iqt;var Fqt=class Fqt{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 Oze({apiURL:this.config.apiURL,apiKey:this.config.apiKey})}static init(t,r,a,o,c,f,_=!1){return new Fqt(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(Vme),...Object.values(oze)].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 zze(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{CS(`
|
|
1846
1846
|
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){CS("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(Vme),...Object.values(oze)].includes(a)?["or","and"].includes(a)?(CS("'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;CS("Executing",r,o);let c=r==="_expect"?"assertion":"action";c==="action"&&this.lastLocatorActionType==="action"&&(CS("Adding minimal wait between consecutive actions..."),await new Promise(_=>setTimeout(_,100))),this.lastLocatorActionType=c,CS("Running initial locator...");let f;try{return this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{CS("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{CS("[executeLocatorAction] checksum libs not loaded")}}),await kqt.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(_){CS("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 CS(`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(Fqt,"ChecksumFrame");var Pqt=Fqt;var Nqt=class Nqt{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 Jze({scriptFile:i_.checksumScript.path,scriptSource:i_.checksumScript.source,scriptURL:i_.checksumScript.url,isScriptFileAbsolute:!0,silenceLogs:!i_.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=zRn();return new Nqt(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=Pqt.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(Vme).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=>VRn.join(Y5r(s4e()),r))}compoundSelection(...t){try{return new zze(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(Nqt,"ChecksumPage");var $0t=Nqt;BQr();NI();var fbe=class fbe{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 Nh.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]=fbe.describeTool(f,_):a[c]=f}return Nh.object(a).strict()}if(t instanceof Nh.ZodArray){let a=t.element;return r&&typeof r=="object"&&r.element?Nh.array(fbe.describeTool(a,r.element)):t}return t instanceof Nh.ZodOptional?fbe.describeTool(t.unwrap(),r).optional():t instanceof Nh.ZodNullable?fbe.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],_=fbe.describeTool(f,r.params),C=IQr(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=fbe.describeTool(_,{});return IQr(e(async T=>{let k=b.parse(T);return a(k)},"validatedHandler"),{name:f.name,description:f.description,schema:b})}};e(fbe,"AbstractToolContainer");var a7e=fbe;NI();var X$t=class X$t{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 X$t(t,r)}};e(X$t,"ToolProtocol");var Y$t=X$t;var Ej=Y$t.create("v1",{readFile:Nh.object({path:Nh.string()}),getState:Nh.object({thought:Nh.string()}),invokeCode:Nh.object({code:Nh.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:Nh.string()}),wait:Nh.object({time:Nh.number().optional()}),scroll:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),final_result:Nh.object({result:Nh.enum(["pass","fail"]),thought:Nh.string(),visualAnalysis:Nh.string().optional()}),getElementScreenshot:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),analyze:Nh.object({previousImmediateSteps:Nh.string(),currentFailingStep:Nh.string(),nextImmediateSteps:Nh.string(),testStepToStopAt:Nh.string()}),think:Nh.object({thought:Nh.string()})});var YQr=kf(w$n(),1);var Lce=Object.create(null);Lce.open="0";Lce.close="1";Lce.ping="2";Lce.pong="3";Lce.message="4";Lce.upgrade="5";Lce.noop="6";var $mt=Object.create(null);Object.keys(Lce).forEach(i=>{$mt[Lce[i]]=i});var Vmt={type:"error",data:"parser error"};var zmt=e(({type:i,data:t},r,a)=>t instanceof ArrayBuffer||ArrayBuffer.isView(t)?a(r?t:"b"+S$n(t,!0).toString("base64")):a(Lce[i]+(t||"")),"encodePacket"),S$n=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 D$n(i,t){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return t(S$n(i.data,!1));zmt(i,!0,r=>{LQr||(LQr=new TextEncoder),t(LQr.encode(r))})}e(D$n,"encodePacketToBinary");var Jmt=e((i,t)=>{if(typeof i!="string")return{type:"message",data:T$n(i,t)};let r=i.charAt(0);if(r==="b"){let a=Buffer.from(i.substring(1),"base64");return{type:"message",data:T$n(a,t)}}return $mt[r]?i.length>1?{type:$mt[r],data:i.substring(1)}:{type:$mt[r]}:Vmt},"decodePacket"),T$n=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 k$n="",I$n=e((i,t)=>{let r=i.length,a=new Array(r),o=0;i.forEach((c,f)=>{zmt(c,!1,_=>{a[f]=_,++o===r&&t(a.join(k$n))})})},"encodePayload"),P$n=e((i,t)=>{let r=i.split(k$n),a=[];for(let o=0;o<r.length;o++){let c=Jmt(r[o],t);if(a.push(c),c.type==="error")break}return a},"decodePayload");function F$n(){return new TransformStream({transform(i,t){D$n(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(F$n,"createPacketEncoderStream");var MQr;function Z$t(i){return i.reduce((t,r)=>t+r.length,0)}e(Z$t,"totalLength");function eVt(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(eVt,"concatChunks");function N$n(i,t){MQr||(MQr=new TextDecoder);let r=[],a=0,o=-1,c=!1;return new TransformStream({transform(f,_){for(r.push(f);;){if(a===0){if(Z$t(r)<1)break;let b=eVt(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(Z$t(r)<2)break;let b=eVt(r,2);o=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(Z$t(r)<8)break;let b=eVt(r,8),C=new DataView(b.buffer,b.byteOffset,b.length),w=C.getUint32(0);if(w>Math.pow(2,21)-1){_.enqueue(Vmt);break}o=w*Math.pow(2,32)+C.getUint32(4),a=3}else{if(Z$t(r)<o)break;let b=eVt(r,o);_.enqueue(Jmt(c?b:MQr.decode(b),t)),a=0}if(o===0||o>i){_.enqueue(Vmt);break}}}})}e(N$n,"createPacketDecoderStream");var jQr=4;var G$n=kf(YPe(),1);var dbe=process.nextTick,Az=global,B$n="nodebuffer";function R$n(){return new UQr}e(R$n,"createCookieJar");function xva(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(xva,"parse");var qQr=class qQr{constructor(){this._cookies=new Map}parseCookies(t){t&&t.forEach(r=>{let a=xva(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(qQr,"CookieJar");var UQr=qQr;function tVt(i,...t){return t.reduce((r,a)=>(i.hasOwnProperty(a)&&(r[a]=i[a]),r),{})}e(tVt,"pick");var Ava=Az.setTimeout,Eva=Az.clearTimeout;function mbe(i,t){t.useNativeTimers?(i.setTimeoutFn=Ava.bind(Az),i.clearTimeoutFn=Eva.bind(Az)):(i.setTimeoutFn=Az.setTimeout.bind(Az),i.clearTimeoutFn=Az.clearTimeout.bind(Az))}e(mbe,"installTimerFunctions");var Cva=1.33;function L$n(i){return typeof i=="string"?wva(i):Math.ceil((i.byteLength||i.size)*Cva)}e(L$n,"byteLength");function wva(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(wva,"utf8Length");function rVt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}e(rVt,"randomString");function M$n(i){let t="";for(let r in i)i.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(i[r]));return t}e(M$n,"encode");function j$n(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(j$n,"decode");var K$n=kf(eFe(),1);var Hva=(0,K$n.default)("engine.io-client:transport"),JQr=class JQr extends Error{constructor(t,r,a){super(t),this.description=r,this.context=a,this.type="TransportError"}};e(JQr,"TransportError");var oVt=JQr,WQr=class WQr extends G$n.Emitter{constructor(t){super(),this.writable=!1,mbe(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 oVt(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):Hva("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){let r=Jmt(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=M$n(t);return r.length?"?"+r:""}};e(WQr,"Transport");var _be=WQr;var Y$n=kf(eFe(),1);var Mce=(0,Y$n.default)("engine.io-client:polling"),HQr=class HQr extends _be{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";let r=e(()=>{Mce("paused"),this.readyState="paused",t()},"pause");if(this._polling||!this.writable){let a=0;this._polling&&(Mce("we are currently polling - waiting to pause"),a++,this.once("pollComplete",function(){Mce("pre-pause polling complete"),--a||r()})),this.writable||(Mce("we are currently writing - waiting to pause"),a++,this.once("drain",function(){Mce("pre-pause writing complete"),--a||r()}))}else r()}_poll(){Mce("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){Mce("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");P$n(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Mce('ignoring poll - transport state "%s"',this.readyState))}doClose(){let t=e(()=>{Mce("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(Mce("transport open - closing"),t()):(Mce("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,I$n(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]=rVt()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}};e(HQr,"Polling");var Hmt=HQr;var tVn=kf(YPe(),1);var X$n=!1;try{X$n=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Z$n=X$n;var rVn=kf(eFe(),1);var GQr=(0,rVn.default)("engine.io-client:polling");function Gva(){}e(Gva,"empty");var KQr=class KQr 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(){GQr("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(KQr,"BaseXHR");var uVt=KQr,MJe=class MJe extends tVn.Emitter{constructor(t,r,a){super(),this.createRequest=t,mbe(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=tVt(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let a=this._xhr=this.createRequest(r);try{GQr("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))},GQr("xhr data %s",this._data),a.send(this._data)}catch(o){this.setTimeoutFn(()=>{this._onError(o)},0);return}typeof document<"u"&&(this._index=MJe.requestsCount++,MJe.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=Gva,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete MJe.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(MJe,"Request");var hbe=MJe;hbe.requestsCount=0;hbe.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",eVn);else if(typeof addEventListener=="function"){let i="onpagehide"in Az?"pagehide":"unload";addEventListener(i,eVn,!1)}}function eVn(){for(let i in hbe.requests)hbe.requests.hasOwnProperty(i)&&hbe.requests[i].abort()}e(eVn,"unloadHandler");var OTs=function(){let i=Kva({xdomain:!1});return i&&i.responseType!==null}();function Kva(i){let t=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Z$n))return new XMLHttpRequest}catch{}if(!t)try{return new Az[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}e(Kva,"newRequest");var Yva=YQr.default||YQr,XQr=class XQr extends uVt{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 hbe(a=>new Yva(a),this.uri(),t)}};e(XQr,"XHR");var jJe=XQr;var oxa=kf(sVn(),1),uxa=kf(f$r(),1),cxa=kf(m$r(),1),T$r=kf(w$r(),1),lxa=kf(nzn(),1);var izn=kf(eFe(),1);var fxa=(0,izn.default)("engine.io-client:websocket"),dxa=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",k$r=class k$r extends _be{get name(){return"websocket"}doOpen(){let t=this.uri(),r=this.opts.protocols,a=dxa?{}:tVt(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;zmt(a,this.supportsBinary,c=>{try{this.doWrite(a,c)}catch{fxa("websocket closed before onclose event")}o&&dbe(()=>{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]=rVt()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}};e(k$r,"BaseWS");var AVt=k$r,b8s=Az.WebSocket||Az.MozWebSocket;var I$r=class I$r extends AVt{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 T$r.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(I$r,"WS");var VJe=I$r;var azn=kf(eFe(),1);var a_t=(0,azn.default)("engine.io-client:webtransport"),P$r=class P$r extends _be{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(()=>{a_t("transport closed gracefully"),this.onClose()}).catch(t=>{a_t("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{let r=N$n(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=t.readable.pipeThrough(r).getReader(),o=F$n();o.readable.pipeTo(t.writable),this._writer=o.writable.getWriter();let c=e(()=>{a.read().then(({done:_,value:b})=>{if(_){a_t("session is closed");return}a_t("received chunk: %o",b),this.onPacket(b),c()}).catch(_=>{a_t("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&&dbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}};e(P$r,"WT");var zJe=P$r;var F$r={websocket:VJe,webtransport:zJe,polling:jJe};var mxa=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,_xa=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function JJe(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=mxa.exec(i||""),c={},f=14;for(;f--;)c[_xa[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=hxa(c,c.path),c.queryKey=gxa(c,c.query),c}e(JJe,"parse");function hxa(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(hxa,"pathNames");function gxa(i,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,o,c){o&&(r[o]=c)}),r}e(gxa,"queryKey");var szn=kf(YPe(),1);var ozn=kf(eFe(),1);var A7=(0,ozn.default)("engine.io-client:socket"),N$r=typeof addEventListener=="function"&&typeof removeEventListener=="function",s_t=[];N$r&&addEventListener("offline",()=>{A7("closing %d connection(s) because the network was lost",s_t.length),s_t.forEach(i=>i())},!1);var WJe=class WJe extends szn.Emitter{constructor(t,r){if(super(),this.binaryType=B$n,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=JJe(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=JJe(r.host).host);mbe(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=j$n(this.opts.query)),N$r&&(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"})},s_t.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=R$n()),this._open()}createTransport(t){A7('creating transport "%s"',t);let r=Object.assign({},this.opts.query);r.EIO=jQr,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&&WJe.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",WJe.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+=L$n(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,dbe(()=>{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),WJe.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(),N$r&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let a=s_t.indexOf(this._offlineEventListener);a!==-1&&(A7("removing listener for the 'offline' event"),s_t.splice(a,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};e(WJe,"SocketWithoutUpgrade");var aFe=WJe;aFe.protocol=jQr;var O$r=class O$r extends aFe{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;aFe.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;aFe.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(O$r,"SocketWithUpgrade");var EVt=O$r,B$r=class B$r extends EVt{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=>F$r[o]).filter(o=>!!o)),super(t,a)}};e(B$r,"Socket");var HJe=B$r;var G8s=HJe.protocol;var dzn=kf(o_t(),1);var fzn=(0,dzn.default)("socket.io-client:url");function mzn(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)||(fzn("protocol-less url %s",i),typeof r<"u"?i=r.protocol+"//"+i:i="https://"+i),fzn("parse %s",i),a=JJe(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(mzn,"url");var J$r={};nz(J$r,{Decoder:()=>V$r,Encoder:()=>$$r,PacketType:()=>BE,protocol:()=>Szn});var Czn=kf(YPe(),1);var Rxa=typeof ArrayBuffer=="function",Lxa=e(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),_zn=Object.prototype.toString,Mxa=typeof Blob=="function"||typeof Blob<"u"&&_zn.call(Blob)==="[object BlobConstructor]",jxa=typeof File=="function"||typeof File<"u"&&_zn.call(File)==="[object FileConstructor]";function c_t(i){return Rxa&&(i instanceof ArrayBuffer||Lxa(i))||Mxa&&i instanceof Blob||jxa&&i instanceof File}e(c_t,"isBinary");function u_t(i,t){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let r=0,a=i.length;r<a;r++)if(u_t(i[r]))return!0;return!1}if(c_t(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return u_t(i.toJSON(),!0);for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)&&u_t(i[r]))return!0;return!1}e(u_t,"hasBinary");function hzn(i){let t=[],r=i.data,a=i;return a.data=M$r(r,t),a.attachments=t.length,{packet:a,buffers:t}}e(hzn,"deconstructPacket");function M$r(i,t){if(!i)return i;if(c_t(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]=M$r(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]=M$r(i[a],t));return r}return i}e(M$r,"_deconstructPacket");function gzn(i,t){return i.data=j$r(i.data,t),delete i.attachments,i}e(gzn,"reconstructPacket");function j$r(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]=j$r(i[r],t);else if(typeof i=="object")for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(i[r]=j$r(i[r],t));return i}e(j$r,"_reconstructPacket");var wzn=kf(Azn(),1);var Q$r=(0,wzn.default)("socket.io-parser"),tAa=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Szn=5,BE;(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"})(BE||(BE={}));var W$r=class W$r{constructor(t){this.replacer=t}encode(t){return Q$r("encoding packet %j",t),(t.type===BE.EVENT||t.type===BE.ACK)&&u_t(t)?this.encodeAsBinary({type:t.type===BE.EVENT?BE.BINARY_EVENT:BE.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let r=""+t.type;return(t.type===BE.BINARY_EVENT||t.type===BE.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)),Q$r("encoded %j as %s",t,r),r}encodeAsBinary(t){let r=hzn(t),a=this.encodeAsString(r.packet),o=r.buffers;return o.unshift(a),o}};e(W$r,"Encoder");var $$r=W$r;function Ezn(i){return Object.prototype.toString.call(i)==="[object Object]"}e(Ezn,"isObject");var IVt=class IVt extends Czn.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===BE.BINARY_EVENT;a||r.type===BE.BINARY_ACK?(r.type=a?BE.EVENT:BE.ACK,this.reconstructor=new z$r(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(c_t(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(BE[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===BE.BINARY_EVENT||a.type===BE.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(IVt.isPayloadValid(a.type,c))a.data=c;else throw new Error("invalid payload")}return Q$r("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 BE.CONNECT:return Ezn(r);case BE.DISCONNECT:return r===void 0;case BE.CONNECT_ERROR:return typeof r=="string"||Ezn(r);case BE.EVENT:case BE.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&tAa.indexOf(r[0])===-1);case BE.ACK:case BE.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};e(IVt,"Decoder");var V$r=IVt,H$r=class H$r{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=gzn(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};e(H$r,"BinaryReconstructor");var z$r=H$r;function bZ(i,t,r){return i.on(t,r),e(function(){i.off(t,r)},"subDestroy")}e(bZ,"on");var Dzn=kf(YPe(),1),Tzn=kf(o_t(),1);var aO=(0,Tzn.default)("socket.io-client:socket"),rAa=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),G$r=class G$r extends Dzn.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=[bZ(t,"open",this.onopen.bind(this)),bZ(t,"packet",this.onpacket.bind(this)),bZ(t,"error",this.onerror.bind(this)),bZ(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(rAa.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:BE.EVENT,data:r};if(f.options={},f.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){let w=this.ids++;aO("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&&!_?aO("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&&(aO("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(_,1));aO("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&&(aO("packet [%d] is discarded after %d tries",a.id,a.tryCount),this._queue.shift(),r&&r(o)):(aO("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(aO("draining queue"),!this.connected||this._queue.length===0)return;let r=this._queue[0];if(r.pending&&!t){aO("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,aO("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(){aO("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:BE.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){aO("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 BE.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 BE.EVENT:case BE.BINARY_EVENT:this.onevent(t);break;case BE.ACK:case BE.BINARY_ACK:this.onack(t);break;case BE.DISCONNECT:this.ondisconnect();break;case BE.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||[];aO("emitting event %j",r),t.id!=null&&(aO("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,aO("sending ack %j",o),r.packet({type:BE.ACK,id:t,data:o}))}}onack(t){let r=this.acks[t.id];if(typeof r!="function"){aO("bad ack %s",t.id);return}delete this.acks[t.id],aO("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){aO("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(){aO("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&&(aO("performing disconnect (%s)",this.nsp),this.packet({type:BE.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(G$r,"Socket");var GJe=G$r;function sFe(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(sFe,"Backoff");sFe.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};sFe.prototype.reset=function(){this.attempts=0};sFe.prototype.setMin=function(i){this.ms=i};sFe.prototype.setMax=function(i){this.max=i};sFe.prototype.setJitter=function(i){this.jitter=i};var kzn=kf(YPe(),1),Izn=kf(o_t(),1);var Cj=(0,Izn.default)("socket.io-client:manager"),K$r=class K$r extends kzn.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,mbe(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 sFe({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||J$r;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(Cj("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Cj("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=bZ(r,"open",function(){a.onopen(),t&&t()}),c=e(_=>{Cj("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",_),t?t(_):this.maybeReconnectOnOpen()},"onError"),f=bZ(r,"error",c);if(this._timeout!==!1){let _=this._timeout;Cj("connect attempt will timeout after %d",_);let b=this.setTimeoutFn(()=>{Cj("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(){Cj("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let t=this.engine;this.subs.push(bZ(t,"ping",this.onping.bind(this)),bZ(t,"data",this.ondata.bind(this)),bZ(t,"error",this.onerror.bind(this)),bZ(t,"close",this.onclose.bind(this)),bZ(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){dbe(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){Cj("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){Cj("socket %s is still active, skipping close",a);return}this._close()}_packet(t){Cj("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(){Cj("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){Cj("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var a;Cj("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)Cj("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let r=this.backoff.duration();Cj("will wait %dms before reconnect attempt",r),this._reconnecting=!0;let a=this.setTimeoutFn(()=>{t.skipReconnect||(Cj("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(Cj("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):(Cj("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(K$r,"Manager");var KJe=K$r;var Fzn=kf(o_t(),1);var Pzn=(0,Fzn.default)("socket.io-client"),l_t={};function p_t(i,t){typeof i=="object"&&(t=i,i=void 0),t=t||{};let r=mzn(i,t.path||"/socket.io"),a=r.source,o=r.id,c=r.path,f=l_t[o]&&c in l_t[o].nsps,_=t.forceNew||t["force new connection"]||t.multiplex===!1||f,b;return _?(Pzn("ignoring socket cache for %s",a),b=new KJe(a,t)):(l_t[o]||(Pzn("new io instance for %s",a),l_t[o]=new KJe(a,t)),b=l_t[o]),r.query&&!t.query&&(t.query=r.queryKey),b.socket(r.path,t)}e(p_t,"lookup");Object.assign(p_t,{Manager:KJe,Socket:GJe,io:p_t,connect:p_t});var PVt={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},Y$r=class Y$r{constructor(t={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=t,this.url=t.url||PVt.URL,this.namespace=t.namespace||PVt.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,a){try{if(await this.connect(),this.emit(t,r,o=>{this.resolveInitialization(o)}),a&&a>0){let o=new Promise((c,f)=>{setTimeout(()=>{f(new Error(`Session initialization timed out after ${a}ms`))},a)});return Promise.race([this.initializationPromise,o])}return this.initializationPromise}catch(o){throw this.logError("\u274C Failed to start session:",o),this.rejectInitialization(o),o}}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=p_t(o,{autoConnect:!0,reconnection:!0,reconnectionAttempts:PVt.RECONNECTION_ATTEMPTS,reconnectionDelay:PVt.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";let a=new Error(`Socket disconnected: ${t}`);this.resolution===null&&t==="io server disconnect"&&this.rejectInitialization(a),!r.connectionResolved&&(t==="io server disconnect"||t==="transport close")&&(r.connectionResolved=!0,r.reject(a)),this.resolution===null&&this.connectionState==="disconnected"&&this.rejectInitialization(a)}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(Y$r,"AbstractClient");var FVt=Y$r;var Nzn,Ozn,Bzn,Rzn,Lzn,Mzn,OVt=class OVt extends(Mzn=FVt,Lzn=Ej.names.getState,Rzn=Ej.names.invokeCode,Bzn=Ej.names.final_result,Ozn=Ej.names.wait,Nzn=Ej.names.getElementScreenshot,Mzn){constructor(r,a){super({verbose:i_.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[Lzn]=a7e.buildTool(Ej,Ej.names.getState,async r=>this.getStateHandler(r));this[Rzn]=a7e.buildTool(Ej,Ej.names.invokeCode,async r=>this.invokeCodeHandler(r));this[Bzn]=a7e.buildTool(Ej,Ej.names.final_result,async r=>this.finalResultHandler(r));this[Ozn]=a7e.buildTool(Ej,Ej.names.wait,async r=>this.waitHandler(r));this[Nzn]=a7e.buildTool(Ej,Ej.names.getElementScreenshot,async r=>this.getElementScreenshotHandler(r))}async init(){let r={...this.initData,version:Ej.version};return await this.startSession("initialize",r).catch(a=>{this.utils.analytics.ARError({error:a.message});let o="Auto-Recovery attempt finished unsuccessfully";return this.utils.createChecksumStep({title:o,withError:!0}),this.utils.addAutoRecoveryErrorToReport(o,!1),{finalThought:o,stepsThoughts:[],result:"failed"}})}static async build(r){let a=await r.buildFallbackData();return new OVt(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){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(OVt,"AutoRecoveryAgent");var NVt=OVt;var jzn=require("fs"),Uzn=kf(require("path"));var X$r=class X$r{constructor(t,r){this.sessionId=null;if(!Zme.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let o=Zme.getCurrentInstance();if(!o)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let c=o.getTestSuiteRunInfo();this.analytics=$me.createFromConfig(c,Zme.isolatedMode,!0),this.fallbackId=t,this.fallbackType=r}updateToSessionId(t){this.sessionId!==t&&(this.sessionId=t)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}setFallbackType(t){this.fallbackType=t}aiFallbackStart(t){this.event({event:"AI Fallback Start",metadata:this.metadata,...t})}aiFallbackConfig(t){this.event({event:"AI Fallback Config",metadata:this.metadata,...t})}aiFallbackIterationResponse(t){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...t})}aiFallbackAssertion(t){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...t})}aiFallbackChangeVariable(t){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...t})}aiFallbackSummary(t){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...t})}aiFallbackActionExecution(t){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...t})}aiFallbackActionExecutionFailure(t){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...t})}aiFallbackEnd(t){this.event({event:"AI Fallback End",metadata:this.metadata,...t})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(t){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...t})}ARGetState(t){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:t})}ARInvokeCode(t,r){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:t,code:r})}ARFinalResult(t){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...t})}autoRecoveryDisconnect(t){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...t})}ARFinish(t){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...t})}ARError(t){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...t})}};e(X$r,"RecoveryAnalytics");var BVt=X$r;var oFe=class oFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:b,variableStore:C}){this.reducedHtmlTimeoutMs=3e4;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 BVt(this.sessionId,b.type)}static async start(t){return new oFe({...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,jzn.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=oFe.currentChecksumId){if(this.pageInteractor.getCurrentURL()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:t};let{reducedHTML:r,currentChecksumId:a}=await this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return oFe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async buildFallbackData(){let t=new Promise((o,c)=>setTimeout(()=>c(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:r,currentChecksumId:a}=await Promise.race([this.getReducedHtml(),t]);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:r,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:a,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((o,c)=>(o[`variablesStore.${c.name}`]=c.value,o),{}),arConfig:this.arConfig}}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.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=Uzn.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return Bze.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(W=>W.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}:
|
|
1847
1847
|
${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.modelConfig)==null?void 0:r.provider)==="anthropic"?"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(oFe,"AutoRecoveryRuntimeIteratorUtils"),oFe.currentChecksumId="0";var RVt=oFe;var xbe=class xbe extends Wve{init(t){var r;return this.initializationData=t,(r=this.initializationData.fallbackConfig).arMode??(r.arMode="fast"),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}${xbe.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 xbe.registerSession(this.initializationData);this.utils=new RVt({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 NVt.build(this.utils)}catch{throw new Error("Failed to prepare ARFallback")}}async resolve(t){let r=new Promise((o,c)=>{setTimeout(()=>{this.utils.analytics.ARError({error:`Auto-recovery timed out after ${xbe.TIMEOUT_MS/1e3} seconds`});let f="Auto-Recovery attempt finished unsuccessfully";this.utils.createChecksumStep({title:f,withError:!0}),this.utils.addAutoRecoveryErrorToReport(f,!1),c(new Error(f))},xbe.TIMEOUT_MS)}),a=Date.now();await this.prepareSession(t),this.utils.analytics.ARStart();try{let o=await Promise.race([this.agent.init(),r]);return this.utils.analytics.ARFinish({duration:Date.now()-a}),{fbResult:o.result,thought:o.finalThought,stepsThoughts:o.stepsThoughts,steps:[]}}catch(o){throw this.utils.analytics.ARFinish({duration:Date.now()-a}),o}}};e(xbe,"ARFallback"),xbe.API_BASE_ROUTE="/auto-recovery",xbe.TIMEOUT_MS=12e4;var Z$r=xbe;var NIs=1e3*30;var jVt=require("fs");var l7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},MIs={defaultMerge:l7e.defaultMerge};function aAa(i,t){return t}e(aAa,"defaultMetaDataUpdater");function sAa(i,t){return i.filter(r=>r!==void 0)}e(sAa,"defaultFilterValues");var qzn;(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"})(qzn||(qzn={}));function Qzn(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:cAa(i)?1:i instanceof Set?3:i instanceof Map?4:5}e(Qzn,"getObjectType");function oAa(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(oAa,"getKeys");function uAa(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}e(uAa,"objectHasProperty");function Vzn(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(Vzn,"getIterableOfIterables");var $zn=["[object Object]","[object Module]"];function cAa(i){if(!$zn.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"||!$zn.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}e(cAa,"isRecord");function lAa(i,t,r){let a={};for(let o of oAa(i)){let c=[];for(let b of i)uAa(b,o)&&c.push(b[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=zzn(c,t,f);_!==l7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}e(lAa,"mergeRecords$1");function pAa(i){return i.flat()}e(pAa,"mergeArrays$1");function fAa(i){return new Set(Vzn(i))}e(fAa,"mergeSets$1");function dAa(i){return new Map(Vzn(i))}e(dAa,"mergeMaps$1");function mAa(i){return i.at(-1)}e(mAa,"mergeOthers$1");var LVt={mergeRecords:lAa,mergeArrays:pAa,mergeSets:fAa,mergeMaps:dAa,mergeOthers:mAa};function MVt(...i){return _Aa({})(...i)}e(MVt,"deepmerge");function _Aa(i,t){let r=hAa(i,a);function a(...o){return zzn(o,r,t)}return e(a,"customizedDeepmerge"),a}e(_Aa,"deepmergeCustom");function hAa(i,t){return{defaultMergeFunctions:LVt,mergeFunctions:{...LVt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(LVt,r)).map(([r,a])=>a===!1?[r,LVt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??aAa,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??sAa,actions:l7e}}e(hAa,"getUtils");function zzn(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 rVr(a,t,r);let o=Qzn(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(Qzn(a[f])!==o)return rVr(a,t,r)}switch(o){case 1:return gAa(a,t,r);case 2:return yAa(a,t,r);case 3:return vAa(a,t,r);case 4:return bAa(a,t,r);default:return rVr(a,t,r)}}e(zzn,"mergeUnknowns");function gAa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===l7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}e(gAa,"mergeRecords");function yAa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===l7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}e(yAa,"mergeArrays");function vAa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===l7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}e(vAa,"mergeSets");function bAa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===l7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}e(bAa,"mergeMaps");function rVr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===l7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}e(rVr,"mergeOthers");var xAa=!1;function CS(...i){xAa&&console.log(...i)}e(CS,"log");async function LRn(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():dT(o(),a,"Execution timeout")}e(LRn,"executePlaywrightMethodWithTimeout");function nVr(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(nVr,"resolveEnvironment");function AAa(i){let t=`${i??s4e()}/login.ts`;if(!(0,jVt.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(AAa,"requireLogin");async function EAa(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:
|
|
1848
|
-
`,c),c}}e(EAa,"proceedWithLogin");function eVr(i){let{config:t,folder:r,throwIfAuthFailed:a}=i,o=AAa(r);return async(c,{role:f,environment:_}={})=>{let{environment:b,user:C}=nVr(t,{role:f,environment:_},i.throwIfEnvInfoInvalid);if(a&&!C)throw new Error("Could not find user credentials matching the provided role and/or environment");await EAa(c,o,{environment:b,user:C,config:t})}}e(eVr,"makeUnboundLogin");var YJe;function zRn(){if(YJe)return YJe;try{let i=(0,jVt.existsSync)(`${s4e()}/checksum.config.ts`)?"checksum.config.ts":(0,jVt.existsSync)(`${s4e()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return Jzn(require(`${s4e()}/${i}`).default)}catch{console.warn("Could not find checksum config file, will run with defaults")}return Jzn()}e(zRn,"loadChecksumConfig");function Jzn(i={}){var r,a,o,c;let t={apiKey:void 0,runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return((a=(r=i.options)==null?void 0:r.useChecksumAI)==null?void 0:a.visualComparison)===void 0&&((c=(o=i.options)==null?void 0:o.useChecksumAI)!=null&&c.assertions)&&(i.options.useChecksumAI.visualComparison=!0),YJe=MVt(t,i),i_.testRun.disableAutoRecovery&&(YJe.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),i_.testRun.disableHostReports&&(YJe.options.hostReports=!1),YJe}e(Jzn,"getChecksumConfig");function tVr(i){let t=e(r=>{r.on("dialog",a=>{})},"makeDialogHandler");i.context().pages().forEach(t),i.context().on("page",r=>{t(r)})}e(tVr,"preventDialogAutoDismissal");var q0t="Checksum failed connecting to the server";var Wzn=".chk";var iVr=class iVr{constructor(t,r=!1,a){this.args=t;this.debugMode=r;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=e(t=>{console.log("\x1B[31m%s\x1B[0m",t,"\x1B[0m")},"printError");this.processConfigArg(),["exit","SIGINT","SIGTERM","uncaughtException"].forEach(o=>{process.on(o,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion(),a!=null&&a.skipChecksumDataLoad||this.loadChecksumData(a)}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{let t=i_.isRepoMode?(0,MI.join)(i_.runtimeRoot,"package","package.json"):"./package.json";return require(t).version}catch{return"unknown"}}getInternalFilesDirPath(){return(0,MI.join)(this.checksumRoot,Wzn)}createInternalFilesDir(){let t=this.getInternalFilesDirPath();if((0,jI.existsSync)(t)){CS("Internal files directory already exists at",t);return}(0,jI.mkdirSync)(t,{recursive:!0}),CS("Internal files directory created at",t)}loadTracer(){this.runtimeAnalytics=EUt.getInstance({version:this.checksumRuntimeVersion},this.debugMode)}async execCmd(t,r={}){let a={...process.env,...r},o=await qVt.spawn(t,{env:a,shell:!0,stdio:"inherit"});return this.childProcesses.push(o),new Promise((f,_)=>{o.on("exit",b=>{b===0?f(!0):_(new Error(`Checksum failed execution with code: ${b} `)),this.childProcesses=this.childProcesses.filter(C=>C!==o)})})}async getCmdOutput(t){return new Promise(function(r,a){qVt.exec(t,(o,c,f)=>{if(o){a(`Error executing command: ${o.message}`);return}r(c.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let t=(0,MI.join)(this.checksumRoot,".auth");(0,jI.existsSync)(t)||(0,jI.writeFileSync)(t,"{}")}loadChecksumData(t={}){this.locateChecksumLibs(),this.loadChecksumConfig(t)}async patchPlaywright(t=!1){CS("Patching playwright",t);let r=(0,MI.join)(__dirname,"./scripts/patch.js");(0,jI.existsSync)(r)||(r=(0,MI.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let a=`node "${r}"${t?" off":""}`;try{await this.execCmd(a,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(o){console.log("Error patching playwright",o.message)}}async promptKillActivePlaywrightProcesses(){try{let t;try{t=await this.getCmdOutput('ps aux | grep "playwright test" | grep -v grep')}catch{return}if(!t)return;let r=t.split(`
|
|
1848
|
+
`,c),c}}e(EAa,"proceedWithLogin");function eVr(i){let{config:t,folder:r,throwIfAuthFailed:a}=i,o=AAa(r);return async(c,{role:f,environment:_}={})=>{let{environment:b,user:C}=nVr(t,{role:f,environment:_},i.throwIfEnvInfoInvalid);if(a&&!C)throw new Error("Could not find user credentials matching the provided role and/or environment");await EAa(c,o,{environment:b,user:C,config:t})}}e(eVr,"makeUnboundLogin");var YJe;function zRn(){if(YJe)return YJe;try{let i=(0,jVt.existsSync)(`${s4e()}/checksum.config.ts`)?"checksum.config.ts":(0,jVt.existsSync)(`${s4e()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return Jzn(require(`${s4e()}/${i}`).default)}catch{console.warn("Could not find checksum config file, will run with defaults")}return Jzn()}e(zRn,"loadChecksumConfig");function Jzn(i={}){var r,a,o,c;let t={apiKey:void 0,runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1,skipTestsWithKnownBugs:!0},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return((a=(r=i.options)==null?void 0:r.useChecksumAI)==null?void 0:a.visualComparison)===void 0&&((c=(o=i.options)==null?void 0:o.useChecksumAI)!=null&&c.assertions)&&(i.options.useChecksumAI.visualComparison=!0),YJe=MVt(t,i),i_.testRun.disableAutoRecovery&&(YJe.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),i_.testRun.disableHostReports&&(YJe.options.hostReports=!1),YJe}e(Jzn,"getChecksumConfig");function tVr(i){let t=e(r=>{r.on("dialog",a=>{})},"makeDialogHandler");i.context().pages().forEach(t),i.context().on("page",r=>{t(r)})}e(tVr,"preventDialogAutoDismissal");var q0t="Checksum failed connecting to the server";var Wzn=".chk";var iVr=class iVr{constructor(t,r=!1,a){this.args=t;this.debugMode=r;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=e(t=>{console.log("\x1B[31m%s\x1B[0m",t,"\x1B[0m")},"printError");this.processConfigArg(),["exit","SIGINT","SIGTERM","uncaughtException"].forEach(o=>{process.on(o,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion(),a!=null&&a.skipChecksumDataLoad||this.loadChecksumData(a)}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{let t=i_.isRepoMode?(0,MI.join)(i_.runtimeRoot,"package","package.json"):"./package.json";return require(t).version}catch{return"unknown"}}getInternalFilesDirPath(){return(0,MI.join)(this.checksumRoot,Wzn)}createInternalFilesDir(){let t=this.getInternalFilesDirPath();if((0,jI.existsSync)(t)){CS("Internal files directory already exists at",t);return}(0,jI.mkdirSync)(t,{recursive:!0}),CS("Internal files directory created at",t)}loadTracer(){this.runtimeAnalytics=EUt.getInstance({version:this.checksumRuntimeVersion},this.debugMode)}async execCmd(t,r={}){let a={...process.env,...r},o=await qVt.spawn(t,{env:a,shell:!0,stdio:"inherit"});return this.childProcesses.push(o),new Promise((f,_)=>{o.on("exit",b=>{b===0?f(!0):_(new Error(`Checksum failed execution with code: ${b} `)),this.childProcesses=this.childProcesses.filter(C=>C!==o)})})}async getCmdOutput(t){return new Promise(function(r,a){qVt.exec(t,(o,c,f)=>{if(o){a(`Error executing command: ${o.message}`);return}r(c.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let t=(0,MI.join)(this.checksumRoot,".auth");(0,jI.existsSync)(t)||(0,jI.writeFileSync)(t,"{}")}loadChecksumData(t={}){this.locateChecksumLibs(),this.loadChecksumConfig(t)}async patchPlaywright(t=!1){CS("Patching playwright",t);let r=(0,MI.join)(__dirname,"./scripts/patch.js");(0,jI.existsSync)(r)||(r=(0,MI.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let a=`node "${r}"${t?" off":""}`;try{await this.execCmd(a,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(o){console.log("Error patching playwright",o.message)}}async promptKillActivePlaywrightProcesses(){try{let t;try{t=await this.getCmdOutput('ps aux | grep "playwright test" | grep -v grep')}catch{return}if(!t)return;let r=t.split(`
|
|
1849
1849
|
`).map(o=>{let[c,f]=o.split(/\s+/);return f}).filter(o=>o&&!isNaN(Number(o)));if(r.length===0)return;let a=await T9r({message:"Existing playwright processes detected. Do you want to kill them?",choices:[{name:"Yes (kill them all\u{1F918})",value:"all"},{name:"No",value:"no"},...r.map(o=>({name:o,value:o}))]});if(a==="no")return;a==="all"?r.forEach(o=>{this.execCmd(`kill -9 ${o}`)}):this.execCmd(`kill -9 ${a}`)}catch(t){console.log("Error detecting playwright processes",t)}}getPlaywrightConfigFilePath(){return(0,MI.join)(this.checksumRoot,"playwright.config.ts")}buildVolatileChecksumConfig(){if(!this.volatileChecksumConfig)return;let t=this.getVolatileConfigPath(),r=`
|
|
1850
1850
|
import { RunMode, getChecksumConfig } from "@checksum-ai/runtime";
|
|
1851
1851
|
|