@checksum-ai/runtime 2.0.19-beta → 2.0.19

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.
@@ -637,10 +637,10 @@ Result: ${JSON.stringify(w)}`);else C=w;let k;h7e(t)&&(k=t.id),!k&&r$n(f)&&(k=f.
637
637
 
638
638
  `),c=`Available pages (${a.length}):
639
639
 
640
- ${o}`;return{success:!0,pages:a,message:c}}async switchPageHandler(r){if(!r.pageId)return{success:!1,message:"pageId is required"};r.thought&&this.utils.createChecksumStep({title:r.thought});try{await this.utils.setActivePage(r.pageId);let a=await this.utils.captureApplicationState();return{success:!0,activePageId:r.pageId,message:`Successfully switched to page ${r.pageId}`,appState:a}}catch(a){let o=a instanceof Error?a.message:String(a);return{success:!1,activePageId:this.utils.activePageGuid,message:`Failed to switch to page ${r.pageId}: ${o}`}}}};e(Bzt,"AutoRecoveryAgent");Ozt=Bzt});var Nzr,Rzt,CHn=Vt(()=>{"use strict";AMr();I0t();Nzr=class Nzr{constructor(t,r){this.sessionId=null;if(!l_e.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let o=l_e.getCurrentInstance();if(!o)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let c=o.getTestSuiteRunInfo();this.analytics=e_e.createFromConfig(c,l_e.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(Nzr,"RecoveryAnalytics");Rzt=Nzr});var SHn=Vt(()=>{"use strict"});function Ozr(i){return i._guid}var DHn,THn,TFe,Lzt,kHn=Vt(()=>{"use strict";xMr();DHn=require("fs"),THn=hf(require("path"));CHn();SHn();e(Ozr,"getPageGuid");TFe=class TFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:v,variableStore:w,runtimePage:C,context:T}){this.reducedHtmlTimeoutMs=3e4;this.page=t,this._originalPage=t,this.evaluateWithChecksum=r,this.checksumPage=a,this._pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=v,this.variableStore=w,this.runtimePage=C,this.context=T,this._activePageGuid=Ozr(this.page),this._analytics=new Rzt(this.sessionId,v.type)}get activePageGuid(){return this._activePageGuid}static async start(t){return new TFe({...t})}async evaluateOnCurrentPage(t,r){return this.page!==this._originalPage?this.page.evaluate(t,r):this.evaluateWithChecksum(t,r)}async getPageById(t){return(this.context||this.page.context()).pages().find(o=>Ozr(o)===t)}async setActivePage(t){let r=await this.getPageById(t);if(!r||r.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);this.page=r,this._activePageGuid=t}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,v=!0)=>{if(!_)return"";try{return(0,DHn.readFileSync)(_,v?"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.evaluateOnCurrentPage(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:v,rrwebId:w}=await window.checksum.testGenerator.getSelectorForChecksumId(a),C=await window.checksum.testGenerator.getElementForChecksumId(a),T=C instanceof HTMLOptionElement&&C.value?C.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:v,rrwebId:w}},t)}async getReducedHtml(t=TFe.currentChecksumId,r=3){if(this.page.url()==="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};try{let a=await this.evaluateOnCurrentPage(async o=>window.checksum.testGenerator.reduceHTML({},o),{initialChecksumId:t,stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0});return TFe.currentChecksumId=a.currentChecksumId,{reducedHTML:a.reducedHTML,currentChecksumId:a.currentChecksumId}}catch(a){if(r>0)return await new Promise(c=>setTimeout(c,2e3)),this.getReducedHtml(t,r-1);let o=a instanceof Error?a.message:String(a);return{reducedHTML:`Unable to extract page DOM at ${this.page.url()}. Error: ${o}`,currentChecksumId:t}}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async capturePageState(t,r){let a=this.page,o=this._activePageGuid;try{this.page=t,this._activePageGuid=r;let{reducedHTML:c}=await this.getReducedHtml(),f=await this.getPageScreenshot();return{pageId:r,reducedHTML:c,screenshot:f,url:t.url()}}finally{this.page=a,this._activePageGuid=o}}async captureAllPagesState(){let r=(this.context||this.page.context()).pages(),a=[],o=[];for(let f of r){if(f.isClosed())continue;let _=Ozr(f);try{let v=await this.capturePageState(f,_);a.push(v)}catch(v){let w=v instanceof Error?v.message:String(v);o.push({pageId:_,url:f.url(),error:w}),console.warn(`Failed to capture state for page ${_} (${f.url()}):`,v)}}let c={pages:a};return o.length>0&&(c.failures=o),c}async captureApplicationState(t,r){if(r)return await this.captureAllPagesState();if(t&&t!==this._activePageGuid){let a=await this.getPageById(t);if(!a||a.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);let o=await this.capturePageState(a,t);return{reducedHTML:o.reducedHTML,screenshot:o.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let r=(this.context||this.page.context()).pages().filter(f=>!f.isClosed()).length,a=new Promise((f,_)=>setTimeout(()=>_(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:o,currentChecksumId:c}=await Promise.race([this.getReducedHtml(),a]);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:o,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:c,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((f,_)=>(f[`variablesStore.${_.name}`]=_.value,f),{}),arConfig:this.arConfig,multiPageContext:{pageCount:r,hasMultiplePages:r>1}}}async scrollToElement(t){t&&await this.evaluateOnCurrentPage(async r=>{let a=document.querySelector(`[checksumid="${r}"]`);a==null||a.scrollIntoView({block:"center"})},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=THn.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return oJe.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],v=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,w=(R=t.match(v))==null?void 0:R[1];if(!w)throw new Error("Checksum ID not found in the code");let C=await this.getSelectionDataForChecksumId(w);if(!(C!=null&&C.locator)||C.invalid)throw new Error(`Locator or selector not found for checksumId: ${w}`);a=a.replace(v,C.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:w,locator:C.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}:
640
+ ${o}`;return{success:!0,pages:a,message:c}}async switchPageHandler(r){if(!r.pageId)return{success:!1,message:"pageId is required"};r.thought&&this.utils.createChecksumStep({title:r.thought});try{await this.utils.setActivePage(r.pageId);let a=await this.utils.captureApplicationState();return{success:!0,activePageId:r.pageId,message:`Successfully switched to page ${r.pageId}`,appState:a}}catch(a){let o=a instanceof Error?a.message:String(a);return{success:!1,activePageId:this.utils.activePageGuid,message:`Failed to switch to page ${r.pageId}: ${o}`}}}};e(Bzt,"AutoRecoveryAgent");Ozt=Bzt});var Nzr,Rzt,CHn=Vt(()=>{"use strict";AMr();I0t();Nzr=class Nzr{constructor(t,r){this.sessionId=null;if(!l_e.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let o=l_e.getCurrentInstance();if(!o)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let c=o.getTestSuiteRunInfo();this.analytics=e_e.createFromConfig(c,l_e.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(Nzr,"RecoveryAnalytics");Rzt=Nzr});var SHn=Vt(()=>{"use strict"});function Ozr(i){return i._guid}var DHn,THn,TFe,Lzt,kHn=Vt(()=>{"use strict";xMr();DHn=require("fs"),THn=hf(require("path"));CHn();SHn();e(Ozr,"getPageGuid");TFe=class TFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:v,variableStore:w,runtimePage:C,context:T}){this.reducedHtmlTimeoutMs=3e4;this.page=t,this._originalPage=t,this.evaluateWithChecksum=r,this.checksumPage=a,this._pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=v,this.variableStore=w,this.runtimePage=C,this.context=T,this._activePageGuid=Ozr(this.page),this._analytics=new Rzt(this.sessionId,v.type)}get activePageGuid(){return this._activePageGuid}static async start(t){return new TFe({...t})}async evaluateOnCurrentPage(t,r){return this.page!==this._originalPage?this.page.evaluate(t,r):this.evaluateWithChecksum(t,r)}async getPageById(t){return(this.context||this.page.context()).pages().find(o=>Ozr(o)===t)}async setActivePage(t){let r=await this.getPageById(t);if(!r||r.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);this.page=r,this._activePageGuid=t}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,v=!0)=>{if(!_)return"";try{return(0,DHn.readFileSync)(_,v?"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.evaluateOnCurrentPage(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:v,rrwebId:w}=await window.checksum.testGenerator.getSelectorForChecksumId(a),C=await window.checksum.testGenerator.getElementForChecksumId(a),T=C instanceof HTMLOptionElement&&C.value?C.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:v,rrwebId:w}},t)}async getReducedHtml(t=TFe.currentChecksumId,r=3){if(this.page.url()==="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};try{let a=await this.evaluateOnCurrentPage(async o=>window.checksum.testGenerator.reduceHTML({},o),{initialChecksumId:t,stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0});return TFe.currentChecksumId=a.currentChecksumId,{reducedHTML:a.reducedHTML,currentChecksumId:a.currentChecksumId}}catch(a){if(r>0)return await new Promise(c=>setTimeout(c,2e3)),this.getReducedHtml(t,r-1);let o=a instanceof Error?a.message:String(a);return{reducedHTML:`Unable to extract page DOM at ${this.page.url()}. Error: ${o}`,currentChecksumId:t}}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async capturePageState(t,r){let a=this.page,o=this._activePageGuid;try{this.page=t,this._activePageGuid=r;let{reducedHTML:c}=await this.getReducedHtml(),f=await this.getPageScreenshot();return{pageId:r,reducedHTML:c,screenshot:f,url:t.url()}}finally{this.page=a,this._activePageGuid=o}}async captureAllPagesState(){let r=(this.context||this.page.context()).pages(),a=[],o=[];for(let f of r){if(f.isClosed())continue;let _=Ozr(f);try{let v=await this.capturePageState(f,_);a.push(v)}catch(v){let w=v instanceof Error?v.message:String(v);o.push({pageId:_,url:f.url(),error:w}),console.warn(`Failed to capture state for page ${_} (${f.url()}):`,v)}}let c={pages:a};return o.length>0&&(c.failures=o),c}async captureApplicationState(t,r){if(r)return await this.captureAllPagesState();if(t&&t!==this._activePageGuid){let a=await this.getPageById(t);if(!a||a.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);let o=await this.capturePageState(a,t);return{reducedHTML:o.reducedHTML,screenshot:o.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let r=(this.context||this.page.context()).pages().filter(f=>!f.isClosed()).length,a=new Promise((f,_)=>setTimeout(()=>_(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:o,currentChecksumId:c}=await Promise.race([this.getReducedHtml(),a]);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:o,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:c,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((f,_)=>(f[`variablesStore.${_.name}`]=_.value,f),{}),arConfig:this.arConfig,multiPageContext:{pageCount:r,hasMultiplePages:r>1}}}async scrollToElement(t){t&&await this.evaluateOnCurrentPage(async r=>{let a=document.querySelector(`[checksumid="${r}"]`);a==null||a.scrollIntoView({block:"center"})},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=THn.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return oJe.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],v=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,w=(R=t.match(v))==null?void 0:R[1];if(!w)throw new Error("Checksum ID not found in the code");let C=await this.getSelectionDataForChecksumId(w);if(!(C!=null&&C.locator)||C.invalid)throw new Error(`Locator or selector not found for checksumId: ${w}`);a=a.replace(v,C.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:w,locator:C.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=>{f!=null&&f.stepId&&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}:
641
641
  ${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}get pageInteractor(){return this._pageInteractor}};e(TFe,"AutoRecoveryRuntimeIteratorUtils"),TFe.currentChecksumId="0";Lzt=TFe});var Lbe,Mbe,IHn=Vt(()=>{"use strict";Ume();bmt();wHn();kHn();Q9e();Lbe=class Lbe extends f_e{constructor(t,r,a,o,c,f,_){super(t,r,a,o,c,f,_),this.runtimePageContext=f}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}${Lbe.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 Lbe.registerSession(this.initializationData);this.utils=new Lzt({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,runtimePage:this.runtimePageContext,context:this.context});try{this.agent=await Ozt.build(this.utils)}catch(a){let o=a instanceof Error?a.message:String(a),c=a instanceof Error?a.stack:void 0;throw new Error(`Failed to prepare ARFallback: ${o}`)}}async resolve(t){let r=null,a=new Promise((c,f)=>{r=setTimeout(()=>{r=null,this.utils.analytics.ARError({error:`Auto-recovery timed out after ${Lbe.TIMEOUT_MS/1e3} seconds`});let _="Auto-Recovery attempt finished unsuccessfully";this.utils.createChecksumStep({title:_,withError:!0}),this.utils.addAutoRecoveryErrorToReport(_,!1),f(new Error(_))},Lbe.TIMEOUT_MS)}),o=Date.now();await this.prepareSession(t),this.utils.analytics.ARStart();try{let c=await Promise.race([this.agent.init(),a]);return r!==null&&(clearTimeout(r),r=null),this.utils.analytics.ARFinish({duration:Date.now()-o}),{fbResult:c.result,thought:c.finalThought,stepsThoughts:c.stepsThoughts,steps:[]}}catch(c){throw r!==null&&(clearTimeout(r),r=null),this.utils.analytics.ARFinish({duration:Date.now()-o}),c}}};e(Lbe,"ARFallback"),Lbe.API_BASE_ROUTE="/auto-recovery",Lbe.TIMEOUT_MS=12e4;Mbe=Lbe});var PHn,FHn=Vt(()=>{"use strict";PHn=e(i=>{let t=i.info();return t.annotations.some(r=>r.type==="bug")||t.tags.some(r=>r==="@bug")},"isKnownBugTest")});var NHn={};cj(NHn,{VtgUserStoryService:()=>Y_t});var Bzr,Y_t,Rzr=Vt(()=>{"use strict";N8();yie();MC();Bzr=class Bzr{constructor(t,r){this.apiService=t;this.config=r}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){return!!this.userStoryTestGeneration}async fetchStory(t){if(Pm.vtg.useFakeStory){this.story={...Pm.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},uf.info("Using fake flow data",this.story);return}if(!t)throw new Error("no story id provided");try{let a=await(await this.apiService.post(`test-generation/info/${t}`)).json();if(!(a!=null&&a.id))throw new Error(`Story ${t} not found`);let{id:o,title:c,steps:f,startUrl:_,userRole:v,environment:w,internalTestId:C,version:T,collectionName:k}=a;this.story={id:o,goal:c,instructions:f,url:_,internalTestId:C,environment:{userRole:v,name:w},version:T,collectionName:k}}catch(r){throw uf.error(`Error fetching story by id ${t}:`,r),new Error(`Couldn't fetch story by id ${t}. Make sure the server is running and the story id is correct. Original error: ${JSON.stringify(r)}`)}}getEnvInfo(){return Lzr(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let t=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.story.internalTestId}),{testGenerationId:r}=await t.json();return this.userStoryTestGeneration={testGenerationId:r},this.userStoryTestGeneration}setTestGenerationData(t){this.userStoryTestGeneration=t}};e(Bzr,"VtgUserStoryService");Y_t=Bzr});var Mzr,Mzt,OHn=Vt(()=>{"use strict";Mzr=class Mzr{constructor(t,r){this.config=t;this.baseURL=t.apiURL+r}getBaseURL(){return this.baseURL}get(t){let r=`${this.baseURL}/${t}`;return fetch(r,{method:"GET",headers:{ChecksumAppCode:this.config.apiKey}})}put(t,r){return fetch(`${this.baseURL}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:r?JSON.stringify(r):void 0})}post(t,r){return fetch(`${this.baseURL}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:r?JSON.stringify(r):void 0})}delete(t){return fetch(`${this.baseURL}/${t}`,{method:"DELETE",headers:{ChecksumAppCode:this.config.apiKey}})}putFile(t,r){return fetch(t,{method:"PUT",headers:{"Content-Type":r.type},body:r})}};e(Mzr,"RuntimeAPIService");Mzt=Mzr});var BHn={};cj(BHn,{VtgCloudAPIService:()=>X_t});var jzr,X_t,Uzr=Vt(()=>{"use strict";OHn();jzr=class jzr extends Mzt{constructor(r){super(r,"/client-api/runtime");this.config=r}};e(jzr,"VtgCloudAPIService");X_t=jzr});var Sz,LHn,CZ,qzr,jbe,RHn,MHn=Vt(()=>{"use strict";fD();ENn();fie();Q9e();w4e();mMt();Ume();ARr();Sz=require("fs"),LHn=hf(fMr()),CZ=hf(require("path"));YLn();yMr();N8();$Mn();VMn();zMn();JMn();WMn();XMn();yie();djr();IHn();nVr();FHn();qzr=1e3*30,jbe=class jbe extends vJe{constructor(r,a="normal",o,c,f,_,v,w,C,T,k,R,B){var X,ne,ce;super(r,o,k,()=>this.pageInteractor,void 0);this.page=r;this.runMode=a;this.testRunAnalytics=c;this.monitorBridge=f;this.testInfo=_;this.checksumTestId=v;this.test=w;this.options=C;this.isReplMode=T;this.config=k;this.pageInteractorAPI=R;this.lastInteractionTime=Date.now();this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.framesMsgBroker=new Fze;this.previousSteps=[];this.scriptLoadWrapper=e(async(r,a)=>(!this.isTimeMachineFrame(a)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(r,a.page())),"scriptLoadWrapper");this.scriptLoadCheck=e(async r=>r.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async r=>{await r.evaluate(async({appSpecificRules:a,esraTimeout:o,sessionRecorder:c,showFrontendLogs:f,showTMSeeker:_,filesObserver:v,nativeDialogObserver:w,assertionsObserver:C,actionsObserver:T,recordOptions:k})=>{var R;(R=window.checksum)==null||R.testGenerator.init(a,{esraTimeout:o,showFrontendLogs:f,skipElementHighlighting:!0,recordOptions:k},{assertionGenerator:!1,sessionRecorder:c,filesObserver:v,nativeDialogObserver:w,assertionsObserver:C,actionsObserver:T});try{_&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:qzr,sessionRecorder:!!(!this.isTimeMachineFrame(r)&&(this.timeMachine||this.isVTG)),showFrontendLogs:Pm.isDevMode,showTMSeeker:this.isTimeMachineFrame(r)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:this.isVTG&&!this.isTimeMachineFrame(r),nativeDialogObserver:this.isVTG&&!this.isTimeMachineFrame(r),assertionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),actionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),recordOptions:this.isVTG?this.getVTGRecordOptions():void 0}),ix(`[init] init script loaded for ${r.page().url()}`)},"scriptLoadCallback");jHn(C.printLogs),this.isVTG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1,arVersion:1,visualComparison:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1},Uzt(this.page)),PHn(w)&&this.config.options.useChecksumAI.skipTestsWithKnownBugs&&(console.log("Auto recovery will not run for this test as it is marked as a known bug"),this.config.options.useChecksumAI.actions=!1,this.config.options.useChecksumAI.assertions=!1,this.config.options.useChecksumAI.visualComparison=!1),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let U=jzt({config:this.config,throwIfAuthFailed:!0}),W=this.getPlaywrightProjectConfig();if(this.pageInteractor=new qve(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:ix,logError:ix},{navigationTimeout:(X=W.use)==null?void 0:X.navigationTimeout,actionTimeout:(ne=W.use)==null?void 0:ne.actionTimeout,testAssetsDir:Ldt(Gne()),waitActionDelay:1e3},this.pageInteractorAPI,U),this.checkForActiveTracing(),this.resetFallbacks(),B&&(this.highLevelThoughts=B.highLevelThoughts??[],this.timeMachineBrowserContext=B.timeMachineBrowserContext,this.variableStore=B.variableStore),Pm.testRun.timeMachine.active){let fe=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:sTn(this.checksumTestId,this.testInfo.retry)}:{};this.isVTG||(this.timeMachine=new bQt(this.framesMsgBroker,this.injectedScriptManager,{...fe,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:Pm.testRun.timeMachine.headless,webProxy:(ce=_.project.use)==null?void 0:ce.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext))}}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(r,a,o,c,f,_,v,w,C,T=!1){let k=!1;v||(v=await jbe.fetchVtgInternalTestId(C),v||(v=iRt(5),k=!0,console.warn(`Checksum test id was not defined for test "${_.title}" and was auto-generated. Please replace - "${_.title}" with -
642
642
  test(defineChecksumTest("${_.title}", "${v}"), async ({ page }) => {...`))),c.addTestInfo(v,_.testId,k),C.options.useChecksumAI!==void 0&&typeof C.options.useChecksumAI=="boolean"&&(C.options.useChecksumAI={actions:C.options.useChecksumAI,assertions:!1,visualComparison:!1});let R=new sJe(C),B=new jbe(r,C.runMode,a,o,c,_,v,w,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:C.runMode!=="normal",useMockData:!1,printLogs:!1,...C.options},T,C,R,{variableStore:f});return a.pages().length===0&&(w._checksum.expect.setPage(B),w._checksum.checksumAI.page=B,f.clearAll(),B.testRunAnalytics.testRunStart()),await B.asyncInit(),B.proxy}static async fetchVtgInternalTestId(r){try{let a=process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;if(!a)return;let o=JSON.parse(a);if(o.mode!=="start"||!o.storyId)return;let{VtgUserStoryService:c}=await Promise.resolve().then(()=>(Rzr(),NHn)),{VtgCloudAPIService:f}=await Promise.resolve().then(()=>(Uzr(),BHn)),_=new f(r),v=new c(_,r);await v.fetchStory(o.storyId);let w=v.getStory();return w==null?void 0:w.internalTestId}catch(a){console.warn("Failed to fetch VTG internalTestId from story:",a);return}}async asyncInit(r=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),r||await this.prepareForTestArtifacts();let a=CZ.resolve(__dirname,"mock-auto-heal-agent.js");await this.page.addInitScript({path:a})}async makePage(r){let a=new jbe(r,this.runMode,this._context,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await a.asyncInit(!0),a.proxy}getTimeMachinePage(){var r;return(r=this.timeMachine)==null?void 0:r.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(r){var a;return r===((a=this.timeMachine)==null?void 0:a.getFrame())}shouldRecordRRwebEvents(){return Pm.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}recordInteraction(){let r=this.getPageGuid(this.page);jbe.recentlyInteracted.set(r,Date.now()),this.lastInteractionTime=Date.now()}static getMostRecentPage(r){let a=r.pages(),o=a[0],c=0;for(let f of a){let _=f._guid,v=jbe.recentlyInteracted.get(_)||0;v>c&&(c=v,o=f)}return o}async goto(r,a){return this.recordInteraction(),this.page.goto(r,a)}async reload(r){return this.recordInteraction(),this.page.reload(r)}async goBack(r){return this.recordInteraction(),this.page.goBack(r)}async goForward(r){return this.recordInteraction(),this.page.goForward(r)}async click(r,a){return this.recordInteraction(),this.page.click(r,a)}async dblclick(r,a){return this.recordInteraction(),this.page.dblclick(r,a)}async fill(r,a,o){return this.recordInteraction(),this.page.fill(r,a,o)}async press(r,a,o){return this.recordInteraction(),this.page.press(r,a,o)}async check(r,a){return this.recordInteraction(),this.page.check(r,a)}async uncheck(r,a){return this.recordInteraction(),this.page.uncheck(r,a)}async selectOption(r,a,o){return this.recordInteraction(),this.page.selectOption(r,a,o)}async hover(r,a){return this.recordInteraction(),this.page.hover(r,a)}async type(r,a,o){return this.recordInteraction(),this.page.type(r,a,o)}async setInputFiles(r,a,o){return this.recordInteraction(),this.page.setInputFiles(r,a,o)}async tap(r,a){return this.recordInteraction(),this.page.tap(r,a)}async dragAndDrop(r,a,o){return this.recordInteraction(),this.page.dragAndDrop(r,a,o)}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var o;let a=(o=this.getPlaywrightProjectConfig().use)==null?void 0:o.trace;this.traceMode=typeof a=="string"?a:a==null?void 0:a.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async r=>{this.injectedScriptManager.onFrameNavigated(r)})}checksumSelector(r){return this.checksumStepId=r,this.options.useChecksumSelectors&&this.setSelectorFallback(r),this.proxy}checksumAI(r,a,o){let c=this.addNewThought(r,"action",!!a);this.previousSteps.push({thought:c.thought,timestamp:Date.now()});let f=this.getPageGuid(this.page);return qve.setLastAction(f,r),a&&typeof a=="function"?this.test.step(r,async _=>{var v;try{return o!=null&&o.withDialog&&this.pageInteractor.listenToDialog(),await a()}catch(w){if(c.children=[],!this.options.useChecksumAI.actions||o!=null&&o.withDialog||o!=null&&o.skipAutoRecovery)throw w;this.setAIFallback(r,"action");try{return await this.initiateFallbackSequence({type:"action",error:w,method:void 0,args:[],testInfo:this.testInfo,step:_},{fallbackTypes:[cbe,Mbe]})}catch(C){throw this.testRunAnalytics.testRunError({failedThought:r,error:(C==null?void 0:C.message)||"Unknown error"}),C}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(v=this.currentThought)==null?void 0:v.parent}}):(this.options.useChecksumAI.actions&&!(o!=null&&o.skipAutoRecovery)&&this.setAIFallback(r,"action"),this.proxy)}resolveAssetsFolder(r){return r.map(a=>CZ.join(Ldt(Gne()),a))}getRuntimeOptions(){return this.options}addPwAnnotation(r){this.testInfo.annotations.push({type:r.type,description:`
643
- ${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let v=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=v}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:qzr};this.pushFallback(this.constructFallback(wmt).init(a)),this.pushFallback(this.constructFallback(Amt).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Emt).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:qzr}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===1,c=e(()=>{var R,B;let v=this.buildThoughtsChainForFallback(),w={title:this.testInfo.title},C={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:v.slice(0,-1),failing:r,next:v.slice(1)},k={storyInfo:w,testIdentification:C,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Mbe).init(k)},"createArFallback"),f=e(()=>{var v,w;return this.constructFallback(cbe).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:Pm.benchmark,arMode:(v=this.options.useChecksumAI)==null?void 0:v.arMode,overrideOptions:(w=this.options.useChecksumAI)==null?void 0:w.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(f()):this.pushFallback(c()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:Pm.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await pD(c,r.timeout),_=Date.now()-o;r instanceof cbe&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Mbe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let v=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new dmt(f.fbResult);if(r instanceof cbe&&f.summary&&this.arSummaries.push(f.summary),r instanceof Mbe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${v}`}),f.steps.length===1){let w=f.steps[0];w.thought&&(this.currentThought.thought=w.thought)}else this.currentThought.children=f.steps.map((w,C)=>({id:`${this.currentThought.id}.${C+1}`,thought:w.thought,type:w.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){ix(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof cbe);if(o){let _=o.getFailedThought(),v=this.variableStore.getActiveVariables();this.fallbacks.forEach(w=>{w.setThought(_),w.setVariables(v)})}let c=this.fallbacks.find(_=>_ instanceof Mbe);if(c){let _=c.failingThought;this.fallbacks.forEach(v=>{v instanceof Mbe&&v.setVariables(this.variableStore.getActiveVariables()),v.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((v,w)=>v||_ instanceof w,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let v=_==null?void 0:_.toString();v&&console.log(`Using ${v}`);let w;try{let C=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));w=!0}catch(C){if(w=!1,r.withChecksumAI&&C.message==="fetch failed")throw new Error(_Je);C instanceof dmt&&C.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),v&&console.log(`Failed to use ${v}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Cmt).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:CZ.basename(r)})}catch(r){ix("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return ix("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[Cmt,Emt,wmt,Amt,cbe];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=aTn(dMt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?oTn(dMt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=ZIr(dMt(this.testInfo.file)),a=CZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Sz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=CZ.join(r,"tmp");(0,Sz.existsSync)(o)||(0,Sz.mkdirSync)(o);let c=(0,Sz.readFileSync)(a),f=await(0,LHn.loadAsync)(c);for(let v of Object.keys(f.files)){let w=await f.file(v).async("string"),C=CZ.join(o,v);(0,Sz.writeFileSync)(C,w),this.unzippedHarData.push(C)}let _=CZ.join(o,"test.har");if(!(0,Sz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Sz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Sz.rmSync)(CZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){ix("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=CZ.join(q9e(Gne()),"settings.asr");if(!(0,Sz.existsSync)(r)){ix("Could not find ASR file");return}let{ungzip:a}=XIr();try{let o=await a((0,Sz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){ix("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(jbe,"RuntimePage"),jbe.recentlyInteracted=new Map;RHn=jbe});function dCa(i,t){return t}function mCa(i,t){return i.filter(r=>r!==void 0)}function qHn(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:gCa(i)?1:i instanceof Set?3:i instanceof Map?4:5}function _Ca(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}function hCa(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}function $Hn(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)}}}}}function gCa(i){if(!QHn.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"||!QHn.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}function yCa(i,t,r){let a={};for(let o of _Ca(i)){let c=[];for(let v of i)hCa(v,o)&&c.push(v[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=VHn(c,t,f);_!==k7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}function vCa(i){return i.flat()}function bCa(i){return new Set($Hn(i))}function xCa(i){return new Map($Hn(i))}function ACa(i){return i.at(-1)}function Qzt(...i){return ECa({})(...i)}function ECa(i,t){let r=wCa(i,a);function a(...o){return VHn(o,r,t)}return e(a,"customizedDeepmerge"),a}function wCa(i,t){return{defaultMergeFunctions:qzt,mergeFunctions:{...qzt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(qzt,r)).map(([r,a])=>a===!1?[r,qzt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??dCa,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??mCa,actions:k7e}}function VHn(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 Qzr(a,t,r);let o=qHn(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(qHn(a[f])!==o)return Qzr(a,t,r)}switch(o){case 1:return CCa(a,t,r);case 2:return SCa(a,t,r);case 3:return DCa(a,t,r);case 4:return TCa(a,t,r);default:return Qzr(a,t,r)}}function CCa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}function SCa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}function DCa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}function TCa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}function Qzr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}var k7e,fNs,UHn,QHn,qzt,$zr=Vt(()=>{k7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},fNs={defaultMerge:k7e.defaultMerge};e(dCa,"defaultMetaDataUpdater");e(mCa,"defaultFilterValues");(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"})(UHn||(UHn={}));e(qHn,"getObjectType");e(_Ca,"getKeys");e(hCa,"objectHasProperty");e($Hn,"getIterableOfIterables");QHn=["[object Object]","[object Module]"];e(gCa,"isRecord");e(yCa,"mergeRecords$1");e(vCa,"mergeArrays$1");e(bCa,"mergeSets$1");e(xCa,"mergeMaps$1");e(ACa,"mergeOthers$1");qzt={mergeRecords:yCa,mergeArrays:vCa,mergeSets:bCa,mergeMaps:xCa,mergeOthers:ACa};e(Qzt,"deepmerge");e(ECa,"deepmergeCustom");e(wCa,"getUtils");e(VHn,"mergeUnknowns");e(CCa,"mergeRecords");e(SCa,"mergeArrays");e(DCa,"mergeSets");e(TCa,"mergeMaps");e(Qzr,"mergeOthers")});function jHn(i){JHn=i}function ix(...i){JHn&&console.log(...i)}async function LMn(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():pD(o(),a,"Execution timeout")}function Lzr(i,{role:t,environment:r}={},a=!1){var _,v;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:w})=>r===w)),o||(o=(v=i.environments)==null?void 0:v.find(({default:w})=>w)),!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(w=>w.role===t)),f||(f=c.find(w=>w.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}}function kCa(i){let t=`${i??Gne()}/login.ts`;if(!(0,$zt.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}}async function ICa(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,{skipAutoRecovery:!0}):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
643
+ ${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),a!=null&&a.stepId&&this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let v=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=v}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:qzr};this.pushFallback(this.constructFallback(wmt).init(a)),this.pushFallback(this.constructFallback(Amt).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Emt).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:qzr}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===1,c=e(()=>{var R,B;let v=this.buildThoughtsChainForFallback(),w={title:this.testInfo.title},C={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:v.slice(0,-1),failing:r,next:v.slice(1)},k={storyInfo:w,testIdentification:C,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Mbe).init(k)},"createArFallback"),f=e(()=>{var v,w;return this.constructFallback(cbe).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:Pm.benchmark,arMode:(v=this.options.useChecksumAI)==null?void 0:v.arMode,overrideOptions:(w=this.options.useChecksumAI)==null?void 0:w.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(f()):this.pushFallback(c()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:Pm.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await pD(c,r.timeout),_=Date.now()-o;r instanceof cbe&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Mbe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let v=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new dmt(f.fbResult);if(r instanceof cbe&&f.summary&&this.arSummaries.push(f.summary),r instanceof Mbe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${v}`}),f.steps.length===1){let w=f.steps[0];w.thought&&(this.currentThought.thought=w.thought)}else this.currentThought.children=f.steps.map((w,C)=>({id:`${this.currentThought.id}.${C+1}`,thought:w.thought,type:w.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){ix(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof cbe);if(o){let _=o.getFailedThought(),v=this.variableStore.getActiveVariables();this.fallbacks.forEach(w=>{w.setThought(_),w.setVariables(v)})}let c=this.fallbacks.find(_=>_ instanceof Mbe);if(c){let _=c.failingThought;this.fallbacks.forEach(v=>{v instanceof Mbe&&v.setVariables(this.variableStore.getActiveVariables()),v.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((v,w)=>v||_ instanceof w,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let v=_==null?void 0:_.toString();v&&console.log(`Using ${v}`);let w;try{let C=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));w=!0}catch(C){if(w=!1,r.withChecksumAI&&C.message==="fetch failed")throw new Error(_Je);C instanceof dmt&&C.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),v&&console.log(`Failed to use ${v}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Cmt).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:CZ.basename(r)})}catch(r){ix("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return ix("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[Cmt,Emt,wmt,Amt,cbe];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=aTn(dMt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?oTn(dMt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=ZIr(dMt(this.testInfo.file)),a=CZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Sz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=CZ.join(r,"tmp");(0,Sz.existsSync)(o)||(0,Sz.mkdirSync)(o);let c=(0,Sz.readFileSync)(a),f=await(0,LHn.loadAsync)(c);for(let v of Object.keys(f.files)){let w=await f.file(v).async("string"),C=CZ.join(o,v);(0,Sz.writeFileSync)(C,w),this.unzippedHarData.push(C)}let _=CZ.join(o,"test.har");if(!(0,Sz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Sz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Sz.rmSync)(CZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){ix("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=CZ.join(q9e(Gne()),"settings.asr");if(!(0,Sz.existsSync)(r)){ix("Could not find ASR file");return}let{ungzip:a}=XIr();try{let o=await a((0,Sz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){ix("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(jbe,"RuntimePage"),jbe.recentlyInteracted=new Map;RHn=jbe});function dCa(i,t){return t}function mCa(i,t){return i.filter(r=>r!==void 0)}function qHn(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:gCa(i)?1:i instanceof Set?3:i instanceof Map?4:5}function _Ca(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}function hCa(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}function $Hn(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)}}}}}function gCa(i){if(!QHn.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"||!QHn.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}function yCa(i,t,r){let a={};for(let o of _Ca(i)){let c=[];for(let v of i)hCa(v,o)&&c.push(v[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=VHn(c,t,f);_!==k7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}function vCa(i){return i.flat()}function bCa(i){return new Set($Hn(i))}function xCa(i){return new Map($Hn(i))}function ACa(i){return i.at(-1)}function Qzt(...i){return ECa({})(...i)}function ECa(i,t){let r=wCa(i,a);function a(...o){return VHn(o,r,t)}return e(a,"customizedDeepmerge"),a}function wCa(i,t){return{defaultMergeFunctions:qzt,mergeFunctions:{...qzt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(qzt,r)).map(([r,a])=>a===!1?[r,qzt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??dCa,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??mCa,actions:k7e}}function VHn(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 Qzr(a,t,r);let o=qHn(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(qHn(a[f])!==o)return Qzr(a,t,r)}switch(o){case 1:return CCa(a,t,r);case 2:return SCa(a,t,r);case 3:return DCa(a,t,r);case 4:return TCa(a,t,r);default:return Qzr(a,t,r)}}function CCa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}function SCa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}function DCa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}function TCa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}function Qzr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}var k7e,fNs,UHn,QHn,qzt,$zr=Vt(()=>{k7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},fNs={defaultMerge:k7e.defaultMerge};e(dCa,"defaultMetaDataUpdater");e(mCa,"defaultFilterValues");(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"})(UHn||(UHn={}));e(qHn,"getObjectType");e(_Ca,"getKeys");e(hCa,"objectHasProperty");e($Hn,"getIterableOfIterables");QHn=["[object Object]","[object Module]"];e(gCa,"isRecord");e(yCa,"mergeRecords$1");e(vCa,"mergeArrays$1");e(bCa,"mergeSets$1");e(xCa,"mergeMaps$1");e(ACa,"mergeOthers$1");qzt={mergeRecords:yCa,mergeArrays:vCa,mergeSets:bCa,mergeMaps:xCa,mergeOthers:ACa};e(Qzt,"deepmerge");e(ECa,"deepmergeCustom");e(wCa,"getUtils");e(VHn,"mergeUnknowns");e(CCa,"mergeRecords");e(SCa,"mergeArrays");e(DCa,"mergeSets");e(TCa,"mergeMaps");e(Qzr,"mergeOthers")});function jHn(i){JHn=i}function ix(...i){JHn&&console.log(...i)}async function LMn(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():pD(o(),a,"Execution timeout")}function Lzr(i,{role:t,environment:r}={},a=!1){var _,v;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:w})=>r===w)),o||(o=(v=i.environments)==null?void 0:v.find(({default:w})=>w)),!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(w=>w.role===t)),f||(f=c.find(w=>w.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}}function kCa(i){let t=`${i??Gne()}/login.ts`;if(!(0,$zt.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}}async function ICa(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,{skipAutoRecovery:!0}):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
644
644
  `,c),c}}function jzt(i){let{config:t,folder:r,throwIfAuthFailed:a}=i,o=kCa(r);return async(c,{role:f,environment:_}={})=>{let{environment:v,user:w}=Lzr(t,{role:f,environment:_},i.throwIfEnvInfoInvalid);if(a&&!w)throw new Error("Could not find user credentials matching the provided role and/or environment");await ICa(c,o,{environment:v,user:w,config:t})}}function ajn(){if(DWe)return DWe;try{let i=(0,$zt.existsSync)(`${Gne()}/checksum.config.ts`)?"checksum.config.ts":(0,$zt.existsSync)(`${Gne()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return zHn(require(`${Gne()}/${i}`).default)}catch{console.warn("Could not find checksum config file, will run with defaults")}return zHn()}function zHn(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),DWe=Qzt(t,i),Pm.testRun.disableAutoRecovery&&(DWe.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),Pm.testRun.disableHostReports&&(DWe.options.hostReports=!1),DWe}function Uzt(i){let t=e(r=>{r.on("dialog",a=>{})},"makeDialogHandler");i.context().pages().forEach(t),i.context().on("page",r=>{t(r)})}var $zt,JHn,DWe,_Je,yie=Vt(()=>{"use strict";MHn();fD();w4e();$zt=require("fs");N8();$zr();JHn=!1;e(jHn,"setLogToConsole");e(ix,"log");e(LMn,"executePlaywrightMethodWithTimeout");e(Lzr,"resolveEnvironment");e(kCa,"requireLogin");e(ICa,"proceedWithLogin");e(jzt,"makeUnboundLogin");e(ajn,"loadChecksumConfig");e(zHn,"getChecksumConfig");e(Uzt,"preventDialogAutoDismissal");_Je="Checksum failed connecting to the server"});var Zzr=Er((QOs,nGn)=>{function qCa(i){r.debug=r,r.default=r,r.coerce=v,r.disable=f,r.enable=o,r.enabled=_,r.humanize=bFe(),r.destroy=w,Object.keys(i).forEach(C=>{r[C]=i[C]}),r.names=[],r.skips=[],r.formatters={};function t(C){let T=0;for(let k=0;k<C.length;k++)T=(T<<5)-T+C.charCodeAt(k),T|=0;return r.colors[Math.abs(T)%r.colors.length]}e(t,"selectColor"),r.selectColor=t;function r(C){let T,k=null,R,B;function U(...W){if(!U.enabled)return;let X=U,ne=Number(new Date),ce=ne-(T||ne);X.diff=ce,X.prev=T,X.curr=ne,T=ne,W[0]=r.coerce(W[0]),typeof W[0]!="string"&&W.unshift("%O");let fe=0;W[0]=W[0].replace(/%([a-zA-Z%])/g,(Se,Fe)=>{if(Se==="%%")return"%";fe++;let ke=r.formatters[Fe];if(typeof ke=="function"){let Oe=W[fe];Se=ke.call(X,Oe),W.splice(fe,1),fe--}return Se}),r.formatArgs.call(X,W),(X.log||r.log).apply(X,W)}return e(U,"debug"),U.namespace=C,U.useColors=r.useColors(),U.color=r.selectColor(C),U.extend=a,U.destroy=r.destroy,Object.defineProperty(U,"enabled",{enumerable:!0,configurable:!1,get:e(()=>k!==null?k:(R!==r.namespaces&&(R=r.namespaces,B=r.enabled(C)),B),"get"),set:e(W=>{k=W},"set")}),typeof r.init=="function"&&r.init(U),U}e(r,"createDebug");function a(C,T){let k=r(this.namespace+(typeof T>"u"?":":T)+C);return k.log=this.log,k}e(a,"extend");function o(C){r.save(C),r.namespaces=C,r.names=[],r.skips=[];let T=(typeof C=="string"?C:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let k of T)k[0]==="-"?r.skips.push(k.slice(1)):r.names.push(k)}e(o,"enable");function c(C,T){let k=0,R=0,B=-1,U=0;for(;k<C.length;)if(R<T.length&&(T[R]===C[k]||T[R]==="*"))T[R]==="*"?(B=R,U=k,R++):(k++,R++);else if(B!==-1)R=B+1,U++,k=U;else return!1;for(;R<T.length&&T[R]==="*";)R++;return R===T.length}e(c,"matchesTemplate");function f(){let C=[...r.names,...r.skips.map(T=>"-"+T)].join(",");return r.enable(""),C}e(f,"disable");function _(C){for(let T of r.skips)if(c(C,T))return!1;for(let T of r.names)if(c(C,T))return!0;return!1}e(_,"enabled");function v(C){return C instanceof Error?C.stack||C.message:C}e(v,"coerce");function w(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e(w,"destroy"),r.enable(r.load()),r}e(qCa,"setup");nGn.exports=qCa});var iGn=Er((lG,Kzt)=>{lG.formatArgs=$Ca;lG.save=VCa;lG.load=zCa;lG.useColors=QCa;lG.storage=JCa();lG.destroy=(()=>{let i=!1;return()=>{i||(i=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();lG.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function QCa(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let i;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(i=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(i[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}e(QCa,"useColors");function $Ca(i){if(i[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+i[0]+(this.useColors?"%c ":" ")+"+"+Kzt.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;i.splice(1,0,t,"color: inherit");let r=0,a=0;i[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(r++,o==="%c"&&(a=r))}),i.splice(a,0,t)}e($Ca,"formatArgs");lG.log=console.debug||console.log||(()=>{});function VCa(i){try{i?lG.storage.setItem("debug",i):lG.storage.removeItem("debug")}catch{}}e(VCa,"save");function zCa(){let i;try{i=lG.storage.getItem("debug")||lG.storage.getItem("DEBUG")}catch{}return!i&&typeof process<"u"&&"env"in process&&(i=process.env.DEBUG),i}e(zCa,"load");function JCa(){try{return localStorage}catch{}}e(JCa,"localstorage");Kzt.exports=Zzr()(lG);var{formatters:WCa}=Kzt.exports;WCa.j=function(i){try{return JSON.stringify(i)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var sGn=Er((MR,Xzt)=>{var HCa=require("tty"),Yzt=require("util");MR.init=tSa;MR.log=XCa;MR.formatArgs=KCa;MR.save=ZCa;MR.load=eSa;MR.useColors=GCa;MR.destroy=Yzt.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");MR.colors=[6,2,3,4,5,1];try{let i=P_t();i&&(i.stderr||i).level>=2&&(MR.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}MR.inspectOpts=Object.keys(process.env).filter(i=>/^debug_/i.test(i)).reduce((i,t)=>{let r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(o,c)=>c.toUpperCase()),a=process.env[t];return/^(yes|on|true|enabled)$/i.test(a)?a=!0:/^(no|off|false|disabled)$/i.test(a)?a=!1:a==="null"?a=null:a=Number(a),i[r]=a,i},{});function GCa(){return"colors"in MR.inspectOpts?!!MR.inspectOpts.colors:HCa.isatty(process.stderr.fd)}e(GCa,"useColors");function KCa(i){let{namespace:t,useColors:r}=this;if(r){let a=this.color,o="\x1B[3"+(a<8?a:"8;5;"+a),c=` ${o};1m${t} \x1B[0m`;i[0]=c+i[0].split(`
645
645
  `).join(`
646
646
  `+c),i.push(o+"m+"+Xzt.exports.humanize(this.diff)+"\x1B[0m")}else i[0]=YCa()+t+" "+i[0]}e(KCa,"formatArgs");function YCa(){return MR.inspectOpts.hideDate?"":new Date().toISOString()+" "}e(YCa,"getDate");function XCa(...i){return process.stderr.write(Yzt.formatWithOptions(MR.inspectOpts,...i)+`