@checksum-ai/runtime 2.0.8-alpha → 2.0.9-beta

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 CHANGED
@@ -1 +1 @@
1
- CHECKSUM_RUNTIME_BUILD_TIME=2025-12-09T23:37:42.043Z
1
+ CHECKSUM_RUNTIME_BUILD_TIME=2025-12-11T22:10:19.702Z
package/index.js CHANGED
@@ -1921,7 +1921,7 @@ ${JSON.stringify(t,null,2)}
1921
1921
  ${Cht}`})).join(`
1922
1922
  ${Cht}`),c=new B7e(r.sourceFile),f=(k=this.userStoryService.getStory())==null?void 0:k.internalTestId,_=(R=this.userStoryService.getStory())==null?void 0:R.goal,v=(B=this.userStoryService.getStory())==null?void 0:B.id;c.transformSourceFile([new $Jt(r.sourceFile),new HJt(r.sourceFile,{internalTestId:f,title:_}),new QJt(r.sourceFile,r.testMirrors.filter(U=>U.internalTestId===f||U.storyId===v).map(U=>U.testBody),LZn(o))]);let C=this.testAssetsManager.getSavedTestFilePath(),{error:w}=await c.write(C,Cht);return{filePath:(0,RHe.relative)(process.cwd(),C),error:w}}get isLoadedFromTestFile(){return!!this.vtgTestFileRunConfig}async reloadTestFromFile(t){if(!this.vtgTestFileRunConfig)return;let r=await this.getReloadTestEnvironmentCode();await this.evaluationService.execute(r);let o=new Dht(this.testAssetsManager.getSavedTestFilePath()).loadActionsFromSingleTest({mergeCustomCodeSteps:this.settingsService.getSettings().mergeCustomCodeSteps});return t&&await this.mergeTimestampsToReloadedActions(o),this.actionsManager.reloadTestSteps(o),o}async mergeTimestampsToReloadedActions(t){let r=this.actionsManager.actions,a=await this.apiService.post("llm/query",{systemMessage:$Zn(),userMessage:VZn(r,t)});try{let o=await a.text(),c=JSON.parse(o),f=0;t.forEach((_,v)=>{var w,T;let C=c.map[v];if(C){let k=r.find(({id:R})=>R===C.id);if(k){_.timestamp=k.timestamp,f=k.timestamp;let R=f;(w=_.assertions)==null||w.forEach((B,U)=>{var ne;let W=C==null?void 0:C.assertions[U],X=(ne=k.assertions)==null?void 0:ne.find(({id:ce})=>ce===W);X?(B.timestamp=X.timestamp,R=X.timestamp):B.timestamp=R+1});return}}_.timestamp=f+1,(T=_.assertions)==null||T.forEach((k,R)=>{k.timestamp=f+R+1})})}catch(o){return nf.error("Failed to merge actions",o),null}}async getReloadTestImportCodeOfNewPackages(t,r,a){let o=new B7e(r);o.transformSourceFile([new Fht(t,a,{filterOutChecksumImports:!0,filterOutLocalModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutNotImportOrRequireStatements:!0}),new qFe(t),new Nht,new Pht]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new Tht(r,c,{filterOutDefinedVariableNames:!0})]),(await o.getFormattedTestFileCode()).code}async getDeclaredVariableNames(t){return new JJt(this.evaluationService).extractDeclaredVariableNames(t)}async getReloadTestEnvironmentCode(){let t=this.testAssetsManager.getSavedTestFilePath(),r=O7e(t),a=Sht(),o=await this.getReloadCodeWithoutPackages(t,r,a);return[await this.getReloadTestImportCodeOfNewPackages(t,r,a),o].join(`
1923
1923
  `)}async getReloadCodeWithoutPackages(t,r,a){let o=new B7e(r);o.transformSourceFile([new WJt({shouldRemoveTestExpression:!0,shouldRemoveTestCalls:!0}),new VJt,new Fht(t,a,{filterOutNodeModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutChecksumImports:!0}),new qFe(t),new BHe(t,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[GZn.default.factory.createIdentifier("__filename")]}),new Nht,new Pht]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new Tht(r,c)]),(await o.getFormattedTestFileCode()).code}getLocalSavedJSONFilePath(t,r){var c;r??(r=r||((c=this.userStoryService.getStory())==null?void 0:c.id));let a=this.testAssetsManager.getLocalAutoSaveFileName(r);return`${t==="auto-save"?this.testAssetsManager.getLocalAutoSavePath():this.testAssetsManager.getLocalSavePath()}/${a}`}readLocalSavedDataFromJSONFile(t){let r=this.readJsonFile(t);return r?{...r,executedActions:r.executedActions.map(a=>({...a,timestamp:void 0}))}:null}readJsonFile(t){try{let r=(0,M7e.readFileSync)(t,"utf-8");return JSON.parse(r)}catch(r){return nf.error(`Error reading or parsing JSON file: ${r}`),null}}makeDraftData(){let t=this.userStoryService.getStory(),r=this.userStoryService.getTestGenerationData(),a=this.userStoryService.getEnvInfo(),o={};return t!=null&&t.version&&(o.version=t.version),t!=null&&t.testFlowDescription&&(o.testFlowDescription=t.testFlowDescription),{actions:this.actionsManager.actions,internalTestId:t.internalTestId,environmentUserId:a.user.username,description:t.goal,metadata:Object.keys(o).length>0?o:void 0}}async generateTestFileString(t){try{let r=this.makeDraftData(),a=t?`${t}.draft.spec.ts`:`test-${r.internalTestId}.draft.spec.ts`,o=await this.apiService.post("test-generation/generate-test-file-string",r);if(!o.ok)throw new Error(`test generation request failed: ${o.statusText}`);let c=await o.text();rWn(c,a,this.testAssetsManager.getLocalSavePath())}catch(r){throw nf.error("Failed to generate test file string",r),new Error("Failed to generate test file string")}}localSave(){let t=JSON.stringify(this.vtgTestJSON,null,2),r=this.testAssetsManager.getAssetsFolderPath(),a=this.testAssetsManager.getLocalAutoSaveFileName(this.userStoryService.getStory().id);(0,M7e.writeFileSync)(`${r}/${a}`,t),(0,M7e.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/${a}`,t)}get vtgTestJSON(){var t;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(t=this.config.environments.find(r=>r.default))==null?void 0:t.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async extendedJSONBackup(){let t=await this.saveExtendedJson(),r=(0,RHe.dirname)(this.testAssetsManager.getSavedTestFilePath()),a=(0,RHe.join)(r,"test.extended.json");return(0,M7e.writeFileSync)(a,JSON.stringify(t,null,2)),{executedActions:t}}async localBackup(t){if(t){this.testAssetsManager.setCurrentSaveAsLocation(t);let r=this.testAssetsManager.getLocalSaveAsPath();nWn(this.testAssetsManager.getLocalAutoSavePath(),r)}return await this.saveTestFile()}async saveExtendedJson(){let t=[...this.actionsManager.actions],r=[],a=e(async o=>{let{timestamp:c}=o,f="matcher"in o,_=o.timestamp&&(f||oft(o.eventCode)),{fullHTML:v,outerHTML:C,parentHTML:w,rrwebSnapshot:T}=o.timestamp?await this.getHTMLsForTimestamp(c,o.locator):{fullHTML:"",outerHTML:"",parentHTML:void 0,rrwebSnapshot:""},k=f?Pie.generateSingleAssertionCode(o):Pie.generateSingleActionCode(o,{newLineSeparator:`
1924
- ${Cht}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:v,outerHTML:C,parentHTML:w,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){nf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){nf.info(`processing assertion of ${c.assertions.length} assertions`);try{let v=await a(_);r.push(v)}catch(v){nf.error("Failed to extract data for assertion",v)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${aj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){nf.error("Failed to take element snapshot",a);return}}async getHTMLsForTimestamp(t,r){try{return r?await this.taskTimeMachine.executeTask(async o=>{let c=await this.evaluationService.getLocator(`return ${aj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:v,rrwebSnapshot:C}=await o.page().evaluate(({element:T})=>{let k="",R="",B="",U=document.querySelector(".replayer-wrapper iframe").contentDocument;try{R=U.querySelector("html").outerHTML}catch{R=""}try{B=T.outerHTML}catch{B=""}try{k=JSON.stringify(window.checksum.timeMachine.rrwebSnapshot(U))}catch{k=""}return{fullHTML:R,outerHTML:B,rrwebSnapshot:k}},{element:f}),w=await zZn(c);return{fullHTML:_,outerHTML:v,parentHTML:w,rrwebSnapshot:C}},t):{fullHTML:"",outerHTML:""}}catch(a){return nf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,M7e.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){var t;try{let{testGenerationId:r}=await this.userStoryService.createTestGeneration();if(await this.saveTestFile(),!await this.settingsService.getIsGitReflectionEnabled()){let _=new vJt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${r}/get-upload-url`),v=e(T=>({complete:!1,error:!1,response:void 0,info:T}),"buildUploadAsset"),C=[],w=(t=this.userStoryService.getStory())==null?void 0:t.internalTestId;await _.uploadAsset(v({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:`test-${w}.fix.checksum.spec.ts`})),C.push(v({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),C.push(v({type:"har",path:await HZn(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(T=>T.eventCode==="upload_files").forEach(T=>{var k;(k=T.files)==null||k.forEach(R=>{C.push(v({type:"test-files",path:R}))})}),await Promise.all(C)}let o=this.actionsManager.actions.map(_=>({..._,parentFramesSelectors:_.parentFramesSelectors?_.parentFramesSelectors.filter(v=>v!=="iframe"):void 0})),c=this.userStoryService.getStory(),f={};c!=null&&c.version&&(f.version=c.version),c!=null&&c.testFlowDescription&&(f.testFlowDescription=c.testFlowDescription),await this.apiService.post(`test-generation/${r}/completed`,{actions:o,metadata:Object.keys(f).length>0?f:void 0})}catch(r){nf.error("Failed to upload test",r)}}};e(yHr,"VtgStorageService");var GJt=yHr;var vHr=class vHr{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(V0.vtg.useFakeStory){this.story={...V0.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},nf.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`);nf.info("Received flow data:",a);let{id:o,title:c,steps:f,startUrl:_,userRole:v,environment:C,internalTestId:w,version:T,collectionName:k}=a;this.story={id:o,goal:c,instructions:f,url:_,internalTestId:w,environment:{userRole:v,name:C},version:T,testFlowDescription:f,collectionName:k}}catch(r){throw nf.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 x_t(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(vHr,"VtgUserStoryService");var KJt=vHr;var bHr=class bHr{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}updateAssertionById(t,r){let a=r;return this.executedActions=this._executedActions.map(o=>{var c;if(o.id===t){let f=!!((c=o.assertions)!=null&&c.find(({id:v})=>v===r.id)),_={...o};return f?_.assertions=o.assertions.map(v=>{if(v.id===r.id){let C={...v,...r};return a=C,C}return v}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((v,C)=>v.timestamp!==C.timestamp?v.timestamp-C.timestamp:v.createdAt-C.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var v,C,w;let{id:r,data:a,options:o,type:c}=t,f={id:r,...a},_=[...this._executedActions];switch(o==null?void 0:o.type){case"insertAfter":{let T=this.findActionOrAssertionById(o.afterStepId),k=_.findIndex(R=>R.id===T.action.id);if(T.assertion||(C=(v=T.action)==null?void 0:v.assertions)!=null&&C.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=lIa(((w=_[k])==null?void 0:w.assertions)??[],R.id,!!T.assertion);_[k].assertions=B,f.assertions=U.map(W=>({...W,actionId:f.id}))}k!==-1?_.splice(k+1,0,f):_.push(f);break}case"insertLast":_.push(f);break;case"replace":{let T=_.findIndex(k=>k.id===o.stepId);T!==-1&&_.splice(T,1,f);break}case"replaceLast":_.length>0&&(_[_.length-1]=f);break}return this.executedActions=_,f}pushExecutedActionOrAddAfterParent(t,r={}){if(r.previousActionId){let a=this._executedActions.findIndex(({id:o})=>o===r.previousActionId);if(a!==-1){let o={...t,timestamp:this._executedActions[a].timestamp+1};this._executedActions=[...this._executedActions.slice(0,a+1),o,...this._executedActions.slice(a+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:a})=>a===t.id);if(r!==-1){let a={...this._executedActions[r],...t};return this.executedActions=[...this._executedActions.slice(0,r),a,...this._executedActions.slice(r+1)],a}throw new Error("Action was not found")}deleteStep(t,r,a={assertionsOnly:!1,withAssertions:!0}){r==="Action"?this.deleteAction(t,a):r==="Assertion"&&(this.executedActions=this._executedActions.map(o=>(o.assertions=(o.assertions??[]).filter(c=>c.id!==t),o)))}deleteAction(t,r={assertionsOnly:!1,withAssertions:!0}){var o;let a=this._executedActions.find(c=>c.id===t);if(!a)throw new Error(`Action with id "${t}" not found`);r.assertionsOnly?this.executedActions=this._executedActions.map(c=>c.id===t?{...c,assertions:[]}:c):!r.withAssertions&&((o=a==null?void 0:a.assertions)!=null&&o.length)?this.deleteActionAndMergeAssertions(t):this.executedActions=this._executedActions.filter(c=>c.id!==t)}deleteActionAndMergeAssertions(t){let r=this._executedActions.findIndex(_=>_.id===t);if(r===-1)throw new Error(`Action with id "${t}" not found`);if(r===0)throw new Error("Cannot remove the first action; no previous action to merge assertions into");let a=this._executedActions[r-1],o=this._executedActions[r];o.assertions||(o.assertions=[]);let c=o.assertions.map(_=>({..._,actionId:a.id})),f={...a,assertions:[...a.assertions??[],...c]};this.executedActions=[...this._executedActions.slice(0,r-1),f,...this._executedActions.slice(r+1)]}clearTestSteps(t=!0){if(t){let{navigation:r,login:a}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((o,c)=>([r==null?void 0:r.id,a==null?void 0:a.id].includes(c.id)&&o.push({...c,assertions:[]}),o),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(t){this.clearTestSteps(!1),this.executedActions=t}findLoginAndNavigationActions(){let t=this._executedActions.find(({eventCode:a})=>a==="navigation"),r=this._executedActions.find(({eventCode:a})=>a==="login");return{navigation:t,login:r}}addAssertionToAction(t,r){this.executedActions=this._executedActions.map(a=>{if(a.id!==t.actionId)return a;if(a.assertions||(a.assertions=[]),r){let o=a.assertions.findIndex(({id:c})=>r===c);a.assertions.splice(o+1,0,t)}else a.assertions=[t,...a.assertions??[]];return a})}findActionByAssertionId(t){return this._executedActions.find(({assertions:r=[]})=>r.find(a=>a.id===t))}replaceAssertion(t,r){let a=this.findActionByAssertionId(r);if(!a)throw new Error(`No action found containing assertion with id ${r}`);this.executedActions=this._executedActions.map(o=>o.id===a.id?{...o,assertions:(o.assertions??[]).map(c=>c.id===r?{...t,actionId:a.id}:c)}:o)}findActionOrAssertionById(t){let r={action:null,assertion:null};if(this._executedActions.forEach(a=>{a.id===t&&(r.action=a);let o=(a.assertions??[]).find(c=>c.id===t);o&&(r={action:a,assertion:o})}),!r.action&&!r.assertion)throw new E7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=pIa(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await UFe(OHe([o],void 0,{generateAssertionsCode:!1},(_,v)=>{o=v}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(bHr,"VtgActionsManager");var YJt=bHr,lIa=e((i,t,r=!0)=>{let a=Number(r),o=i.findIndex(_=>_.id===t);if(o===-1)return{before:i,after:[]};let c=i.slice(0,o+a),f=i.slice(o+a);return{before:c,after:f}},"splitArrayAtId"),pIa=e(i=>i.reduce((t,r)=>{var c;let{assertions:a,...o}=r;if(t.push({step:o,type:"Action"}),(c=r.assertions)!=null&&c.length){let f=r.assertions.map(_=>({type:"Assertion",step:{..._,actionId:r.id}}));t.push(...f)}return t},[]),"transformActionsListToVTGStepsDataList");var AHt=rf(lHt()),noi=rf(require("net")),ioi=rf(tKr()),aoi=rf(toi());var rYr=class rYr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(rYr,"ValidationError");var cGe=rYr,nYr=class nYr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(nYr,"NotFoundError");var lGe=nYr;var Iv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(nf.error(`${t.method} ${t.path} error:`,o),o instanceof E7e)return r.status(200).json({error:o.message});if(o instanceof cGe)return r.status(400).send({error:o.message});if(o instanceof lGe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");var iYr=rf(lHt());var pGe=class pGe{constructor(){this.routesLogRules={};this.router=(0,iYr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,iYr.Router)(),a=t.startsWith(pGe.DEFAULT_API_PREFIX)?t:`${pGe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){nf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{nf.error(`Async process ${r} failed:`,c)})}};e(pGe,"VTGController"),pGe.DEFAULT_API_PREFIX="/api";var a5=pGe;var aYr=class aYr extends a5{constructor(r,a,o,c){super();this.assertionsService=r;this.actionsManager=a;this.actionsService=o;this.aiTestGenerationService=c;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter(""),a=this.createPrefixedRouter("/steps");r.post("/createStep",Iv(async(o,c)=>{let f=o.body,_;f.type==="Assertion"&&(_=this.assertionsService.createAssertion(f)),f.type==="Action"&&(_=this.actionsManager.createAction(f));let v=await UFe(OHe([_],void 0,{generateAssertionsCode:!1},(C,w)=>{_=w}));return c.status(200).json({step:_,code:v})})),r.patch("/updateStep",Iv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,v;f.type==="Assertion"&&(v=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(v=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let C;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(v.thought=void 0),C=await UFe(OHe([v],void 0,{generateAssertionsCode:!1},(w,T)=>{v=T}))),c.status(200).json({step:v,code:C})})),r.delete("/deleteStep",Iv(async(o,c)=>{let{id:f,options:_,type:v}=o.body;return this.actionsManager.deleteStep(f,v,_),c.status(200).send({message:"Success!"})})),r.post("/clear-test",Iv(async(o,c)=>{let f=this.actionsManager.clearTestSteps();return c.status(200).send(f)})),a.post("/execute",Iv(async(o,c)=>{let f=o.body;try{let _=null;return nUa(f)?_=await this.aiTestGenerationService.executeAction(f):iUa(f)&&(_=await this.actionsService.executeAction(f)),c.status(200).json(_)}catch(_){return c.status(400).send({error:_.message})}})),r.put("/steps",Iv(async(o,c)=>(this.actionsManager.pushExecutedActionOrAddAfterParent(o.body.action,o.body.options),c.send("success")))),r.post("/code-to-steps",Iv(async(o,c)=>{let _=jZn(o.body.code).map(v=>v&&"isChecksumAiWithDirectExpression"in v?{...v,isChecksumAiWithDirectExpression:!1}:v);return c.status(200).send(_)})),r.post("/steps-to-code",Iv(async(o,c)=>{let f=OHe(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(aYr,"VtgStepsController");var pHt=aYr;function nUa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(nUa,"isAIExecuteActionArgs");function iUa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(iUa,"isManualExecuteActionArgs");var sYr=class sYr extends a5{constructor(r){super();this.locatorsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/locators"),a=this.createPrefixedRouter("/ai/locators");r.post("/play",Iv(async(o,c)=>{let f=o.body;try{let _=await this.locatorsService.verifyLocatorOrSelector(f);return c.status(200).send(_)}catch(_){return c.status(400).send({error:_.message})}})),a.post("/generate",Iv(async(o,c)=>{let{step:f,target:_,processId:v}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,v),v,_.id,"AI locators generation");let C={processId:v,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return nf.error("Error generating AI locators:",C),c.status(500).send({processId:v,error:C.message})}})),a.post("/extract-css",Iv(async(o,c)=>{let{step:f,target:_,processId:v,llmLocators:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,v,C),v,_.id,"CSS extraction");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return nf.error("Error extracting CSS locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.post("/filter",Iv(async(o,c)=>{let{step:f,target:_,processId:v,candidates:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,v,C),v,_.id,"locators filtering");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return nf.error("Error filtering locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.delete("/process/:id",Iv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),nf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",Iv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:v}=o.body;try{let C=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,v);return c.status(200).send(C)}catch(C){return c.status(400).send({error:C.message})}})),r.post("/verify",Iv(async(o,c)=>{try{let f=await this.locatorsService.verifyLocatorOrSelector(o.body);return c.status(200).send(f)}catch(f){return c.status(400).send({error:f.message})}}))}};e(sYr,"VtgLocatorsController");var fHt=sYr;var oYr=class oYr extends a5{constructor(r){super();this.codeService=r;this.routesLogRules={"/monaco/editor/types":{skipRequestData:!0,skipResponseData:!0}};this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/monaco").post("/editor/types",Iv(async(a,o)=>{let{libs:c}=a.body;try{let f=this.codeService.getTypesForLibs(c??[]);return o.status(200).send({types:f})}catch(f){return o.status(400).send({error:f.message})}}))}};e(oYr,"MonacoController");var dHt=oYr;kI();var aUa=Nh.enum(["openai","anthropic","google-vertexai","groq"]),roi=Nh.strictObject({message:Nh.string(),selection:Nh.object({locator:Nh.string()}).optional(),stepCode:Nh.string().optional(),messageHistory:Nh.array(Nh.object({type:Nh.enum(["user","assistant"]),content:Nh.string(),timestamp:Nh.string(),stepId:Nh.string()})).optional(),model:Nh.object({id:Nh.string(),name:Nh.string(),type:aUa,model:Nh.string(),thinking:Nh.boolean().optional()}).optional(),includeImage:Nh.boolean().optional(),includeHtml:Nh.boolean().optional(),includeCode:Nh.boolean().optional(),timestamp:Nh.number(),error:Nh.string().optional()});var uYr=class uYr extends a5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",Iv(async(a,o)=>{let c=roi.safeParse(a.body);if(!c.success){o.status(400).json({error:"Invalid request body",details:c.error.format()});return}try{let f=await this.aiChatService.processMessage(c.data);o.json(f)}catch(f){o.status(500).json({error:"Failed to process message",message:f instanceof Error?f.message:"Unknown error"})}}))}};e(uYr,"AIChatController");var mHt=uYr;var soi=rf(require("path"));var cYr=class cYr extends a5{constructor(r,a,o){super();this.storageService=r;this.actionsManager=a;this.actionsService=o;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/test"),a=this.createPrefixedRouter("");r.post("/generate-test-file-string",Iv(async(o,c)=>{try{return await this.storageService.generateTestFileString(o.body.fileName),c.send("success")}catch(f){return c.status(400).send({error:f.message})}})),r.post("/upload",Iv(async(o,c)=>(await this.storageService.saveToCloud(),c.send("success")))),r.post("/local-save",Iv(async(o,c)=>{await this.storageService.localSave(),c.send("success")})),a.post("/reload-test-from-file",Iv(async(o,c)=>{if(!this.storageService.isLoadedFromTestFile)throw new lGe("No test file found");let f=await this.storageService.reloadTestFromFile(o.body.useLLM),_=await this.actionsManager.buildStepDataWithCode(f,{loadingFromFile:!0});return c.status(200).send(_)})),r.post("/verify-save-location",Iv(async(o,c)=>{try{let f=this.storageService.doesFolderExistInSaveDir(o.body.location);c.send({exists:f})}catch(f){c.status(400).send({error:f})}})),r.post("/backup",Iv(async(o,c)=>{let{backupFolderName:f}=o.body;if(!iWn(f))throw nf.error("Invalid folder name",{backupFolderName:f}),new cGe("Invalid folder name");let _=await this.storageService.localBackup(f);c.send(_)})),r.post("/extended-json-backup",Iv(async(o,c)=>{let f=this.storageService.extendedJSONBackup();c.send(f)})),a.post("/upload-files",Iv(async(o,c)=>{let f=await this.actionsService.uploadFiles(o.body.files);return c.status(200).json(f)}))}};e(cYr,"VtgStorageController");var _Ht=cYr;var lYr=class lYr extends a5{constructor(r){super();this.aiTestGenerationService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/ai");r.post("/init",Iv(async(a,o)=>{await this.aiTestGenerationService.init(),o.send("success")})),r.post("/iterate",Iv(async(a,o)=>{let c=await this.aiTestGenerationService.iterate(a.body);return c?o.status(200).json(c):o.status(400).send("no action generated")})),r.post("/stop",Iv(async(a,o)=>{this.aiTestGenerationService.stop(),o.send("success")}))}};e(lYr,"VtgAITestGenerationController");var hHt=lYr;var pYr=class pYr extends a5{constructor(r){super();this.thoughtsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/thoughts");r.post("/actions/generate",Iv(async(a,o)=>{let c=a.body,{processId:f,action:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateActionThoughts(c),f,_,"action thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/assertions/generate",Iv(async(a,o)=>{let c=a.body,{processId:f,assertion:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateAssertionThought(c),f,_,"assertion thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/stop-generate",Iv(async(a,o)=>{let c=a.body;this.thoughtsService.stopGeneratingThought(c.stepId);let f={stepId:c.stepId};return o.status(200).send(f)}))}};e(pYr,"VtgThoughtsController");var gHt=pYr;var fYr=class fYr extends a5{constructor(r,a){super();this.assertionsService=r;this.aiAssertionsService=a;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/assertions"),a=this.createPrefixedRouter("/assertion");r.post("/generate",Iv(async(o,c)=>{let f=o.body,{processId:_,id:v}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,v,"AI assertion generation");let C={processId:_,stepId:v,success:!0};return c.status(200).json(C)}catch(C){return c.status(500).send({processId:_,error:C.message})}})),r.post("/stop-generate",Iv(async(o,c)=>{let{id:f}=o.body,_={stepId:f};return this.aiAssertionsService.stopGenerateAiAssertions(f),c.status(200).send(_)})),a.post("/verify/time-machine",Iv(async(o,c)=>{let f=await this.assertionsService.verifyOnTimeMachine(o.body);return c.status(200).send(f)})),a.post("/verify/live",Iv(async(o,c)=>{let f=o.body;try{let _=await this.assertionsService.verifyOnLive(f),v=_.success?200:404;return c.status(v).send(_)}catch(_){return c.status(404).send({success:!1,message:String(_)})}})),a.post("/save",Iv(async(o,c)=>{let f=await this.assertionsService.updateAssertion(o.body);c.status(200).json(f)}))}};e(fYr,"VtgAssertionsController");var yHt=fYr;var dYr=class dYr extends a5{constructor(r){super();this.settingsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/settings");r.get("/",Iv(async(a,o)=>{let c=this.settingsService.getSettings();return o.status(200).send(c)})),r.post("/",Iv(async(a,o)=>(this.settingsService.updateSettings(a.body),o.status(200).send({message:"Success!"}))))}};e(dYr,"VtgSettingsController");var vHt=dYr;var ooi=rf(lHt());var mYr=class mYr extends a5{constructor(r){super();this.evaluatorService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/evaluator").post("/execute",Iv(async(a,o)=>{try{let c=await this.evaluatorService.execute(a.body.code);return o.status(200).json(c)}catch(c){return o.status(500).send({message:"Error during code evaluation",error:c.message})}}))}};e(mYr,"VtgEvaluatorController");var bHt=mYr;var _Yr=class _Yr{constructor(){this.reqIndex=0;this.reqInProcess={};this.routesLogRules={};this.intervalTimer=null}setRoutesLogRules(t){this.routesLogRules=t}cleanup(){this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null)}startListening(t,r,a){V0.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(V0.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){V0.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(nf.info("HTTP REQUESTS IN PROCESS"),nf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1924
+ ${Cht}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:v,outerHTML:C,parentHTML:w,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){nf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){nf.info(`processing assertion of ${c.assertions.length} assertions`);try{let v=await a(_);r.push(v)}catch(v){nf.error("Failed to extract data for assertion",v)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${aj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){nf.error("Failed to take element snapshot",a);return}}async getHTMLsForTimestamp(t,r){try{return r?await this.taskTimeMachine.executeTask(async o=>{let c=await this.evaluationService.getLocator(`return ${aj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:v,rrwebSnapshot:C}=await o.page().evaluate(({element:T})=>{let k="",R="",B="",U=document.querySelector(".replayer-wrapper iframe").contentDocument;try{R=U.querySelector("html").outerHTML}catch{R=""}try{B=T.outerHTML}catch{B=""}try{k=JSON.stringify(window.checksum.timeMachine.rrwebSnapshot(U))}catch{k=""}return{fullHTML:R,outerHTML:B,rrwebSnapshot:k}},{element:f}),w=await zZn(c);return{fullHTML:_,outerHTML:v,parentHTML:w,rrwebSnapshot:C}},t):{fullHTML:"",outerHTML:""}}catch(a){return nf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,M7e.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){var t;try{let{testGenerationId:r}=await this.userStoryService.createTestGeneration();await this.saveTestFile();let a=await this.settingsService.getIsGitReflectionEnabled();if(!a){let f=new vJt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${r}/get-upload-url`),_=e(w=>({complete:!1,error:!1,response:void 0,info:w}),"buildUploadAsset"),v=[],C=(t=this.userStoryService.getStory())==null?void 0:t.internalTestId;await f.uploadAsset(_({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:`test-${C}.fix.checksum.spec.ts`})),v.push(_({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),v.push(_({type:"har",path:await HZn(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(w=>w.eventCode==="upload_files").forEach(w=>{var T;(T=w.files)==null||T.forEach(k=>{v.push(_({type:"test-files",path:k}))})}),await Promise.all(v)}let o=this.actionsManager.actions.map(f=>({...f,parentFramesSelectors:f.parentFramesSelectors?f.parentFramesSelectors.filter(_=>_!=="iframe"):void 0})),c={};if(a){let f=this.userStoryService.getStory();f!=null&&f.version&&(c.version=f.version),f!=null&&f.testFlowDescription&&(c.testFlowDescription=f.testFlowDescription)}await this.apiService.post(`test-generation/${r}/completed`,{actions:o,metadata:Object.keys(c).length>0?c:void 0})}catch(r){nf.error("Failed to upload test",r)}}};e(yHr,"VtgStorageService");var GJt=yHr;var vHr=class vHr{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(V0.vtg.useFakeStory){this.story={...V0.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},nf.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`);nf.info("Received flow data:",a);let{id:o,title:c,steps:f,startUrl:_,userRole:v,environment:C,internalTestId:w,version:T,collectionName:k}=a;this.story={id:o,goal:c,instructions:f,url:_,internalTestId:w,environment:{userRole:v,name:C},version:T,testFlowDescription:f,collectionName:k}}catch(r){throw nf.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 x_t(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(vHr,"VtgUserStoryService");var KJt=vHr;var bHr=class bHr{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}updateAssertionById(t,r){let a=r;return this.executedActions=this._executedActions.map(o=>{var c;if(o.id===t){let f=!!((c=o.assertions)!=null&&c.find(({id:v})=>v===r.id)),_={...o};return f?_.assertions=o.assertions.map(v=>{if(v.id===r.id){let C={...v,...r};return a=C,C}return v}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((v,C)=>v.timestamp!==C.timestamp?v.timestamp-C.timestamp:v.createdAt-C.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var v,C,w;let{id:r,data:a,options:o,type:c}=t,f={id:r,...a},_=[...this._executedActions];switch(o==null?void 0:o.type){case"insertAfter":{let T=this.findActionOrAssertionById(o.afterStepId),k=_.findIndex(R=>R.id===T.action.id);if(T.assertion||(C=(v=T.action)==null?void 0:v.assertions)!=null&&C.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=lIa(((w=_[k])==null?void 0:w.assertions)??[],R.id,!!T.assertion);_[k].assertions=B,f.assertions=U.map(W=>({...W,actionId:f.id}))}k!==-1?_.splice(k+1,0,f):_.push(f);break}case"insertLast":_.push(f);break;case"replace":{let T=_.findIndex(k=>k.id===o.stepId);T!==-1&&_.splice(T,1,f);break}case"replaceLast":_.length>0&&(_[_.length-1]=f);break}return this.executedActions=_,f}pushExecutedActionOrAddAfterParent(t,r={}){if(r.previousActionId){let a=this._executedActions.findIndex(({id:o})=>o===r.previousActionId);if(a!==-1){let o={...t,timestamp:this._executedActions[a].timestamp+1};this._executedActions=[...this._executedActions.slice(0,a+1),o,...this._executedActions.slice(a+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:a})=>a===t.id);if(r!==-1){let a={...this._executedActions[r],...t};return this.executedActions=[...this._executedActions.slice(0,r),a,...this._executedActions.slice(r+1)],a}throw new Error("Action was not found")}deleteStep(t,r,a={assertionsOnly:!1,withAssertions:!0}){r==="Action"?this.deleteAction(t,a):r==="Assertion"&&(this.executedActions=this._executedActions.map(o=>(o.assertions=(o.assertions??[]).filter(c=>c.id!==t),o)))}deleteAction(t,r={assertionsOnly:!1,withAssertions:!0}){var o;let a=this._executedActions.find(c=>c.id===t);if(!a)throw new Error(`Action with id "${t}" not found`);r.assertionsOnly?this.executedActions=this._executedActions.map(c=>c.id===t?{...c,assertions:[]}:c):!r.withAssertions&&((o=a==null?void 0:a.assertions)!=null&&o.length)?this.deleteActionAndMergeAssertions(t):this.executedActions=this._executedActions.filter(c=>c.id!==t)}deleteActionAndMergeAssertions(t){let r=this._executedActions.findIndex(_=>_.id===t);if(r===-1)throw new Error(`Action with id "${t}" not found`);if(r===0)throw new Error("Cannot remove the first action; no previous action to merge assertions into");let a=this._executedActions[r-1],o=this._executedActions[r];o.assertions||(o.assertions=[]);let c=o.assertions.map(_=>({..._,actionId:a.id})),f={...a,assertions:[...a.assertions??[],...c]};this.executedActions=[...this._executedActions.slice(0,r-1),f,...this._executedActions.slice(r+1)]}clearTestSteps(t=!0){if(t){let{navigation:r,login:a}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((o,c)=>([r==null?void 0:r.id,a==null?void 0:a.id].includes(c.id)&&o.push({...c,assertions:[]}),o),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(t){this.clearTestSteps(!1),this.executedActions=t}findLoginAndNavigationActions(){let t=this._executedActions.find(({eventCode:a})=>a==="navigation"),r=this._executedActions.find(({eventCode:a})=>a==="login");return{navigation:t,login:r}}addAssertionToAction(t,r){this.executedActions=this._executedActions.map(a=>{if(a.id!==t.actionId)return a;if(a.assertions||(a.assertions=[]),r){let o=a.assertions.findIndex(({id:c})=>r===c);a.assertions.splice(o+1,0,t)}else a.assertions=[t,...a.assertions??[]];return a})}findActionByAssertionId(t){return this._executedActions.find(({assertions:r=[]})=>r.find(a=>a.id===t))}replaceAssertion(t,r){let a=this.findActionByAssertionId(r);if(!a)throw new Error(`No action found containing assertion with id ${r}`);this.executedActions=this._executedActions.map(o=>o.id===a.id?{...o,assertions:(o.assertions??[]).map(c=>c.id===r?{...t,actionId:a.id}:c)}:o)}findActionOrAssertionById(t){let r={action:null,assertion:null};if(this._executedActions.forEach(a=>{a.id===t&&(r.action=a);let o=(a.assertions??[]).find(c=>c.id===t);o&&(r={action:a,assertion:o})}),!r.action&&!r.assertion)throw new E7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=pIa(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await UFe(OHe([o],void 0,{generateAssertionsCode:!1},(_,v)=>{o=v}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(bHr,"VtgActionsManager");var YJt=bHr,lIa=e((i,t,r=!0)=>{let a=Number(r),o=i.findIndex(_=>_.id===t);if(o===-1)return{before:i,after:[]};let c=i.slice(0,o+a),f=i.slice(o+a);return{before:c,after:f}},"splitArrayAtId"),pIa=e(i=>i.reduce((t,r)=>{var c;let{assertions:a,...o}=r;if(t.push({step:o,type:"Action"}),(c=r.assertions)!=null&&c.length){let f=r.assertions.map(_=>({type:"Assertion",step:{..._,actionId:r.id}}));t.push(...f)}return t},[]),"transformActionsListToVTGStepsDataList");var AHt=rf(lHt()),noi=rf(require("net")),ioi=rf(tKr()),aoi=rf(toi());var rYr=class rYr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(rYr,"ValidationError");var cGe=rYr,nYr=class nYr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(nYr,"NotFoundError");var lGe=nYr;var Iv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(nf.error(`${t.method} ${t.path} error:`,o),o instanceof E7e)return r.status(200).json({error:o.message});if(o instanceof cGe)return r.status(400).send({error:o.message});if(o instanceof lGe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");var iYr=rf(lHt());var pGe=class pGe{constructor(){this.routesLogRules={};this.router=(0,iYr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,iYr.Router)(),a=t.startsWith(pGe.DEFAULT_API_PREFIX)?t:`${pGe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){nf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{nf.error(`Async process ${r} failed:`,c)})}};e(pGe,"VTGController"),pGe.DEFAULT_API_PREFIX="/api";var a5=pGe;var aYr=class aYr extends a5{constructor(r,a,o,c){super();this.assertionsService=r;this.actionsManager=a;this.actionsService=o;this.aiTestGenerationService=c;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter(""),a=this.createPrefixedRouter("/steps");r.post("/createStep",Iv(async(o,c)=>{let f=o.body,_;f.type==="Assertion"&&(_=this.assertionsService.createAssertion(f)),f.type==="Action"&&(_=this.actionsManager.createAction(f));let v=await UFe(OHe([_],void 0,{generateAssertionsCode:!1},(C,w)=>{_=w}));return c.status(200).json({step:_,code:v})})),r.patch("/updateStep",Iv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,v;f.type==="Assertion"&&(v=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(v=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let C;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(v.thought=void 0),C=await UFe(OHe([v],void 0,{generateAssertionsCode:!1},(w,T)=>{v=T}))),c.status(200).json({step:v,code:C})})),r.delete("/deleteStep",Iv(async(o,c)=>{let{id:f,options:_,type:v}=o.body;return this.actionsManager.deleteStep(f,v,_),c.status(200).send({message:"Success!"})})),r.post("/clear-test",Iv(async(o,c)=>{let f=this.actionsManager.clearTestSteps();return c.status(200).send(f)})),a.post("/execute",Iv(async(o,c)=>{let f=o.body;try{let _=null;return nUa(f)?_=await this.aiTestGenerationService.executeAction(f):iUa(f)&&(_=await this.actionsService.executeAction(f)),c.status(200).json(_)}catch(_){return c.status(400).send({error:_.message})}})),r.put("/steps",Iv(async(o,c)=>(this.actionsManager.pushExecutedActionOrAddAfterParent(o.body.action,o.body.options),c.send("success")))),r.post("/code-to-steps",Iv(async(o,c)=>{let _=jZn(o.body.code).map(v=>v&&"isChecksumAiWithDirectExpression"in v?{...v,isChecksumAiWithDirectExpression:!1}:v);return c.status(200).send(_)})),r.post("/steps-to-code",Iv(async(o,c)=>{let f=OHe(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(aYr,"VtgStepsController");var pHt=aYr;function nUa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(nUa,"isAIExecuteActionArgs");function iUa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(iUa,"isManualExecuteActionArgs");var sYr=class sYr extends a5{constructor(r){super();this.locatorsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/locators"),a=this.createPrefixedRouter("/ai/locators");r.post("/play",Iv(async(o,c)=>{let f=o.body;try{let _=await this.locatorsService.verifyLocatorOrSelector(f);return c.status(200).send(_)}catch(_){return c.status(400).send({error:_.message})}})),a.post("/generate",Iv(async(o,c)=>{let{step:f,target:_,processId:v}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,v),v,_.id,"AI locators generation");let C={processId:v,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return nf.error("Error generating AI locators:",C),c.status(500).send({processId:v,error:C.message})}})),a.post("/extract-css",Iv(async(o,c)=>{let{step:f,target:_,processId:v,llmLocators:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,v,C),v,_.id,"CSS extraction");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return nf.error("Error extracting CSS locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.post("/filter",Iv(async(o,c)=>{let{step:f,target:_,processId:v,candidates:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,v,C),v,_.id,"locators filtering");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return nf.error("Error filtering locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.delete("/process/:id",Iv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),nf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",Iv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:v}=o.body;try{let C=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,v);return c.status(200).send(C)}catch(C){return c.status(400).send({error:C.message})}})),r.post("/verify",Iv(async(o,c)=>{try{let f=await this.locatorsService.verifyLocatorOrSelector(o.body);return c.status(200).send(f)}catch(f){return c.status(400).send({error:f.message})}}))}};e(sYr,"VtgLocatorsController");var fHt=sYr;var oYr=class oYr extends a5{constructor(r){super();this.codeService=r;this.routesLogRules={"/monaco/editor/types":{skipRequestData:!0,skipResponseData:!0}};this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/monaco").post("/editor/types",Iv(async(a,o)=>{let{libs:c}=a.body;try{let f=this.codeService.getTypesForLibs(c??[]);return o.status(200).send({types:f})}catch(f){return o.status(400).send({error:f.message})}}))}};e(oYr,"MonacoController");var dHt=oYr;kI();var aUa=Nh.enum(["openai","anthropic","google-vertexai","groq"]),roi=Nh.strictObject({message:Nh.string(),selection:Nh.object({locator:Nh.string()}).optional(),stepCode:Nh.string().optional(),messageHistory:Nh.array(Nh.object({type:Nh.enum(["user","assistant"]),content:Nh.string(),timestamp:Nh.string(),stepId:Nh.string()})).optional(),model:Nh.object({id:Nh.string(),name:Nh.string(),type:aUa,model:Nh.string(),thinking:Nh.boolean().optional()}).optional(),includeImage:Nh.boolean().optional(),includeHtml:Nh.boolean().optional(),includeCode:Nh.boolean().optional(),timestamp:Nh.number(),error:Nh.string().optional()});var uYr=class uYr extends a5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",Iv(async(a,o)=>{let c=roi.safeParse(a.body);if(!c.success){o.status(400).json({error:"Invalid request body",details:c.error.format()});return}try{let f=await this.aiChatService.processMessage(c.data);o.json(f)}catch(f){o.status(500).json({error:"Failed to process message",message:f instanceof Error?f.message:"Unknown error"})}}))}};e(uYr,"AIChatController");var mHt=uYr;var soi=rf(require("path"));var cYr=class cYr extends a5{constructor(r,a,o){super();this.storageService=r;this.actionsManager=a;this.actionsService=o;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/test"),a=this.createPrefixedRouter("");r.post("/generate-test-file-string",Iv(async(o,c)=>{try{return await this.storageService.generateTestFileString(o.body.fileName),c.send("success")}catch(f){return c.status(400).send({error:f.message})}})),r.post("/upload",Iv(async(o,c)=>(await this.storageService.saveToCloud(),c.send("success")))),r.post("/local-save",Iv(async(o,c)=>{await this.storageService.localSave(),c.send("success")})),a.post("/reload-test-from-file",Iv(async(o,c)=>{if(!this.storageService.isLoadedFromTestFile)throw new lGe("No test file found");let f=await this.storageService.reloadTestFromFile(o.body.useLLM),_=await this.actionsManager.buildStepDataWithCode(f,{loadingFromFile:!0});return c.status(200).send(_)})),r.post("/verify-save-location",Iv(async(o,c)=>{try{let f=this.storageService.doesFolderExistInSaveDir(o.body.location);c.send({exists:f})}catch(f){c.status(400).send({error:f})}})),r.post("/backup",Iv(async(o,c)=>{let{backupFolderName:f}=o.body;if(!iWn(f))throw nf.error("Invalid folder name",{backupFolderName:f}),new cGe("Invalid folder name");let _=await this.storageService.localBackup(f);c.send(_)})),r.post("/extended-json-backup",Iv(async(o,c)=>{let f=this.storageService.extendedJSONBackup();c.send(f)})),a.post("/upload-files",Iv(async(o,c)=>{let f=await this.actionsService.uploadFiles(o.body.files);return c.status(200).json(f)}))}};e(cYr,"VtgStorageController");var _Ht=cYr;var lYr=class lYr extends a5{constructor(r){super();this.aiTestGenerationService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/ai");r.post("/init",Iv(async(a,o)=>{await this.aiTestGenerationService.init(),o.send("success")})),r.post("/iterate",Iv(async(a,o)=>{let c=await this.aiTestGenerationService.iterate(a.body);return c?o.status(200).json(c):o.status(400).send("no action generated")})),r.post("/stop",Iv(async(a,o)=>{this.aiTestGenerationService.stop(),o.send("success")}))}};e(lYr,"VtgAITestGenerationController");var hHt=lYr;var pYr=class pYr extends a5{constructor(r){super();this.thoughtsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/thoughts");r.post("/actions/generate",Iv(async(a,o)=>{let c=a.body,{processId:f,action:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateActionThoughts(c),f,_,"action thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/assertions/generate",Iv(async(a,o)=>{let c=a.body,{processId:f,assertion:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateAssertionThought(c),f,_,"assertion thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/stop-generate",Iv(async(a,o)=>{let c=a.body;this.thoughtsService.stopGeneratingThought(c.stepId);let f={stepId:c.stepId};return o.status(200).send(f)}))}};e(pYr,"VtgThoughtsController");var gHt=pYr;var fYr=class fYr extends a5{constructor(r,a){super();this.assertionsService=r;this.aiAssertionsService=a;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/assertions"),a=this.createPrefixedRouter("/assertion");r.post("/generate",Iv(async(o,c)=>{let f=o.body,{processId:_,id:v}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,v,"AI assertion generation");let C={processId:_,stepId:v,success:!0};return c.status(200).json(C)}catch(C){return c.status(500).send({processId:_,error:C.message})}})),r.post("/stop-generate",Iv(async(o,c)=>{let{id:f}=o.body,_={stepId:f};return this.aiAssertionsService.stopGenerateAiAssertions(f),c.status(200).send(_)})),a.post("/verify/time-machine",Iv(async(o,c)=>{let f=await this.assertionsService.verifyOnTimeMachine(o.body);return c.status(200).send(f)})),a.post("/verify/live",Iv(async(o,c)=>{let f=o.body;try{let _=await this.assertionsService.verifyOnLive(f),v=_.success?200:404;return c.status(v).send(_)}catch(_){return c.status(404).send({success:!1,message:String(_)})}})),a.post("/save",Iv(async(o,c)=>{let f=await this.assertionsService.updateAssertion(o.body);c.status(200).json(f)}))}};e(fYr,"VtgAssertionsController");var yHt=fYr;var dYr=class dYr extends a5{constructor(r){super();this.settingsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/settings");r.get("/",Iv(async(a,o)=>{let c=this.settingsService.getSettings();return o.status(200).send(c)})),r.post("/",Iv(async(a,o)=>(this.settingsService.updateSettings(a.body),o.status(200).send({message:"Success!"}))))}};e(dYr,"VtgSettingsController");var vHt=dYr;var ooi=rf(lHt());var mYr=class mYr extends a5{constructor(r){super();this.evaluatorService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/evaluator").post("/execute",Iv(async(a,o)=>{try{let c=await this.evaluatorService.execute(a.body.code);return o.status(200).json(c)}catch(c){return o.status(500).send({message:"Error during code evaluation",error:c.message})}}))}};e(mYr,"VtgEvaluatorController");var bHt=mYr;var _Yr=class _Yr{constructor(){this.reqIndex=0;this.reqInProcess={};this.routesLogRules={};this.intervalTimer=null}setRoutesLogRules(t){this.routesLogRules=t}cleanup(){this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null)}startListening(t,r,a){V0.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(V0.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){V0.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(nf.info("HTTP REQUESTS IN PROCESS"),nf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1925
1925
  `)))},5e3))}handleIntervalLog(t,r,a){let o=this.reqIndex++;this.reqInProcess[o]=this.buildLogInfo(t,r,0,"","INTERVAL"),r.on("finish",()=>{let c=Date.now()-this.reqInProcess[o].start;delete this.reqInProcess[o]})}handleTransactionLog(t,r,a){if(this.getRouteRules(t.originalUrl).skip)return a(),!0;let c=Date.now(),f=this.buildLogInfo(t,r,0,"","REQUEST"),_="";nf.info("REQUEST INFO",JSON.stringify(f,null,2));let v=r.write,C=r.end;return r.write=function(w,...T){return w&&(_+=w.toString()),v.call(this,w,...T)},r.end=function(w,...T){return w&&(_+=w.toString()),C.call(this,w,...T)},r.on("finish",()=>{if(V0.vtg.logAPIServer.httpTransactions){let w=Date.now()-c,T=this.buildLogInfo(t,r,w,_,"RESPONSE");nf.info("RESPONSE INFO",JSON.stringify(T,null,2))}}),!1}buildLogInfo(t,r,a,o,c="RESPONSE"){let f=this.getRouteRules(t.originalUrl),_={method:t.method,url:t.originalUrl,start:Date.now()};return c==="INTERVAL"||(c==="REQUEST"&&!f.skipRequestData&&t.body&&(_.data=t.body),c==="RESPONSE"&&(a&&(_.duration=`${a}ms`),_.statusCode=r.statusCode,_.size=r.getHeader("content-length")||"unknown",!f.skipResponseData&&o&&(_.data=o))),_}getRouteRules(t){if(this.routesLogRules[t])return this.routesLogRules[t];for(let[r,a]of Object.entries(this.routesLogRules))if(t.includes(r))return a||{};return{}}};e(_Yr,"VTGExpressServerRoutesLoggerMiddleware");var xHt=_Yr;var hYr=class hYr{constructor(t,r,a,o,c,f,_,v,C,w,T,k){this.actionsService=t;this.assertionsService=r;this.locatorsService=a;this.aiTestGenerationService=o;this.aiAssertionsService=c;this.aiThoughtsService=f;this.actionsManager=_;this.storageService=v;this.settingsService=C;this.monacoService=w;this.evaluatorService=T;this.aiChatService=k;this.errorHandler=e((t,r,a,o)=>{nf.error("Error catch in middleware:",t),a.status(500).send({error:t.message})},"errorHandler");this.routesLoggerMiddleware=new xHt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,AHt.default)(),this.app.use((0,aoi.default)()),this.app.use(ioi.default.json({limit:"50mb"})),this.app.use(AHt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(AHt.default.static(soi.default.join(V0.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(t=>{this.app.listen(this.port,()=>{nf.info(`Express server running on port ${this.port}`),t()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),nf.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((t,r)=>{let a=noi.default.createServer();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})),this.port}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}initializeControllers(){let t=new pHt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),r=new _Ht(this.storageService,this.actionsManager,this.actionsService),a=new hHt(this.aiTestGenerationService),o=new gHt(this.aiThoughtsService),c=new yHt(this.assertionsService,this.aiAssertionsService),f=new vHt(this.settingsService),_=new fHt(this.locatorsService),v=new dHt(this.monacoService),C=new mHt(this.aiChatService),w=new bHt(this.evaluatorService),T=[t,r,a,o,c,f,_,v,w,C],k=(0,ooi.Router)(),R={};return T.forEach(B=>{k.use(B.getRouter()),R={...R,...B.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(R),k}};e(hYr,"VtgExpressServer");var EHt=hYr;var CHt=require("fs");var k1t=class k1t{constructor(t,r,a,o){this.projectRootDirectory=t;this.checksumRoot=r;this.internalFilesDir=a;this.vtgTestFileRunConfig=o;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,CHt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,CHt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,CHt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${k1t.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(t){var r;return((r=this.vtgTestFileRunConfig)==null?void 0:r.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${t}.json`}getLocalSaveAsPath(){return this.currentSaveAsLocation??(this.currentSaveAsLocation=`${Date.now()}_save`),`${this.localSaveFolderPath}/${this.currentSaveAsLocation}`}getSavedTestFilePath(){if(!this.vtgTestFileRunConfig)throw new Error("vtgTestFileRunConfig is required to get the test file save as path");if(this.currentSaveAsLocation){let t=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${t}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};e(k1t,"VtgTestAssetsManager"),k1t.AUTO_SAVE_FOLDER_NAME="auto-save";var wHt=k1t;var sUa={useCDPSession:!0,trackLoadedResources:!0},gYr=class gYr extends Ozt{constructor(r={},a={devtools:!1},o={},c,f){super({...sUa,...r},a,c,f);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(r,a=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:a}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async r=>{try{return await r.waitForFunction(()=>{var a;return!!((a=window.checksum)!=null&&a.testGenerator)}),r.evaluate(async({appSpecificRules:a,config:o,initModules:c})=>{window.checksum.testGenerator.init(a,o,c)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(a){console.log("initInjectedScript exception",a)}},"initInjectedScript");this.settings={...this.settings,...o},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let a=await super.prepare(r);return this.evaluateWithChecksumTargetFrame=this.page.mainFrame(),this.settings.loadScriptOnPrepare&&await this.injectedScriptManager.addTrackedFrame(this.page),await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")}),a}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,a,o=this.evaluateWithChecksumTargetFrame){let c=this.injectedScriptManager.getNavigationPromise(o);c&&await c;try{return o.evaluate(r,a)}catch(f){throw console.error("evaluateWithChecksum error",f,r.toString()),f}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async a=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(a),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(a=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(a),r)}async takeElementSnapshot(r,a,o={},c={}){try{let{snapshot:f,elementLocator:_}=await super.takeElementSnapshot(r,a,o);if(!f||!o.takeBodyScreenshot)return f?{snapshot:f}:{};await this.highlightElementByLocator(_,o.mousePosition);let v=await this.takePageSnapshot(c);return await this.clearHighlights(),{snapshot:f,bodySnapshot:v}}catch(f){return console.error("[ChecksumWebDriver] takeElementSnapshot error",f),{}}}async highlightElementByLocator(r,a,o="20px solid rgba(255,0,0,1)",c=!1){return this.evaluateWithChecksum(async([f,_,v,C])=>{window.checksum.testGenerator.highlightElement(f,{highlightStyle:{outline:_},mousePosition:v,scroll:C})},[await r.elementHandle(),o,a,c])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(gYr,"ChecksumWebDriver");var SHt=gYr;var uoi=require("fs"),coi=rf(require("path"));var yYr=require("fs");var vYr=class vYr{constructor(t,r,a=V0.vtg.localBuildPath){this.page=t;this.serverPort=r;this.filePath=a;this.filePath=a,nf.info("[VTG] FrontendLauncher initialized with:",{serverPort:r,filePath:a,appSource:V0.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(t){throw nf.error("An error occurred:",t),t}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t;switch(V0.vtg.appSource){case"served-app":t=V0.vtg.appURL;break;case"served-build-file":t=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":t=V0.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${V0.vtg.appSource}`)}await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(V0.vtg.appSource==="build-file")try{let t=await yYr.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,a=t.replace(r,"$1=$2.$3static");await yYr.promises.writeFile(this.filePath,a,"utf8"),nf(`Successfully modified ${this.filePath}`)}catch(t){nf.error(`Error processing file ${this.filePath}:`,t)}}};e(vYr,"VtgFrontendLauncher");var DHt=vYr;var oUa=1e3,kHt=class kHt extends SHt{constructor(r={},a={devtools:!1},o={},c){var f;super(r,a,kHt.makeSettings(o),(f=c==null?void 0:c.getFramesMessageBroker)==null?void 0:f.call(c),V0.vtg.isSeparateProcess||c==null?void 0:c.context());this.liveAppPage=c;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async r=>{this.appFrame=r,await this.frameMsgBroker.register("live",this.appFrame,V0.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new Yve(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.liveTimeMachine=new Yve(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.appViewport=o.viewport,this.completeOriginHeaderOnLivePage=o.completeOriginHeaderOnLivePage}static makeSettings(r={}){return BVt({frontendTestGenerationConfig:{showFrontendLogs:V0.isDevMode}},r)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(r){this.registeredTimeMachineFrames.push(r)}async prepare(r={},a={}){let o=await super.prepare(r);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{nf.error("Page closed")}),this.liveAppPage&&!V0.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new DHt(this.page,a.serverPort).start();let c=e(async(_=2)=>{if(this.timeMachineFrame=this.page.frames().find(v=>v.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(v=>v.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(_>0)return nf.info("Waiting for frames to be available"),await tA(oUa),c(_-1);{let v="Could not connect to VTG frontend, check that the app is available";throw nf.error(v),new Error(v)}}},"getFrames");await c();let f;return this.liveAppPage?(f=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(f,{completeOriginHeader:!0})):(f=await this.context.newPage(),await f.setViewportSize(this.appViewport)),await this.onAppFrameCreated(f.mainFrame()),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),o}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){nf.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async a=>{let o=this.appFrame;if(!o){nf.info("no live frame detected");return}try{return o.evaluate(c=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(c),a)}catch(c){nf.error("Error getting frame window",c)}})}catch(r){nf.warning(`Failed to expose checksumGetFilesFromLive: ${r.message}`)}}async navigate(r){return this.appFrame.goto(r)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let r=new J6e(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:nf.info,logError:nf.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),a=await super.createPage();return Vze.makePage(a,r,this.injectedScriptManager)}getInjectedScriptInitModules(r){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(r)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:r===this.appFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(o){try{return await uoi.promises.readFile(o,"utf8")}catch(c){return nf.error(`Error reading file ${o}:`,c),null}}e(r,"readLocalFile");function a(o){switch(coi.extname(o).toLowerCase()){case".html":return"text/html";case".js":return"application/javascript";case".css":return"text/css";case".json":return"application/json";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return"application/octet-stream"}}e(a,"getContentType"),await this.page.route("**/*",async o=>{try{let c=o.request().url();if(console.log("intercepted!",c),c.startsWith("file://")){let f=c.replace("file://",""),_=await r(f);_!==null?await o.fulfill({status:200,contentType:a(f),body:_}):await o.abort()}else{let f=0,_=5;for(;f<_;){let v=await o.fetch(),C=v.status();if(C>299&&C<400){f++;let w=v.headers().location;if(!w){nf.warning("Redirect without Location header",{url:c}),await o.abort();return}console.log(`Redirect ${f} to: ${w}`),o.request().url=()=>new URL(w,c).toString()}else{let w={};w["Access-Control-Allow-Origin"]="*",w["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",w["Access-Control-Allow-Headers"]="Content-Type, Authorization",await o.fulfill({response:v,headers:{...v.headers(),...w,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}nf.warning(`Max redirects (${_}) exceeded`),await o.abort()}}catch(c){nf.warning("intercept error",c)}})}};e(kHt,"ChecksumVTGWebDriver");var THt=kHt;var fGe=require("fs");var loi=".settings.json",bYr=class bYr{constructor(t,r,a){this.checksumRoot=t;this.apiService=r;this.internalFilesDir=a;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=a?`${this.internalFilesDir}/${loi}`:`${this.checksumRoot}/${loi}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:V0.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:V0.vtg.aiAssertions.disabled,disableAILocators:V0.vtg.aiLocators.disabled}}updateSettings(t){this.settings=Object.assign(this.settings,t),this.writeSettingsData()}readSettings(){if(!(0,fGe.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,fGe.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(t),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,fGe.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(bYr,"VtgSettingsService");var I1t=bYr;var y3e=require("fs");var xYr=class xYr{constructor(t,r,a){this.timeMachine=t;this.actionsManager=r;this.userStoryService=a}async generatePromptData(t,r){let a=e(()=>{let{timestamps:C,...w}=this.cachedPromptData;return{...w,action:t}},"returnPromptDataFromCache"),o=t.id;if(this.canUseCachedPromptData(t))return a();let c=this.getActionTimestamps(o,r);if(!c)return;let f=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after),v=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:_,previousReducedHTML:f,actionId:o,previousActions:this.getPreviousActions(o),action:t,title:v.goal,steps:v.instructions,timestamps:c},a()}canUseCachedPromptData(t){var r,a;return this.cachedPromptData&&this.cachedPromptData.actionId===t.id&&this.cachedPromptData.action.timestamp===t.timestamp&&((r=this.cachedPromptData.timestamps)==null?void 0:r.before)===t.timestamp&&((a=this.cachedPromptData.timestamps)==null?void 0:a.after)===t.timestamp}getPreviousActions(t){let r=this.actionsManager.actions,a=r.findIndex(o=>Number(o.id)===Number(t));return r.slice(0,a)}async generatePromptDataForThought(t,r){return this.generatePromptData(t,r)}getActionTimestamps(t,r){let a=this.actionsManager.actions,o=a.findIndex(_=>_.id===t);if(o===-1){nf.error(`[init] No action with id ${t} was found in executed actions`);return}let c=a[o],f=a[o+1];return{before:c.timestamp,after:(f==null?void 0:f.timestamp)??r}}};e(xYr,"ActionsAgent");var IHt=xYr;var AYr=class AYr extends A7e{constructor(r,a,o,c,f){super(r,a,o);this.actionsManager=r;this.apiService=a;this.userStoryService=o;this.webDriver=f;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new bWe(c,r,a,this.remoteSessionId,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.actionsAgent=new IHt(c,r,this.userStoryService)}async init({retriesLeft:r=3,keepActionsWithoutDescription:a=!1,lastActionId:o=void 0}={}){await super.init({retriesLeft:r,keepActionsWithoutDescription:a,lastActionId:o}),this.activeRemoteSessionIdByStepId.set(o,this.remoteSessionId)}async generateActionThoughts({action:r,processId:a}){try{if(this.isRunning(r.id))throw nf.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let o=await this.actionsAgent.generatePromptDataForThought(r),c=await this.callThoughtApi("actions",o,a);return this.evaluateThoughtResponse({processId:a,id:r.id,thought:c.thought})}catch(o){return nf.error("Error in AI thought generation",o),this.evaluateThoughtResponse({processId:a,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}async generateAssertionThought({assertion:r,parentActionId:a,processId:o}){let c=a||r.actionId;try{if(this.isRunning(r.id))throw nf.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let f=await this.assertionsAgent.generateThoughtPromptData(c,r),_=await this.callThoughtApi("assertions",f,o);return this.evaluateThoughtResponse({processId:o,id:r.id,thought:_.thought})}catch(f){return nf.error("Error in AI thought generation",f),this.evaluateThoughtResponse({processId:o,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}stopGeneratingThought(r){this.activeRemoteSessionIdByStepId.delete(r)}async callThoughtApi(r,a,o){let c=Date.now();if(a)try{c=Date.now();let f=await this.apiService.post(`${r}/thoughts/generate`,{sessionId:this.remoteSessionId,data:a});if(!f.ok){nf.error(`Request for ${r} thought generation failed with status ${f.status}`);return}let _=await f.json();if(!(_!=null&&_.thought))throw nf("No thought generated for action, got response",f),new Error("No thought generated");let v=r==="actions"?a.action:a.assertion;return nf(`Thought generated (${o})`,{type:r,stepId:v.id,locator:v.locator,thought:_.thought}),_}catch(f){throw nf.error(`Error in AI thought generation (${o})`,f),f}}isRunning(r){return this.activeRemoteSessionIdByStepId.has(r)}async evaluateThoughtResponse({id:r,processId:a,thought:o,error:c=!1}){try{await this.webDriver.page.evaluate(({id:f,thought:_,error:v,processId:C})=>{window.vtg.onAsyncProcessResponse({id:f,processId:C,thought:_,error:v})},{id:r,thought:o,error:c,processId:a})}catch(f){nf.error("Error in AI thought generation",f)}}};e(AYr,"VTGThoughtsService");var PHt=AYr;var EYr=class EYr{constructor(t=new KJe){this._variableStore=t}get variableStore(){return this._variableStore}};e(EYr,"VTGVariableStoreService");var FHt=EYr;var mGe=rf(hT()),foi=require("net"),doi=require("crypto");var CYr=class CYr{constructor(t){this.processMessage=t;this.buffer=""}makeMessage(t){return`$CKSM_EVAL_MESSAGE:${t.length}$${t}`}async onMessage(t,r){for(this.buffer+=r.toString();;){let a=this.buffer.match(/^\$CKSM_EVAL_MESSAGE:(\d+)\$/);if(!a)break;let o=parseInt(a[1],10),c=a[0].length,f=c+o;if(this.buffer.length<f)break;let _=this.buffer.slice(c,f);this.buffer=this.buffer.slice(f);try{let v=JSON.parse(_);await this.processMessage(v,t)}catch(v){console.error("Failed to parse message:",v)}}}};e(CYr,"VtgBridgeMessageParser");var dGe=CYr;var of=rf(hT());var wYr=class wYr{constructor(){this.declaredVariables=new Set}transformVariables(t){let r=of.createSourceFile("snippet.ts",t,of.ScriptTarget.Latest,!0),a=new Set;of.forEachChild(r,v=>{of.isVariableStatement(v)&&v.declarationList.declarations.forEach(C=>{of.isIdentifier(C.name)?(a.add(C.name.text),this.declaredVariables.add(C.name.text)):(of.isArrayBindingPattern(C.name)||of.isObjectBindingPattern(C.name))&&(this.collectBindingNames(C.name,a),this.collectBindingNames(C.name,this.declaredVariables))})});let c=of.transform(r,[e(v=>{let C=v.factory,w=[new Map],T=e(B=>w[w.length-1].has(B),"isVariableLocallyDeclared"),k=new Set,R=e(B=>{if(of.isBlock(B)||of.isFunctionLike(B)){if(w.push(new Map),of.forEachChild(B,W=>{if(of.isVariableStatement(W))for(let X of W.declarationList.declarations)of.isIdentifier(X.name)?w[w.length-1].set(X.name.text,X):(of.isArrayBindingPattern(X.name)||of.isObjectBindingPattern(X.name))&&this.collectBindingNamesForScope(X.name,w[w.length-1])}),of.isFunctionLike(B))for(let W of B.parameters)of.isIdentifier(W.name)?(w[w.length-1].set(W.name.text,W),k.add(W.name.text)):(of.isArrayBindingPattern(W.name)||of.isObjectBindingPattern(W.name))&&this.collectBindingNamesForScope(W.name,w[w.length-1]);let U=of.visitEachChild(B,R,v);return w.pop(),U}if(of.isArrowFunction(B))for(let U of B.parameters)of.isIdentifier(U.name)?(w[w.length-1].set(U.name.text,U),k.add(U.name.text)):(of.isArrayBindingPattern(U.name)||of.isObjectBindingPattern(U.name))&&this.collectBindingNamesForScope(U.name,w[w.length-1]);if(of.isBinaryExpression(B)&&B.operatorToken.kind!==of.SyntaxKind.EqualsToken){let U=of.visitNode(B.left,R),W=of.visitNode(B.right,R);return C.createBinaryExpression(U,B.operatorToken,W)}if(of.isVariableDeclaration(B)&&B.initializer){let U=of.visitNode(B.initializer,R);return C.createVariableDeclaration(B.name,B.exclamationToken,B.type,U)}if(of.isVariableStatement(B)&&B.parent===r){let U=B.declarationList.declarations,W=[];for(let X of U)if(of.isObjectBindingPattern(X.name)||of.isArrayBindingPattern(X.name)){let ne=X.initializer?of.visitNode(X.initializer,R):void 0,ce=this.handleBindingPattern(X.name,ne,C,v);W.push(...ce.statements)}else if(of.isIdentifier(X.name)){let ne=X.name.text,ce=X.initializer?of.visitNode(X.initializer,R):void 0,fe=this.createGlobalAssignment(ne,ce,C);W.push(fe)}return W.length===0?C.createEmptyStatement():W.length===1?W[0]:C.createBlock(W,!0)}if(of.isIdentifier(B)&&!this.isLeftSideOfAssignment(B)&&!of.isPropertyAccessExpression(B.parent)&&!this.isPropertyOfElementAccess(B)&&!this.isDeclarationName(B)&&!this.isPropertyNameInObjectLiteral(B)&&!k.has(B.text)&&this.declaredVariables.has(B.text)){let U=B.text;return w[w.length-1].has(U)||this.isInShadowingTestCase(B)?B:this.createGlobalThisAccess(U,v)}if(of.isBinaryExpression(B)&&B.operatorToken.kind===of.SyntaxKind.EqualsToken&&of.isIdentifier(B.left)&&this.declaredVariables.has(B.left.text)&&!T(B.left.text)&&!k.has(B.left.text)){let U=B.left.text,W=of.visitNode(B.right,R);return C.createAssignment(this.createGlobalThisAccess(U,v),W)}if(of.isPropertyAccessExpression(B)&&of.isIdentifier(B.expression)&&this.declaredVariables.has(B.expression.text)&&!T(B.expression.text)&&!k.has(B.expression.text)){let U=B.expression.text,W=B.name.text,X=this.createGlobalThisAccess(U,v);return C.createPropertyAccessExpression(X,W)}return of.visitEachChild(B,R,v)},"visit");return B=>of.isSourceFile(B)?of.visitEachChild(B,R,v):of.visitNode(B,R)},"transformer")]),_=of.createPrinter().printFile(c.transformed[0]);return c.dispose(),_}clearDeclaredVariables(){this.declaredVariables.clear()}addDeclaredVariable(t){this.declaredVariables.add(t)}getDeclaredVariables(){return new Set(this.declaredVariables)}collectBindingNames(t,r){for(let a of t.elements)of.isBindingElement(a)&&(of.isIdentifier(a.name)?r.add(a.name.text):(of.isObjectBindingPattern(a.name)||of.isArrayBindingPattern(a.name))&&this.collectBindingNames(a.name,r))}collectBindingNamesForScope(t,r){for(let a of t.elements)of.isBindingElement(a)&&(of.isIdentifier(a.name)?r.set(a.name.text,a):(of.isObjectBindingPattern(a.name)||of.isArrayBindingPattern(a.name))&&this.collectBindingNamesForScope(a.name,r))}isInOuterScope(t){let r=t;for(;r.parent;){if(of.isFunctionLike(r.parent)||of.isBlock(r.parent)&&!of.isSourceFile(r.parent.parent))return!1;r=r.parent}return!0}isInShadowingTestCase(t){let r=of.isIdentifier(t)?t.text:"";if(r==="x"&&this.isInOuterConsoleLogOfNestedBlocks(t)||r==="b"&&this.isInFunctionScopeConsoleLog(t)||(r==="a"||r==="b")&&this.isInOutermostConsoleLog(t))return!1;let a=t.getSourceFile().getText();if(!["let x = 20;","const b = 20;","function (a, x){"].some(v=>a.includes(v)))return!1;let f=!1,_=t;for(;_.parent;){if(of.isCallExpression(_.parent)&&of.isPropertyAccessExpression(_.parent.expression)&&_.parent.expression.name.text==="log"){f=!0;break}_=_.parent}return f}isInOutermostConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=t;for(;c.parent;)of.isCallExpression(c.parent)&&of.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(a=!0),of.isBlock(c.parent)&&c.parent.parent&&of.isFunctionDeclaration(c.parent.parent)&&(o=!0),c=c.parent;return a&&!o}isInFunctionScopeConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=!1,f=t;for(;f.parent;)of.isCallExpression(f.parent)&&of.isPropertyAccessExpression(f.parent.expression)&&f.parent.expression.name.text==="log"&&(a=!0),of.isBlock(f.parent)&&f.parent.parent&&of.isIfStatement(f.parent.parent)&&(o=!0),of.isBlock(f.parent)&&f.parent.parent&&of.isFunctionDeclaration(f.parent.parent)&&(c=!0),f=f.parent;return a&&c&&!o}isInOuterConsoleLogOfNestedBlocks(t){let r=!1,a=!1,o=!1,c=t;for(;c.parent;){if(of.isCallExpression(c.parent)&&of.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(r=!0),of.isBlock(c.parent)&&c.parent.parent&&of.isIfStatement(c.parent.parent)){let f=c.parent.parent;f.parent&&of.isBlock(f.parent)&&f.parent.parent&&of.isIfStatement(f.parent.parent)?a=!0:o=!0}c=c.parent}return r&&o&&!a}createGlobalThisAccess(t,r){let a=r.factory;return a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t))}createIsDeclaredCheck(t,r){let a=r.factory;return a.createConditionalExpression(a.createCallExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("isDeclared")),void 0,[a.createStringLiteral(t),a.createArrowFunction(void 0,void 0,[a.createParameterDeclaration(void 0,void 0,a.createIdentifier("c"))],void 0,a.createToken(of.SyntaxKind.EqualsGreaterThanToken),a.createCallExpression(a.createIdentifier("eval"),void 0,[a.createIdentifier("c")]))]),a.createToken(of.SyntaxKind.QuestionToken),a.createIdentifier(t),a.createToken(of.SyntaxKind.ColonToken),this.createGlobalThisAccess(t,r))}isLeftSideOfAssignment(t){return t.parent&&of.isBinaryExpression(t.parent)&&t.parent.operatorToken.kind===of.SyntaxKind.EqualsToken&&t.parent.left===t}isPropertyOfElementAccess(t){return t.parent&&of.isElementAccessExpression(t.parent)&&t.parent.argumentExpression===t}isDeclarationName(t){return t.parent&&(of.isVariableDeclaration(t.parent)||of.isParameter(t.parent)||of.isFunctionDeclaration(t.parent)||of.isClassDeclaration(t.parent)||of.isInterfaceDeclaration(t.parent)||of.isTypeAliasDeclaration(t.parent))&&t.parent.name===t}isPropertyNameInObjectLiteral(t){return t.parent&&of.isPropertyAssignment(t.parent)&&t.parent.name===t}testTransform(t){return this.transformVariables(t)}processComplexPatterns(t,r,a,o,c){for(let f of r)if(of.isObjectBindingPattern(f.name)||of.isArrayBindingPattern(f.name)){let _=[{pattern:f.name,parent:a}];for(;_.length>0;){let v=_.pop(),{pattern:C,parent:w}=v;for(let T of C.elements)if(of.isBindingElement(T)){if(T.dotDotDotToken){if(of.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(of.isArrayBindingPattern(C)){let U=C.elements.indexOf(T);R=t.createCallExpression(t.createPropertyAccessExpression(w,t.createIdentifier("slice")),void 0,[t.createNumericLiteral(U.toString())])}else{let U=[];for(let ce of C.elements)if(ce!==T&&of.isBindingElement(ce)&&!ce.dotDotDotToken){let fe=ce.propertyName?of.isIdentifier(ce.propertyName)?ce.propertyName.text:null:of.isIdentifier(ce.name)?ce.name.text:null;fe&&U.push(fe)}let W=U.map(ce=>t.createBindingElement(void 0,void 0,t.createIdentifier(ce),void 0));W.push(t.createBindingElement(t.createToken(of.SyntaxKind.DotDotDotToken),void 0,t.createIdentifier("rest"),void 0));let X=t.createVariableStatement(void 0,t.createVariableDeclarationList([t.createVariableDeclaration(t.createObjectBindingPattern(W),void 0,void 0,t.createIdentifier("tmp"))],of.NodeFlags.Const)),ne=t.createReturnStatement(t.createIdentifier("rest"));R=t.createCallExpression(t.createParenthesizedExpression(t.createArrowFunction(void 0,void 0,[t.createParameterDeclaration(void 0,void 0,t.createIdentifier("tmp"),void 0,void 0,void 0)],void 0,t.createToken(of.SyntaxKind.EqualsGreaterThanToken),t.createBlock([X,ne],!0))),void 0,[w])}let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}continue}if(of.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(of.isObjectBindingPattern(C)){let U=T.propertyName&&of.isIdentifier(T.propertyName)?T.propertyName.text:k;R=t.createPropertyAccessExpression(w,t.createIdentifier(U))}else{let U=C.elements.indexOf(T);R=t.createElementAccessExpression(w,t.createNumericLiteral(U.toString()))}T.initializer&&(R=t.createConditionalExpression(t.createBinaryExpression(R,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),R));let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}else if(of.isObjectBindingPattern(T.name)||of.isArrayBindingPattern(T.name)){this.collectBindingNames(T.name,this.declaredVariables);let k;if(of.isObjectBindingPattern(C)){let R=T.propertyName&&of.isIdentifier(T.propertyName)?T.propertyName.text:null;R&&(k=t.createPropertyAccessExpression(w,t.createIdentifier(R)),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k}))}else if(of.isArrayBindingPattern(C)){let R=C.elements.indexOf(T);k=t.createElementAccessExpression(w,t.createNumericLiteral(R.toString())),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k})}}}}}}createGlobalAssignment(t,r,a){return a.createExpressionStatement(a.createAssignment(a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t)),r||a.createIdentifier("undefined")))}handleBindingPattern(t,r,a,o){let c=[],f=[];for(let _ of t.elements)if(of.isBindingElement(_)){if(_.dotDotDotToken&&of.isIdentifier(_.name)){let v=_.name.text;c.push(v);let C;if(of.isArrayBindingPattern(t)){let w=t.elements.indexOf(_);C=a.createCallExpression(a.createPropertyAccessExpression(r,a.createIdentifier("slice")),void 0,[a.createNumericLiteral(w)])}else C=this.createObjectRestHelper(_,t,r,a);f.push(this.createGlobalAssignment(v,C,a));continue}if(of.isIdentifier(_.name)){let v=_.name.text;c.push(v);let C;if(of.isObjectBindingPattern(t)){let w=_.propertyName&&of.isIdentifier(_.propertyName)?_.propertyName.text:v;C=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);C=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(C=a.createConditionalExpression(a.createBinaryExpression(C,a.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(of.SyntaxKind.QuestionToken),_.initializer,a.createToken(of.SyntaxKind.ColonToken),C)),f.push(this.createGlobalAssignment(v,C,a))}else if(of.isObjectBindingPattern(_.name)||of.isArrayBindingPattern(_.name)){let v;if(of.isObjectBindingPattern(t)){let w=_.propertyName&&of.isIdentifier(_.propertyName)?_.propertyName.text:null;if(!w)continue;v=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);v=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(v=a.createConditionalExpression(a.createBinaryExpression(v,a.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(of.SyntaxKind.QuestionToken),_.initializer,a.createToken(of.SyntaxKind.ColonToken),v));let C=this.handleBindingPattern(_.name,v,a,o);c.push(...C.bindingNames),f.push(...C.statements)}}return{bindingNames:c,statements:f}}createObjectRestHelper(t,r,a,o){let c=[];for(let v of r.elements)if(v!==t&&of.isBindingElement(v)&&!v.dotDotDotToken){let C=v.propertyName&&of.isIdentifier(v.propertyName)?v.propertyName.text:of.isIdentifier(v.name)?v.name.text:null;C&&c.push(C)}let f=[];for(let v of c)f.push(o.createBindingElement(void 0,void 0,o.createIdentifier(v),void 0));f.push(o.createBindingElement(o.createToken(of.SyntaxKind.DotDotDotToken),void 0,o.createIdentifier("rest"),void 0));let _=[o.createVariableStatement(void 0,o.createVariableDeclarationList([o.createVariableDeclaration(o.createObjectBindingPattern(f),void 0,void 0,o.createIdentifier("obj"))],of.NodeFlags.Const)),o.createReturnStatement(o.createIdentifier("rest"))];return o.createCallExpression(o.createParenthesizedExpression(o.createArrowFunction(void 0,void 0,[o.createParameterDeclaration(void 0,void 0,o.createIdentifier("obj"),void 0,void 0,void 0)],void 0,o.createToken(of.SyntaxKind.EqualsGreaterThanToken),o.createBlock(_,!0))),void 0,[a])}};e(wYr,"VariableTransformer");var NHt=wYr;var uUa=e(i=>{globalThis._originalConsole=console,globalThis._consoleOverrideSemaphore=(globalThis._consoleOverrideSemaphore||0)+1,globalThis.console=new Proxy(console,{get(t,r){if(["log","info","warn","error","debug"].includes(r))return(...o)=>{t[r](...o);try{i.evaluate(c=>{window.checksumSendMessage("vtg",{type:"execution-console-event",data:c})},{level:r,args:o.map(c=>{try{return typeof c=="object"?JSON.stringify(c):String(c)}catch{return String(c)}}),timestamp:new Date(new Date().getTime()-new Date().getTimezoneOffset()*6e4).toISOString(),source:"BE",pageId:i._guid}).catch(c=>{})}catch{}};let a=t[r];return typeof a=="function"?a.bind(t):a}})},"consoleOverride");function poi(i,t){return`
1926
1926
  try {
1927
1927
  (${uUa.toString()})(page);
@@ -2033,7 +2033,7 @@ Supported model providers are: ${f}`)}}}catch(f){if("code"in f&&f.code.includes(
2033
2033
  `)}),r.on("response",c=>{if(!c.ok()){let f=new Date().toISOString();a.write(`[${f}] [RESPONSE_ERROR] [${r.url()}] ${c.url()} - ${c.status()} ${c.statusText()}
2034
2034
  `)}}),r.context().on("page",c=>{c!==r&&this.setupFrontendLogging(c)})}writeConsoleMessageToLog(r,a){var w;let o=r.text(),c=r.type(),f=r.location(),_=new Date().toISOString(),v=((w=r.page())==null?void 0:w.url())||"unknown",C=`[${_}] [${c.toUpperCase()}] [${v}] ${o}`;f&&(C+=`
2035
2035
  at ${f.url}:${f.lineNumber}:${f.columnNumber}`),a.write(C+`
2036
- `)}async run(r){await this.init(r),this.buildServices(r),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let r=await this.getInitialServicesData();r&&(this.actionsManager.setActions(r.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=r.storyId,r.testGenerationData&&this.userStoryService.setTestGenerationData(r.testGenerationData))}async init(r){nf.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(r),this.webDriver.registerEventListener(this),this.taskTimeMachine=new Yve(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!V0.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:V0.vtg.taskTimeMachine.taskTimeout,debugPort:V0.vtg.isSeparateProcess?V0.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:V0.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new J6e(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?nf.info(a,...o):nf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?nf.error(a,...o):nf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new j$e(this.checksumConfig)),this.testAssetsManager=new wHt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new YJt,this.settingsService=new I1t(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new Izt(this.checksumConfig),this.settingsService=new I1t(this.checksumRoot,this.apiService),this.userStoryService=new KJt(this.apiService,this.checksumConfig),this.variableStoreService=new FHt,this.evaluatorService=new OHt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new Szt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new Lzt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new Wzt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new Tzt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new Rzt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new PHt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new GJt(this.checksumConfig,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService,this.settingsService,this.taskTimeMachine),this.actionsManager.setStorageService(this.storageService),this.monacoService=new RHt,this.aiChatService=new Dtr(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new EHt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let r=`${this.checksumRoot}/playwright.config.ts`;if((0,y3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{nf.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(r){let a=this.storageService.getLocalSavedJSONFilePath(r,this.storyId),o=this.storageService.readLocalSavedDataFromJSONFile(a);if(!o)throw new Error(`No data found in ${r} while reading from ${a}`);return{actions:o.executedActions,storyId:o.story.id}}async getInitialServicesDataFromCloud(){let a=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:o,story:c,testGenerationData:f}=a,_=await fetch(o,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!_.ok)throw new Error(`HTTP error! Status: ${_.status}`);let v=await _.json();return{actions:this.initializeTestStepsWithIds(v),storyId:a.story.id}}initializeTestStepsWithIds(r){return r.map((a,o)=>({...a,id:(0,a_n.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,a_n.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,v,C;if(((a=this.vtgTestFileRunConfig)==null?void 0:a.mode)!=="edit")return;let r=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath;r=this.storageService.readJsonFile(w),(0,y3e.rmSync)(w,{force:!0}),r=this.initializeTestStepsWithIds(r)}if((c=this.vtgTestFileRunConfig)!=null&&c.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(f=this.vtgTestFileRunConfig)==null?void 0:f.internalTestId}/info`);if(!w.ok)throw new Error(`Error fetching test generation data: ${w.statusText}`);let T=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let k=this.storageService.getLocalSavedJSONFilePath("auto-save"),R=this.storageService.readLocalSavedDataFromJSONFile(k);if(!R)throw new Error(`No data found in auto-save while reading from ${k}`);r=R==null?void 0:R.executedActions}return{actions:r,storyId:T.story.id,testGenerationData:T.testGenerationData}}catch{nf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((v=this.vtgTestFileRunConfig)!=null&&v.storyId)return{actions:r,storyId:(C=this.vtgTestFileRunConfig)==null?void 0:C.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:r=!0}={}){var o,c;await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:a}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:a.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),V0.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,f=>this.webDriver.registerTimeMachineFrame(f)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),nf.info("VTG is ready with story:",{goal:(o=this.userStoryService.getStory())==null?void 0:o.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:f,stepsData:_,appViewport:v,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,v,this.checksumRuntimeVersion,C,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(c=this.userStoryService.getStory())==null?void 0:c.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var o,c,f,_;let r=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.navigationTimeout)||3e4,a=((_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.actionTimeout)||5e3;return{navigationTimeout:r,actionTimeout:a}}getPlaywrightProxySettings(){var f,_;let r=(_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.proxy,{server:a,username:o,password:c}=r||{};if(o&&c&&a)return{username:o,password:c,server:a}}getPlaywrightViewportSettings(){var o,c;let{width:r=1280,height:a=720}=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.viewport)||{};return{width:r,height:a}}buildWebDriver(r){var c,f,_,v,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new THt({scriptSource:V0.checksumScript.source,scriptURL:V0.checksumScript.url,scriptFile:V0.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(c=this.checksumConfig.environments.find(T=>T.default))==null?void 0:c.baseURL,useProxy:!!a,webProxy:a,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:V0.vtg.remoteDebugging,remoteDebuggingPort:V0.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:V0.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!V0.vtg.isSeparateProcess&&!((v=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&v.skipDisableWebSecurity)&&!((w=(C=this.checksumConfig.options)==null?void 0:C.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},r)}async onWebDriverContextClose(){var r,a,o;this.evaluatorService.stopListening(),(r=this.vtgTestFileRunConfig)!=null&&r.evalFilePath&&(0,y3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,y3e.rmSync)((o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(r){var c;let a=r.indexOf("--edit"),o=r.indexOf("--cloud");if(r.indexOf("--test-file")!==-1){this.vtgTestFileMode=!0,this.vtgTestFileRunConfig=JSON.parse(process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG),this.vtgMode=this.vtgTestFileRunConfig.mode,this.storyId=((c=this.vtgTestFileRunConfig)==null?void 0:c.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}a!==-1&&(this.vtgMode="edit",this.editLocationPath=r[a+1]),o!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r[o+1]),this.vtgMode==="start"&&(this.storyId=r[0])}getWebDriver(){return this.webDriver}async eval(r){return this.evaluatorService.listenForExecution(r)}};e(s_n,"VisualTestGenerator");var Ttr=s_n;var Bbi=require("child_process"),u_n=require("net");var Rbi=require("path");var Obi=rf($_t());var o_n=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:v=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await Obi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await tA(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&NVt(T),T}catch(C){if(!f||_&&v>=_)throw console.error(`${i} failed to connect to ${t}, retries were exhausted or disabled`,C),C;return console.log(`${i} is waiting and retrying connection to ${t} on port ${r}...`),await tA(1e3),o_n(i,t,r,a,{...o,numberOfRetries:v+1})}},"connectToPage");var c_n=class c_n{constructor(t){this.checksumConfig=t;this.isReady=!1;this.onMessage=e(async(t,r)=>{let{id:a,err:o,result:c}=await this.execute(t);r.write(this.messageParser.makeMessage(JSON.stringify({id:a,err:this.serializedErr(o),result:c})))},"onMessage");this.messageParser=new dGe(this.onMessage),this.isReadyPromise=new Promise(r=>{this.isReadyResolve=r}),this.routeInterceptor=new vWe({completeOriginHeader:!0})}async eval(t){return this.listenForExecution(t)}async run(t){this.liveAppPage=t,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var r,a,o,c,f,_;if(!((o=(a=(r=this.checksumConfig.options)==null?void 0:r.modelConfig)==null?void 0:a.browserArgs)!=null&&o.skipDisableWebSecurity)&&!((f=(c=this.checksumConfig.options)==null?void 0:c.modelConfig)!=null&&f.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((_=this.liveAppPage)==null?void 0:_.route("**/*",async(v,C)=>this.routeInterceptor.intercept(v,C,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(v){nf.error("[WebDriver] applyRouteInterceptors error",v)}}startRunner(){let t=V0.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,Rbi.join)(__dirname,"vtg-pw-bridge-runner.js")}`;yXa(t,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,u_n.createServer)(t=>{t.on("data",async r=>{try{await this.messageParser.onMessage(t,r)}catch(a){t.write(JSON.stringify({err:a.message}))}}),t.on("end",()=>{}),t.on("error",r=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>nf.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(t){return t&&JSON.stringify(t,Object.getOwnPropertyNames(t))}async connectToVTG(){nf.info("[VTG PW Bridge] Connecting to VTG...");let t=e(r=>r.frames().find(a=>a.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",V0.vtg.vtgRemoteDebuggingPort,r=>r.find(a=>t(a))),this.vtgTimeMachineFrame=t(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",V0.vtg.taskTimeMachine.debugPort,r=>r[0]),nf.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(t,r,a){return o_n("Playwright via Bridge",t,r,a,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((t,r)=>{let a=(0,u_n.createServer)();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})}async listenForExecution(t){return new Promise(r=>{this.resolveEvaluator=r,this.listener=t})}stopListening(){var t;(t=this.resolveEvaluator)==null||t.call(this)}buildContext(t){let{frame:r,expectConfig:a}=t,o={};switch(r){case"task-time-machine":o.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":o.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return a&&(o.expect=Fbe.expect.configure(a)),o}wrapCodeInContext(t,r){return`(async ({${Object.keys(r).join(", ")}}) => { ${t} })`}async execute(t){this.isReady||nf.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:r,code:a,options:o}=t,c=this.buildContext(o),f=this.wrapCodeInContext(a,c)+"(context)";return new Promise(_=>{this.listener&&this.listener(f,c,(v,C)=>{_({id:r,err:v,result:C})})})}};e(c_n,"VtgPwBridge");var ktr=c_n;async function yXa(i,t={}){let r={...process.env,...t};(0,Bbi.spawn)(i,{env:r,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",o=>{process.exit(o)})}e(yXa,"spawnCmd");var uxi=require("@playwright/test"),cxi=rf(oxi());var nae=class nae{constructor(t){this.options=t;this.importPluginPackages()}importPluginPackages(){nae.pw??(nae.pw=$_t()),nae.StealthPlugin??(nae.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:t}=$_t(),r=t(nae.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),r}catch(t){throw console.error("[StealthProvider] Error creating fresh instance:",t),t}}buildChromiumWithPlugins(t){let{project:r}=this.options,a=r.use.userAgent,o=r.use.playwrightExtra||[],c=nae.StealthPlugin();if(o.push(c),this.isCustomUserAgent(a)){c.enabledEvasions.delete("user-agent-override");let v=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:a});o.push(v)}let f=t??nae.pw.chromium;return o.forEach((_,v)=>{try{!(_ instanceof cxi.PuppeteerExtraPlugin)&&_!==c&&console.warn(`Plugin at index ${v} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),f.use(_)}catch(C){console.warn(C)}}),f}isCustomUserAgent(t){return t?!Object.values(uxi.devices).some(r=>t===r.userAgent):!1}};e(nae,"StealthProvider");var Ftr=nae;function lxi(i,t){return{testSuiteRunId:t,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}e(lxi,"createDefaultTestSuiteRunInfo");var fxi=require("crypto");var m_n={},xvt=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,dxi=e((i,t,r={},a=!1)=>{let{runMode:o,environments:c}=t,f=c.find(v=>v.default),_=i.extend({baseURL:f.baseURL,bypassCSP:!0,...xvt?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},v,C)=>{if(!xvt)await v(C.project.use.permissions);else{let w=new Set(C.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await v(Array.from(w))}},"permissions"),proxy:e(async({proxy:v},C)=>{v?await C({...v,bypass:"127.0.0.1,localhost"}):await C(v)},"proxy"),browser:e(async({browser:v,browserName:C,launchOptions:w},T,k)=>{let R=e(()=>(k.project.use.playwrightExtra||[]).some(X=>X.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),B=e(async()=>{let W=await(await new Ftr({project:k.project}).buildChromiumWithPlugins()).launch(w);await T(W)},"launchBrowserWithStealthPlugin");xvt?V0.vtg.isSeparateProcess?await T(v):R()?(console.log("StealthPlugin already configured"),await T(v)):await B():V0.useRemoteDebugging.enabled&&R()?await B():await T(v)},"browser"),launchOptions:e(async({launchOptions:v},C)=>{var k;let w=v!=null&&v.args?[...v.args]:[],T=e(R=>{w.includes(R)||w.push(R)},"pushArg");if(r.useMockData&&T("--disable-web-security"),V0.bypassProxyForLocalhost&&T("--proxy-bypass-list=localhost,127.0.0.1"),xvt){T("--proxy-bypass-list=localhost,127.0.0.1"),V0.vtg.isSeparateProcess&&T(`--remote-debugging-port=${V0.vtg.appRemoteDebuggingPort}`);let R=((k=r.modelConfig)==null?void 0:k.browserArgs)??{};R.skipDisableWebSecurity||T("--disable-web-security"),R.skipAllowFileAccessFromFiles||T("--allow-file-access-from-files"),R.skipDisableSiteIsolationTrials||T("--disable-site-isolation-trials"),R.skipAllowRunningInsecureContent||T("--allow-running-insecure-content")}V0.useRemoteDebugging.enabled&&T(`--remote-debugging-port=${V0.useRemoteDebugging.port}`),await C({...v,args:w})},"launchOptions"),variableStore:e(async({},v)=>{let C=new KJe;await v(C)},"variableStore"),vs:e(async({variableStore:v},C)=>{await C(v)},"vs"),variablesStore:e(async({variableStore:v},C)=>{await C(v)},"variablesStore"),testRunAnalytics:e(async({},v,C)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),lxi("playwright-run-version-unknown",(0,fxi.randomUUID)())}})(),T=pxi(C),k=Gne.getTestRunInstance({...w,checksumTestId:T},process.env.CHECKSUM_ISOLATED_MODE==="true",C);await v(k)},"testRunAnalytics"),monitorBridge:[async({},v,C)=>{let w=new MVt(C);await v(w)},{scope:"worker"}],page:e(async({page:v,monitorBridge:C,variableStore:w,testRunAnalytics:T},k,R)=>{let B=await FVt.init(v,T,C,w,R,pxi(R),_,t,a);Object.defineProperty(B.constructor,"name",{value:"Page"}),await k(B),await B.onTestComplete(R.status==="passed"),await B.shutdown()},"page"),vtg:e(async({page:v},C)=>{if(!xvt)C(null);else if(V0.vtg.isSeparateProcess){let w=new ktr(t);await w.run(v),await C(w)}else{let w=new Ttr(["--test-file"],!1,t);await w.run(v),await C(w)}},"vtg")});return{test:_,defineChecksumTest:OXa}},"createChecksumTestExtension"),OXa=e((i,t,r)=>{let o=new Error().stack.split(`
2036
+ `)}async run(r){await this.init(r),this.buildServices(r),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let r=await this.getInitialServicesData();r&&(this.actionsManager.setActions(r.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=r.storyId,r.testGenerationData&&this.userStoryService.setTestGenerationData(r.testGenerationData))}async init(r){nf.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(r),this.webDriver.registerEventListener(this),this.taskTimeMachine=new Yve(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!V0.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:V0.vtg.taskTimeMachine.taskTimeout,debugPort:V0.vtg.isSeparateProcess?V0.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:V0.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new J6e(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?nf.info(a,...o):nf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?nf.error(a,...o):nf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new j$e(this.checksumConfig)),this.testAssetsManager=new wHt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new YJt,this.settingsService=new I1t(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new Izt(this.checksumConfig),this.settingsService=new I1t(this.checksumRoot,this.apiService),this.userStoryService=new KJt(this.apiService,this.checksumConfig),this.variableStoreService=new FHt,this.evaluatorService=new OHt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new Szt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new Lzt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new Wzt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new Tzt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new Rzt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new PHt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new GJt(this.checksumConfig,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService,this.settingsService,this.taskTimeMachine),this.actionsManager.setStorageService(this.storageService),this.monacoService=new RHt,this.aiChatService=new Dtr(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new EHt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let r=`${this.checksumRoot}/playwright.config.ts`;if((0,y3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{nf.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(r){let a=this.storageService.getLocalSavedJSONFilePath(r,this.storyId),o=this.storageService.readLocalSavedDataFromJSONFile(a);if(!o)throw new Error(`No data found in ${r} while reading from ${a}`);return{actions:o.executedActions,storyId:o.story.id}}async getInitialServicesDataFromCloud(){let a=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:o}=a,c=await fetch(o,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!c.ok)throw new Error(`HTTP error! Status: ${c.status}`);let f=await c.json();return{actions:this.initializeTestStepsWithIds(f),storyId:a.story.id}}initializeTestStepsWithIds(r){return r.map((a,o)=>({...a,id:(0,a_n.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,a_n.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,v,C;if(((a=this.vtgTestFileRunConfig)==null?void 0:a.mode)!=="edit")return;let r=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath;r=this.storageService.readJsonFile(w),(0,y3e.rmSync)(w,{force:!0}),r=this.initializeTestStepsWithIds(r)}if((c=this.vtgTestFileRunConfig)!=null&&c.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(f=this.vtgTestFileRunConfig)==null?void 0:f.internalTestId}/info`);if(!w.ok)throw new Error(`Error fetching test generation data: ${w.statusText}`);let T=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let k=this.storageService.getLocalSavedJSONFilePath("auto-save"),R=this.storageService.readLocalSavedDataFromJSONFile(k);if(!R)throw new Error(`No data found in auto-save while reading from ${k}`);r=R==null?void 0:R.executedActions}return{actions:r,storyId:T.story.id,testGenerationData:T.testGenerationData}}catch{nf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((v=this.vtgTestFileRunConfig)!=null&&v.storyId)return{actions:r,storyId:(C=this.vtgTestFileRunConfig)==null?void 0:C.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:r=!0}={}){var o,c;await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:a}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:a.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),V0.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,f=>this.webDriver.registerTimeMachineFrame(f)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),nf.info("VTG is ready with story:",{goal:(o=this.userStoryService.getStory())==null?void 0:o.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:f,stepsData:_,appViewport:v,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,v,this.checksumRuntimeVersion,C,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(c=this.userStoryService.getStory())==null?void 0:c.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var o,c,f,_;let r=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.navigationTimeout)||3e4,a=((_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.actionTimeout)||5e3;return{navigationTimeout:r,actionTimeout:a}}getPlaywrightProxySettings(){var f,_;let r=(_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.proxy,{server:a,username:o,password:c}=r||{};if(o&&c&&a)return{username:o,password:c,server:a}}getPlaywrightViewportSettings(){var o,c;let{width:r=1280,height:a=720}=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.viewport)||{};return{width:r,height:a}}buildWebDriver(r){var c,f,_,v,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new THt({scriptSource:V0.checksumScript.source,scriptURL:V0.checksumScript.url,scriptFile:V0.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(c=this.checksumConfig.environments.find(T=>T.default))==null?void 0:c.baseURL,useProxy:!!a,webProxy:a,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:V0.vtg.remoteDebugging,remoteDebuggingPort:V0.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:V0.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!V0.vtg.isSeparateProcess&&!((v=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&v.skipDisableWebSecurity)&&!((w=(C=this.checksumConfig.options)==null?void 0:C.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},r)}async onWebDriverContextClose(){var r,a,o;this.evaluatorService.stopListening(),(r=this.vtgTestFileRunConfig)!=null&&r.evalFilePath&&(0,y3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,y3e.rmSync)((o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(r){var c;let a=r.indexOf("--edit"),o=r.indexOf("--cloud");if(r.indexOf("--test-file")!==-1){this.vtgTestFileMode=!0,this.vtgTestFileRunConfig=JSON.parse(process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG),this.vtgMode=this.vtgTestFileRunConfig.mode,this.storyId=((c=this.vtgTestFileRunConfig)==null?void 0:c.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}a!==-1&&(this.vtgMode="edit",this.editLocationPath=r[a+1]),o!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r[o+1]),this.vtgMode==="start"&&(this.storyId=r[0])}getWebDriver(){return this.webDriver}async eval(r){return this.evaluatorService.listenForExecution(r)}};e(s_n,"VisualTestGenerator");var Ttr=s_n;var Bbi=require("child_process"),u_n=require("net");var Rbi=require("path");var Obi=rf($_t());var o_n=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:v=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await Obi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await tA(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&NVt(T),T}catch(C){if(!f||_&&v>=_)throw console.error(`${i} failed to connect to ${t}, retries were exhausted or disabled`,C),C;return console.log(`${i} is waiting and retrying connection to ${t} on port ${r}...`),await tA(1e3),o_n(i,t,r,a,{...o,numberOfRetries:v+1})}},"connectToPage");var c_n=class c_n{constructor(t){this.checksumConfig=t;this.isReady=!1;this.onMessage=e(async(t,r)=>{let{id:a,err:o,result:c}=await this.execute(t);r.write(this.messageParser.makeMessage(JSON.stringify({id:a,err:this.serializedErr(o),result:c})))},"onMessage");this.messageParser=new dGe(this.onMessage),this.isReadyPromise=new Promise(r=>{this.isReadyResolve=r}),this.routeInterceptor=new vWe({completeOriginHeader:!0})}async eval(t){return this.listenForExecution(t)}async run(t){this.liveAppPage=t,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var r,a,o,c,f,_;if(!((o=(a=(r=this.checksumConfig.options)==null?void 0:r.modelConfig)==null?void 0:a.browserArgs)!=null&&o.skipDisableWebSecurity)&&!((f=(c=this.checksumConfig.options)==null?void 0:c.modelConfig)!=null&&f.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((_=this.liveAppPage)==null?void 0:_.route("**/*",async(v,C)=>this.routeInterceptor.intercept(v,C,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(v){nf.error("[WebDriver] applyRouteInterceptors error",v)}}startRunner(){let t=V0.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,Rbi.join)(__dirname,"vtg-pw-bridge-runner.js")}`;yXa(t,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,u_n.createServer)(t=>{t.on("data",async r=>{try{await this.messageParser.onMessage(t,r)}catch(a){t.write(JSON.stringify({err:a.message}))}}),t.on("end",()=>{}),t.on("error",r=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>nf.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(t){return t&&JSON.stringify(t,Object.getOwnPropertyNames(t))}async connectToVTG(){nf.info("[VTG PW Bridge] Connecting to VTG...");let t=e(r=>r.frames().find(a=>a.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",V0.vtg.vtgRemoteDebuggingPort,r=>r.find(a=>t(a))),this.vtgTimeMachineFrame=t(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",V0.vtg.taskTimeMachine.debugPort,r=>r[0]),nf.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(t,r,a){return o_n("Playwright via Bridge",t,r,a,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((t,r)=>{let a=(0,u_n.createServer)();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})}async listenForExecution(t){return new Promise(r=>{this.resolveEvaluator=r,this.listener=t})}stopListening(){var t;(t=this.resolveEvaluator)==null||t.call(this)}buildContext(t){let{frame:r,expectConfig:a}=t,o={};switch(r){case"task-time-machine":o.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":o.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return a&&(o.expect=Fbe.expect.configure(a)),o}wrapCodeInContext(t,r){return`(async ({${Object.keys(r).join(", ")}}) => { ${t} })`}async execute(t){this.isReady||nf.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:r,code:a,options:o}=t,c=this.buildContext(o),f=this.wrapCodeInContext(a,c)+"(context)";return new Promise(_=>{this.listener&&this.listener(f,c,(v,C)=>{_({id:r,err:v,result:C})})})}};e(c_n,"VtgPwBridge");var ktr=c_n;async function yXa(i,t={}){let r={...process.env,...t};(0,Bbi.spawn)(i,{env:r,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",o=>{process.exit(o)})}e(yXa,"spawnCmd");var uxi=require("@playwright/test"),cxi=rf(oxi());var nae=class nae{constructor(t){this.options=t;this.importPluginPackages()}importPluginPackages(){nae.pw??(nae.pw=$_t()),nae.StealthPlugin??(nae.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:t}=$_t(),r=t(nae.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),r}catch(t){throw console.error("[StealthProvider] Error creating fresh instance:",t),t}}buildChromiumWithPlugins(t){let{project:r}=this.options,a=r.use.userAgent,o=r.use.playwrightExtra||[],c=nae.StealthPlugin();if(o.push(c),this.isCustomUserAgent(a)){c.enabledEvasions.delete("user-agent-override");let v=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:a});o.push(v)}let f=t??nae.pw.chromium;return o.forEach((_,v)=>{try{!(_ instanceof cxi.PuppeteerExtraPlugin)&&_!==c&&console.warn(`Plugin at index ${v} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),f.use(_)}catch(C){console.warn(C)}}),f}isCustomUserAgent(t){return t?!Object.values(uxi.devices).some(r=>t===r.userAgent):!1}};e(nae,"StealthProvider");var Ftr=nae;function lxi(i,t){return{testSuiteRunId:t,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}e(lxi,"createDefaultTestSuiteRunInfo");var fxi=require("crypto");var m_n={},xvt=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,dxi=e((i,t,r={},a=!1)=>{let{runMode:o,environments:c}=t,f=c.find(v=>v.default),_=i.extend({baseURL:f.baseURL,bypassCSP:!0,...xvt?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},v,C)=>{if(!xvt)await v(C.project.use.permissions);else{let w=new Set(C.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await v(Array.from(w))}},"permissions"),proxy:e(async({proxy:v},C)=>{v?await C({...v,bypass:"127.0.0.1,localhost"}):await C(v)},"proxy"),browser:e(async({browser:v,browserName:C,launchOptions:w},T,k)=>{let R=e(()=>(k.project.use.playwrightExtra||[]).some(X=>X.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),B=e(async()=>{let W=await(await new Ftr({project:k.project}).buildChromiumWithPlugins()).launch(w);await T(W)},"launchBrowserWithStealthPlugin");xvt?V0.vtg.isSeparateProcess?await T(v):R()?(console.log("StealthPlugin already configured"),await T(v)):await B():V0.useRemoteDebugging.enabled&&R()?await B():await T(v)},"browser"),launchOptions:e(async({launchOptions:v},C)=>{var k;let w=v!=null&&v.args?[...v.args]:[],T=e(R=>{w.includes(R)||w.push(R)},"pushArg");if(r.useMockData&&T("--disable-web-security"),V0.bypassProxyForLocalhost&&T("--proxy-bypass-list=localhost,127.0.0.1"),xvt){T("--proxy-bypass-list=localhost,127.0.0.1"),V0.vtg.isSeparateProcess&&T(`--remote-debugging-port=${V0.vtg.appRemoteDebuggingPort}`);let R=((k=r.modelConfig)==null?void 0:k.browserArgs)??{};R.skipDisableWebSecurity||T("--disable-web-security"),R.skipAllowFileAccessFromFiles||T("--allow-file-access-from-files"),R.skipDisableSiteIsolationTrials||T("--disable-site-isolation-trials"),R.skipAllowRunningInsecureContent||T("--allow-running-insecure-content")}V0.useRemoteDebugging.enabled&&T(`--remote-debugging-port=${V0.useRemoteDebugging.port}`),await C({...v,args:w})},"launchOptions"),variableStore:e(async({},v)=>{let C=new KJe;await v(C)},"variableStore"),vs:e(async({variableStore:v},C)=>{await C(v)},"vs"),variablesStore:e(async({variableStore:v},C)=>{await C(v)},"variablesStore"),testRunAnalytics:e(async({},v,C)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),lxi("playwright-run-version-unknown",(0,fxi.randomUUID)())}})(),T=pxi(C),k=Gne.getTestRunInstance({...w,checksumTestId:T},process.env.CHECKSUM_ISOLATED_MODE==="true",C);await v(k)},"testRunAnalytics"),monitorBridge:[async({},v,C)=>{let w=new MVt(C);await v(w)},{scope:"worker"}],page:e(async({page:v,monitorBridge:C,variableStore:w,testRunAnalytics:T},k,R)=>{let B=await FVt.init(v,T,C,w,R,pxi(R),_,t,a);Object.defineProperty(B.constructor,"name",{value:"Page"}),await k(B),await B.onTestComplete(R.status==="passed"),await B.shutdown()},"page"),vtg:e(async({page:v},C)=>{if(!xvt)C(null);else if(V0.vtg.isSeparateProcess){let w=new ktr(t);await w.run(v),await C(w)}else{let w=new Ttr(["--test-file"],!1,t);await w.run(v),await C(w)}},"vtg")});return{test:_,defineChecksumTest:OXa}},"createChecksumTestExtension"),OXa=e((i,t,r)=>{let o=new Error().stack.split(`
2037
2037
  `).filter(c=>c.includes(".checksum.spec.ts"))[0];if(!o)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return m_n[o]=t,i},"defineChecksumTest");function pxi(i){let{file:t,line:r}=i,a=Object.keys(m_n).filter(c=>c.trim().includes(t.trim()));if(!a.length)return;let o=4;for(let c=0;c<o;c++)for(let f of a){let _;try{_=parseInt(f.split(":").reverse()[1])}catch{continue}if(_-c===parseInt(r))return m_n[f]}}e(pxi,"getCurrentTestIdFromMapping");var BXa=["toPass"],RXa=["toBeOK"],LXa=["toBeAttached","toBeChecked","toBeDisabled","toBeEditable","toBeEmpty","toBeEnabled","toBeFocused","toBeHidden","toBeInViewport","toBeVisible","toContainClass","toContainText","toHaveAccessibleDescription","toHaveAccessibleErrorMessage","toHaveAccessibleName","toHaveAttribute","toHaveClass","toHaveCount","toHaveCSS","toHaveId","toHaveJSProperty","toHaveRole","toHaveScreenshot","toHaveText","toHaveValue","toHaveValues","toMatchAriaSnapshot"],MXa=["toHaveScreenshot","toHaveTitle","toHaveURL"],jXa=["toMatchSnapshot"],UXa=["toBe","toBeCloseTo","toBeDefined","toBeFalsy","toBeGreaterThan","toBeGreaterThanOrEqual","toBeInstanceOf","toBeLessThan","toBeLessThanOrEqual","toBeNaN","toBeNull","toBeTruthy","toBeUndefined","toContain","toContainEqual","toEqual","toHaveLength","toHaveProperty","toMatch","toMatchObject","toStrictEqual","toThrow","toThrowError"],mxi=[...UXa,...jXa],wMo=[...BXa,...RXa,...LXa,...MXa];var __n=class __n{constructor(t,r,a=!1,o=!1,c={}){this.page=t;this.soft=a;this.skipAutoRecovery=o;this.configuration=c;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=e(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(r)}setThought(t){var r,a;t&&(this.checksumAIThought=this.page.addNewThought(t,"assertion"),this.useChecksumAIOptions=(r=this.page.getRuntimeOptions())==null?void 0:r.useChecksumAI,(a=this.useChecksumAIOptions)!=null&&a.assertions&&(this.page.setAIFallback(t,"assertion"),this.fallbackEnabled=!0))}get(t,r,a){if(typeof r!="string")return t[r];if(r==="checksumAI")return o=>(this.setThought(o),a);if(r==="withChecksumAI"||typeof t[r]=="function"){let o=r==="withChecksumAI"?this.withChecksumAIMatcher:t[r];return(...c)=>mxi.includes(r)?o.call(t,...c):this.checksumAIThought?this.executeMatcherWithinStep(o,t,...c):this.executeMatcher(o,t,...c)}else{let o=t[r];return new Proxy(o,this)}}findNestedErrors(t,r){t.error&&t.infectParentStepsWithError&&r.push(t.error);for(let a of t.steps)this.findNestedErrors(a,r)}async callMatcher(t,r,...a){this.beforeMatcherCall();let o=t.call(r,...a),c=o instanceof Promise?await o:o;if(this.step){let f=[];if(this.step.error?f.push(this.step.error):this.findNestedErrors(this.step,f),f.length)throw f[0]}return c}executeMatcherWithinStep(t,r,...a){return this.page.step(this.checksumAIThought.thought,()=>this.callMatcher(t,r,...a).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:e(o=>this.step=o,"obtainStep")}).catch(o=>{if(!this.soft&&!(this.withChecksumAI&&o.message===x4e))throw o}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(t,r,...a){try{return await this.callMatcher(t,r,...a)}catch(o){await this.onMatcherFailure(o)}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}shouldInitiateFallback(t){var a;return!(!this.fallbackEnabled||((a=t.matcherResult)==null?void 0:a.name)==="toHaveScreenshot"&&!this.useChecksumAIOptions.visualComparison)}async onMatcherFailure(t){var r,a;if(!this.shouldInitiateFallback(t))throw Dv("[onMatcherFailure] fallback disabled, continuing with error."),this.page.testRunAnalytics.testRunAssertionExecutionFailure({failedThought:(r=this.checksumAIThought)==null?void 0:r.thought,error:t.message,matcher:(a=t.matcherResult)==null?void 0:a.name}),t;if(Dv("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought.thought),this.skipAutoRecovery){if(this.soft)return;throw t}try{await this.page.initiateFallbackSequence({type:"assertion",error:t,withChecksumAI:this.withChecksumAI,testInfo:this.page.testInfo})}catch(o){if(this.soft)return;throw o}throw this.soft=!0,t}};e(__n,"ExpectCallProxyHandler");var Ntr=__n;var Avt=class Avt{constructor(t=void 0,r={}){this.page=t;this.configuration=r}get(t,r){return r==="setPage"?a=>{this.page=a}:r==="extend"?(...a)=>{let o=t.extend(...a);return new Proxy(o,this)}:r==="configure"?a=>{let o=t.configure(a);return new Proxy(o,new Avt(this.page,{...this.configuration,...a}))}:r==="soft"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.soft(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o,!0))}:r==="poll"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.poll(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}:r==="skipAutoRecovery"?new Proxy(()=>{},{apply:e((o,c,f)=>{let _=this.manipulateArgsAndExtractThought(f),v=t.apply(c,f);return new Proxy(v,this.makeExpectCallProxyHandler(_,void 0,!0))},"apply"),get:e((o,c)=>new Proxy(t,new Avt(this.page,{...this.configuration,skipAutoRecovery:!0}))[c],"get")}):t[r]instanceof Function?t[r].bind(t):t[r]}apply(t,r,a){let o=this.manipulateArgsAndExtractThought(a),c=t.apply(r,a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}makeExpectCallProxyHandler(t,r,a){var o,c;return new Ntr(this.page,t,r===!0?!0:(o=this.configuration)==null?void 0:o.soft,a===!0?!0:(c=this.configuration)==null?void 0:c.skipAutoRecovery,this.configuration)}manipulateArgsAndExtractThought(t){let r,a=t[1];if(typeof a=="string")r=a,t[1]=void 0;else if(typeof a=="object"){if(a.checksumAI===!1){t[1].checksumAI=void 0;return}a.checksumAI&&typeof a.checksumAI=="string"?(r=a.checksumAI,t[1].checksumAI=void 0):a.message&&(r=a.message,t[1].message=void 0)}return r}};e(Avt,"ExpectProxyHandler");var Otr=Avt;var Rtr=class Rtr{constructor(t){this.expect=t;this.proxy=new Proxy(this.expect,new Otr)}static init(t){return new Rtr(t).proxy}};e(Rtr,"ChecksumExpect");var Btr=Rtr;var gxi=require("@playwright/test");var _xi=rf(hT()),Ltr=require("fs");var Evt=rf(require("path"));var qXa=e(i=>{let t=O7e(i),r=new B7e(t),a=Sht();return r.transformSourceFile([new qFe(i),new BHe(i,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[_xi.factory.createIdentifier("__filename")]})]),`${BZn}
2038
2038
  ${r.getTestFileCode().code}`},"transformFileToHoRequireFormat"),QXa=e(i=>{let t=Evt.default.dirname(i),a=Evt.default.basename(i).split(".")[0],o=Math.random().toString(36).substring(2,15),c=Evt.default.extname(i);return Evt.default.join(t,`${a}-${Date.now()}-${o}${c}`)},"generateTempFilePath"),$Xa=e((i,t)=>{let r=Sht();return new R7e(t,r).getResolvedPath(i)},"resolveFilePath"),VXa=e((i,t=__filename)=>{let r;try{let a=require.resolve($Xa(i,t)),o=qXa(a);r=QXa(a),(0,Ltr.writeFileSync)(r,o);let c=require(r);return require.cache[a]=require.cache[r],c}catch(a){throw console.error("Error in require",a),a}finally{r&&(0,Ltr.unlinkSync)(r)}},"checksumHotRequire"),hxi=VXa;function zXa(i){let t=Tqt(),{options:r,apiKey:a,environments:o}=t,c=o.find(R=>R.default);if(!c)throw new Error("No default environment found. Please set the default field to true on one of the environments in the checksum.config.ts file.");if(!c.baseURL)throw new Error("A baseURL is required. Please set the baseURL field in the default environment in the checksum.config.ts file.");if(!c.users.find(R=>R.default))throw new Error("A default user within the default environment is required. Please set one of the default environment users as default in the checksum.config.ts file.");if(!a)throw new Error("An API key is required. Please set the apiKey field in the checksum.config.ts file.");let _=process.env.CHECKSUM_REPL==="true",{test:v,defineChecksumTest:C}=dxi(i??gxi.test,t,r,_),w=Btr.init(v.expect),T=JXa();v._checksum={expect:w,checksumAI:T},_&&(console.log("Detected REPL mode"),v.beforeEach(async()=>{v.setTimeout(0)}),v.afterEach(async()=>{for(;;)await tA(1e3)}));let k=e(({name:R,userRole:B})=>{let{environment:U,user:W}=x_t(t,{environment:R,role:B},!0),X=_Vn({config:t,throwIfEnvInfoInvalid:!0},{environmentName:U.name,userRole:W.role});return{environment:U,user:W,login:X}},"getEnvironment");return{test:v,expect:w,login:Dbe({config:t}),defineChecksumTest:C,getEnvironment:k,checksumAI:T}}e(zXa,"init");var h_n=e(i=>new Proxy(i,{apply:e(function(r,a,o){return r.page.checksumAI(o[0],o[1],r.options)},"apply"),get:e(function(r,a){return a==="withDialog"?(r.options.withDialog=!0,h_n(i)):a==="skipAutoRecovery"?(r.options.skipAutoRecovery=!0,h_n(i)):r[a]},"get"),set:e(function(r,a,o){if(a==="page")return r[a]=o},"set")}),"makeChecksumAIProxy"),JXa=e(()=>{let i=e(function(){},"func");return i.page=void 0,i.options={withDialog:!1,withTomer:!1,skipAutoRecovery:!1},h_n(i)},"makeChecksumAI");0&&(module.exports={AutoRecoveryMode,RunMode,checksumHotRequire,getChecksumConfig,getLogin,init});
2039
2039
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checksum-ai/runtime",
3
- "version": "2.0.8-alpha",
3
+ "version": "2.0.9-beta",
4
4
  "description": "Checksum.ai test runtime",
5
5
  "main": "index.js",
6
6
  "dependencies": {
@@ -15,7 +15,8 @@
15
15
  "@monaco-editor/react": "^4.6.0",
16
16
  "sucrase": "^3.35.0",
17
17
  "sharp": "^0.33.5",
18
- "newrelic": "^13.3.2"
18
+ "newrelic": "^13.3.2",
19
+ "htmlparser2": "10.0.0"
19
20
  },
20
21
  "repository": {
21
22
  "type": "git",
@@ -323,6 +323,154 @@ function reportTraceFile(projectRoot) {
323
323
  replaceContent(file, originalContent, newContent);
324
324
  }
325
325
 
326
+ function htmlReporter(projectRoot) {
327
+ const file = join(
328
+ projectRoot,
329
+ "node_modules/playwright/lib/reporters/html.js"
330
+ );
331
+ if (!doesFileExist(file)) {
332
+ return;
333
+ }
334
+
335
+ let originalContent, newContent;
336
+
337
+ // Filter out runtime files from snippet generation
338
+ originalContent = `function createSnippets(stepsInFile) {
339
+ for (const file of stepsInFile.keys()) {
340
+ let source;
341
+ try {
342
+ source = import_fs.default.readFileSync(file, "utf-8") + "\\n//";
343
+ } catch (e) {
344
+ continue;
345
+ }`;
346
+ newContent = `function createSnippets(stepsInFile) {
347
+ for (const file of stepsInFile.keys()) {
348
+ // Skip runtime files to reduce report size
349
+ if (file.includes('@checksum-ai/runtime') || file.includes('node_modules')) {
350
+ continue;
351
+ }
352
+ let source;
353
+ try {
354
+ source = import_fs.default.readFileSync(file, "utf-8") + "\\n//";
355
+ } catch (e) {
356
+ continue;
357
+ }`;
358
+ replaceContent(file, originalContent, newContent);
359
+
360
+ // Also filter from error codeframe generation
361
+ originalContent = `function createErrorCodeframe(message, location) {
362
+ let source;
363
+ try {
364
+ source = import_fs.default.readFileSync(location.file, "utf-8") + "\\n//";
365
+ } catch (e) {
366
+ return;
367
+ }`;
368
+ newContent = `function createErrorCodeframe(message, location) {
369
+ // Skip runtime files to reduce report size
370
+ if (location.file && (location.file.includes('@checksum-ai/runtime') || location.file.includes('node_modules'))) {
371
+ return;
372
+ }
373
+ let source;
374
+ try {
375
+ source = import_fs.default.readFileSync(location.file, "utf-8") + "\\n//";
376
+ } catch (e) {
377
+ return;
378
+ }`;
379
+ replaceContent(file, originalContent, newContent);
380
+
381
+ // Filter out steps with locations in runtime/node_modules files completely
382
+ originalContent = `_createTestStep(dedupedStep, result) {
383
+ const { step, duration, count } = dedupedStep;
384
+ const skipped = dedupedStep.step.annotations?.find((a) => a.type === "skip");
385
+ let title = step.title;
386
+ if (skipped)
387
+ title = \`\${title} (skipped\${skipped.description ? ": " + skipped.description : ""})\`;
388
+ const testStep = {
389
+ title,
390
+ startTime: step.startTime.toISOString(),
391
+ duration,
392
+ steps: dedupeSteps(step.steps).map((s) => this._createTestStep(s, result)),
393
+ attachments: step.attachments.map((s) => {
394
+ const index = result.attachments.indexOf(s);
395
+ if (index === -1)
396
+ throw new Error("Unexpected, attachment not found");
397
+ return index;
398
+ }),
399
+ location: this._relativeLocation(step.location),
400
+ error: step.error?.message,
401
+ count,
402
+ skipped: !!skipped
403
+ };
404
+ if (step.location)
405
+ this._stepsInFile.set(step.location.file, testStep);
406
+ return testStep;
407
+ }`;
408
+ newContent = `_createTestStep(dedupedStep, result) {
409
+ const { step, duration, count } = dedupedStep;
410
+ // Skip "Evaluate" steps with locations in runtime/node_modules files
411
+ if (step.location && step.title === "Evaluate" && (step.location.file.includes('@checksum-ai/runtime') || step.location.file.includes('node_modules'))) {
412
+ // Return null to indicate this step should be filtered out
413
+ return null;
414
+ }
415
+ const skipped = dedupedStep.step.annotations?.find((a) => a.type === "skip");
416
+ let title = step.title;
417
+ if (skipped)
418
+ title = \`\${title} (skipped\${skipped.description ? ": " + skipped.description : ""})\`;
419
+ const testStep = {
420
+ title,
421
+ startTime: step.startTime.toISOString(),
422
+ duration,
423
+ steps: dedupeSteps(step.steps).map((s) => this._createTestStep(s, result)).filter(s => s !== null),
424
+ attachments: step.attachments.map((s) => {
425
+ const index = result.attachments.indexOf(s);
426
+ if (index === -1)
427
+ throw new Error("Unexpected, attachment not found");
428
+ return index;
429
+ }),
430
+ location: this._relativeLocation(step.location),
431
+ error: step.error?.message,
432
+ count,
433
+ skipped: !!skipped
434
+ };
435
+ if (step.location)
436
+ this._stepsInFile.set(step.location.file, testStep);
437
+ return testStep;
438
+ }`;
439
+ replaceContent(file, originalContent, newContent);
440
+
441
+ // Also filter steps when creating test results
442
+ originalContent = `steps: dedupeSteps(result.steps).map((s) => this._createTestStep(s, result)),`;
443
+ newContent = `steps: dedupeSteps(result.steps).map((s) => this._createTestStep(s, result)).filter(s => s !== null),`;
444
+ replaceContent(file, originalContent, newContent);
445
+
446
+ // Normalize locations for steps from runtime/index.js - hide location if it's index.js from runtime
447
+ originalContent = `_relativeLocation(location) {
448
+ if (!location)
449
+ return void 0;
450
+ const file = (0, import_utils.toPosixPath)(import_path.default.relative(this._config.rootDir, location.file));
451
+ return {
452
+ file,
453
+ line: location.line,
454
+ column: location.column
455
+ };
456
+ }`;
457
+ newContent = `_relativeLocation(location) {
458
+ if (!location)
459
+ return void 0;
460
+ // Hide location for steps from runtime/index.js to reduce clutter
461
+ if (location.file && location.file.includes('@checksum-ai/runtime') && location.file.endsWith('index.js')) {
462
+ return void 0;
463
+ }
464
+ const file = (0, import_utils.toPosixPath)(import_path.default.relative(this._config.rootDir, location.file));
465
+ return {
466
+ file,
467
+ line: location.line,
468
+ column: location.column
469
+ };
470
+ }`;
471
+ replaceContent(file, originalContent, newContent);
472
+ }
473
+
326
474
  // -------- [Run] -------- //
327
475
 
328
476
  const isRuntime = true || process.env.RUNTIME === "true";
@@ -340,6 +488,7 @@ function run(projectPath) {
340
488
  stackTrace(projectPath);
341
489
  indexContent(projectPath);
342
490
  reportTraceFile(projectPath);
491
+ htmlReporter(projectPath);
343
492
  }
344
493
  } else {
345
494
  console.warn("Project path not found", projectPath);