@checksum-ai/runtime 1.1.71 → 1.1.72-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 +1 -1
- package/checksumlib.js +245 -160
- package/cli.js +345 -345
- package/index.js +2 -2
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1887,7 +1887,7 @@ ${C}`,_(P,C))return g}return g}addESRA(l,_){if(!this.esraMetadataMap)return"";if
|
|
|
1887
1887
|
\\s]*(?:(?!\\1)[\\s\\S]))*\\1(?:[\r
|
|
1888
1888
|
\\s]*,\\s*({[\\s\\S]*?}))?[\r
|
|
1889
1889
|
\\s]*\\)`)}}};e(FEt,"CodeMirror");var cFt=FEt;var gxe=class gxe{constructor(l){this.workerInfo=l;this.hasMonitor=!1;gxe.monitorAgentPort?this.hasMonitor=!0:gT("CHECKSUM_UPLOAD_AGENT_PORT is not defined"),this.sendPlaywrightConfig()}addAsset(l){this.signalUpload(l,["trace","har"].includes(l.type))}addTestInfo(l,_){this.sendMessage({type:"testInfo",payload:{checksumTestId:l,pwTestId:_}})}addSingleTestStats(l,_){this.sendMessage({type:"testStats",payload:{passed:l,healed:_}})}sendPlaywrightConfig(){gxe.playwrightConfigSent||(this.sendMessage({type:"playwrightConfig",payload:this.buildPlaywrightConfig()}),gxe.playwrightConfigSent=!0)}buildPlaywrightConfig(){let{use:l,testDir:_,testMatch:g,testIgnore:C,timeout:P,outputDir:F,retries:M}=this.workerInfo.project,{reporter:V,configFile:W,projects:Q}=this.workerInfo.config,se=Object.keys(Q).filter(G=>[l,_,g,C,P,F,M].includes(G)).reduce((G,_e)=>({...G,[_e]:Q[_e]}),{});return{reporter:V,configFile:W,filteredProjects:se,use:l,testDir:_,testMatch:g,testIgnore:C,timeout:P,outputDir:F,retries:M}}sendMessage(l){if(this.hasMonitor)return fetch(`${gxe.monitorAgentHost}:${gxe.monitorAgentPort}`,{method:"POST",body:JSON.stringify(l)}).catch(_=>{gT("Failed to send message to test run monitor",l,_)})}signalUpload(l,_=!1){return this.sendMessage({type:"asset",payload:l,watch:_})}};e(gxe,"TestRunMonitorBridge"),gxe.monitorAgentHost="http://localhost",gxe.monitorAgentPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT,gxe.playwrightConfigSent=!1;var uFt=gxe;var son=e(()=>{let l=new Error().stack.split(`
|
|
1890
|
-
`).find(_=>_.includes(".checksum.spec.ts"));if(l)return{lineNumber:parseInt(l.split(":")[1]),columnNumber:parseInt(l.split(":")[2])}},"findCodeLocationFromStackTrace"),I$t=class I$t{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let l in this.store)Object.prototype.hasOwnProperty.call(this.store,l)&&delete this.store[l];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(l=>this.store[l])}setVariable(l,_){this.store[l]={name:l,value:_,type:_ instanceof Function?"RandomValueGenerator":"FillValue"}}set(l,_,g){if(typeof _!="string")return!1;let C=son();return l.store[_]={name:_,value:g,type:g instanceof Function?"RandomValueGenerator":"FillValue",...C,line:""},!0}get(l,_){var g;if(_ in l)return l[_];if(!(_ in l.store))throw new Error(`Variable ${_} is not defined`);return l.activeVariablesSet.add(_),(g=l.store[_])==null?void 0:g.value}};e(I$t,"VariableStore");var Utt=I$t;var uxr=x7(cxr());var xOt=(_=>(_.Launched="Launched",_.Log="Log",_))(xOt||{});var sXt=class sXt{constructor(l,_){this.config=l;this.options=_;this.didIdentify=!1;this.isolatedMode=!1;this.internalId=process.env.CHECKSUM_TRACE_INTERNAL_ID??j9e(6)}async identify(l,_,g=!1){let C=this.identifier;this.identifier=l,this.didIdentify=!0,!(!this.analyticsBase||g)&&(C&&(this.analyticsBase.alias({userId:l,previousId:C}),await WC(10)),this.analyticsBase.identify({userId:l,anonymousId:C,traits:{..._,...this.getTraits()}}))}log(...l){this.trackEvent("Log",{lines:l})}setIsolatedMode(){this.isolatedMode=!0}trackEvent(l,_={}){if(!(!this.analyticsBase||this.isolatedMode))try{!this.didIdentify&&!this.identifier&&(this.identifier=Date.now().toString()),_.internalId=this.internalId,this.track(l,_),this.logToConsole(l,_)}catch(g){console.error(`Failed to track event: ${l} with payload:`,_,g)}}logToConsole(l,_){this.options.logToConsole&&console.log(`Event Tracked: ${l}`,_)}getTraits(){return{}}};e(sXt,"BaseAnalytics");var SOt=sXt;var oXt=class oXt extends SOt{constructor(l,_){super(l,_),l!=null&&l.writeKey&&(this.analyticsBase=new uxr.default({...l,flushAt:1,flushInterval:1e3}))}async flush(){this.analyticsBase&&await this.analytics.flush()}async close(){this.analyticsBase&&await this.analytics.closeAndFlush({timeout:1e4})}track(l,_){if(this.analyticsBase)try{let g=this.didIdentify?{userId:this.identifier}:{anonymousId:this.identifier};this.analytics.track({...g,event:l,properties:_})}catch(g){this.options.logToConsole&&console.error(`Failed to track event: ${l} with payload:`,_,g)}}get analytics(){return this.analyticsBase}};e(oXt,"NodeAnalytics");var TOt=oXt;var cXt=(_r=>(_r.RuntimeError="Runtime Error",_r.TestRunMonitorError="Test Run Monitor Error",_r.ChecksumConfigError="Checksum Config Error",_r.InitializationError="Initialization Error",_r.UploadStart="Upload Start",_r.UploadComplete="Upload Complete",_r.UploadFailed="Upload Failed",_r.TestRunStarted="Test Run Started",_r.TestRunEnd="Test Run End",_r.TestRunFailed="Test Run Failed",_r.AllUploadsComplete="All Uploads Complete",_r.UploadsCompleteWithErrors="Upload Complete With Errors",_r.ReportComplete="Report Complete",_r.ReportUploadError="Report Upload Error",_r.RuntimeTimeout="Runtime Timeout",_r.CompletionStatus="Completion Status",_r.RuntimeComplete="Runtime Complete",_r.ChecksumConfig="Checksum Config",_r.PlaywrightConfig="Playwright Config",_r.FallbackStart="Fallback Start",_r.ActionExecutionFailure="Action Execution Failure",_r.AIFallbackStep="AI Fallback Step",_r.ActionFallbackExecution="Action Fallback Execution",_r.AssertionFallbackExecution="Assertion Fallback Execution",_r.AssertionFailure="Assertion Failure",_r.CompoundSelectionFailure="Compound Selection Failure",_r))(cXt||{});var NZe=class NZe extends TOt{constructor(_,g,C){super(g,C);this.traits=_}static getInstance(_={},g={},C={logToConsole:!0}){return NZe.instance||(NZe.instance=new NZe(_,g,C)),NZe.instance}setTestId(_){this.testId=_}event(_){this.trackEvent(_)}eventWithMessage(_,g){this.trackEvent(_,{message:g})}runtimeError(_){this.trackEvent("Runtime Error",_)}completionStatus(_){this.trackEvent("Completion Status",{stats:_})}reportComplete(_,g){this.trackEvent("Report Complete",{stats:_,reportUrl:g})}allUploadsComplete(){this.trackEvent("All Uploads Complete")}uploadsCompleteWithErrors(_){this.trackEvent("Upload Complete With Errors",{errors:_})}testsStart(){this.trackEvent("Test Run Started")}testsEnd(){this.trackEvent("Test Run End")}testsFailed(){this.trackEvent("Test Run Failed")}checksumConfig(_){this.trackEvent("Checksum Config",_)}playwrightConfig(_){this.trackEvent("Playwright Config",_)}uploadStart(_){this.trackEvent("Upload Start",{filename:_})}uploadComplete(_){this.trackEvent("Upload Complete",{filename:_})}uploadFailed(_,g){this.trackEvent("Upload Failed",{filename:_,error:g})}fallbackStart(_){_.shouldSendToAnalytics&&this.trackEvent("Fallback Start",{description:_.toString(),testId:this.testId})}actionFallbackExecution(_,g){g.shouldSendToAnalytics&&this.trackEvent("Action Fallback Execution",{success:_,...g.getAnalyticsPayload(),testId:this.testId})}actionExecutionFailure(_){this.trackEvent("Action Execution Failure",{..._,testId:this.testId})}aiFallbackStep(_,g){this.trackEvent("AI Fallback Step",{sessionId:_,...g,testId:this.testId})}compoundSelectionFailure(_,g){this.trackEvent("Compound Selection Failure",{error:_,compoundSelector:g,testId:this.testId})}assertionFailure(_,g,C){this.trackEvent("Assertion Failure",{thought:_,error:g,matcher:C,testId:this.testId})}assertionFallbackExecution(_,g){g.shouldSendToAnalytics&&this.trackEvent("Assertion Fallback Execution",{success:_,...g.getAnalyticsPayload(),testId:this.testId})}track(_,g){if(!this.getAllowedEvents().includes(_))throw new Error(`Invalid runtime event type: ${_}`);super.track(_,g)}getTraits(){return this.traits}getAllowedEvents(){return[...Object.values(cXt),...Object.values(xOt)]}};e(NZe,"RuntimeAnalytics");var Srt=NZe;var Enr=require("crypto");var LQ=require("fs"),COt=x7(require("child_process")),ice=require("path");var uXt=class uXt{constructor(l,_=!1){this.args=l;this.debugMode=_;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=e(l=>{console.log("\x1B[31m%s\x1B[0m",l,"\x1B[0m")},"printError");this.processConfigArg(),["SIGINT","SIGTERM"].forEach(g=>{process.on(g,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion()}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{return require("./package.json").version}catch{return"unknown"}}loadTracer(){let l=j4.testRun.monitoring.segment;this.trace=Srt.getInstance({version:this.checksumRuntimeVersion},l,{logToConsole:this.debugMode})}async execCmd(l,_={}){let g={...process.env,..._},C=await COt.spawn(l,{env:g,shell:!0,stdio:"inherit"});return this.childProcesses.push(C),new Promise((F,M)=>{C.on("exit",V=>{V===0?F(!0):M(new Error(`Checksum failed execution with code: ${V} `)),this.childProcesses=this.childProcesses.filter(W=>W!==C)})})}async getCmdOutput(l){return new Promise(function(_,g){COt.exec(l,(C,P,F)=>{if(C){g(`Error executing command: ${C.message}`);return}_(P.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let l=(0,ice.join)(this.checksumRoot,".auth");(0,LQ.existsSync)(l)||(0,LQ.writeFileSync)(l,"{}")}loadChecksumData(){this.locateChecksumLibs(),this.setChecksumConfig()}async patchPlaywright(l=!1){gT("Patching playwright",l);let _=(0,ice.join)(__dirname,"./scripts/patch.js");(0,LQ.existsSync)(_)||(_=(0,ice.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let g=`node "${_}"${l?" off":""}`;try{await this.execCmd(g,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(C){console.log("Error patching playwright",C.message)}}getPlaywrightConfigFilePath(){return(0,ice.join)(this.checksumRoot,"playwright.config.ts")}
|
|
1890
|
+
`).find(_=>_.includes(".checksum.spec.ts"));if(l)return{lineNumber:parseInt(l.split(":")[1]),columnNumber:parseInt(l.split(":")[2])}},"findCodeLocationFromStackTrace"),I$t=class I$t{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let l in this.store)Object.prototype.hasOwnProperty.call(this.store,l)&&delete this.store[l];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(l=>this.store[l])}setVariable(l,_){this.store[l]={name:l,value:_,type:_ instanceof Function?"RandomValueGenerator":"FillValue"}}set(l,_,g){if(typeof _!="string")return!1;let C=son();return l.store[_]={name:_,value:g,type:g instanceof Function?"RandomValueGenerator":"FillValue",...C,line:""},!0}get(l,_){var g;if(_ in l)return l[_];if(!(_ in l.store))throw new Error(`Variable ${_} is not defined`);return l.activeVariablesSet.add(_),(g=l.store[_])==null?void 0:g.value}};e(I$t,"VariableStore");var Utt=I$t;var uxr=x7(cxr());var xOt=(_=>(_.Launched="Launched",_.Log="Log",_))(xOt||{});var sXt=class sXt{constructor(l,_){this.config=l;this.options=_;this.didIdentify=!1;this.isolatedMode=!1;this.internalId=process.env.CHECKSUM_TRACE_INTERNAL_ID??j9e(6)}async identify(l,_,g=!1){let C=this.identifier;this.identifier=l,this.didIdentify=!0,!(!this.analyticsBase||g)&&(C&&(this.analyticsBase.alias({userId:l,previousId:C}),await WC(10)),this.analyticsBase.identify({userId:l,anonymousId:C,traits:{..._,...this.getTraits()}}))}log(...l){this.trackEvent("Log",{lines:l})}setIsolatedMode(){this.isolatedMode=!0}trackEvent(l,_={}){if(!(!this.analyticsBase||this.isolatedMode))try{!this.didIdentify&&!this.identifier&&(this.identifier=Date.now().toString()),_.internalId=this.internalId,this.track(l,_),this.logToConsole(l,_)}catch(g){console.error(`Failed to track event: ${l} with payload:`,_,g)}}logToConsole(l,_){this.options.logToConsole&&console.log(`Event Tracked: ${l}`,_)}getTraits(){return{}}};e(sXt,"BaseAnalytics");var SOt=sXt;var oXt=class oXt extends SOt{constructor(l,_){super(l,_),l!=null&&l.writeKey&&(this.analyticsBase=new uxr.default({...l,flushAt:1,flushInterval:1e3}))}async flush(){this.analyticsBase&&await this.analytics.flush()}async close(){this.analyticsBase&&await this.analytics.closeAndFlush({timeout:1e4})}track(l,_){if(this.analyticsBase)try{let g=this.didIdentify?{userId:this.identifier}:{anonymousId:this.identifier};this.analytics.track({...g,event:l,properties:_})}catch(g){this.options.logToConsole&&console.error(`Failed to track event: ${l} with payload:`,_,g)}}get analytics(){return this.analyticsBase}};e(oXt,"NodeAnalytics");var TOt=oXt;var cXt=(_r=>(_r.RuntimeError="Runtime Error",_r.TestRunMonitorError="Test Run Monitor Error",_r.ChecksumConfigError="Checksum Config Error",_r.InitializationError="Initialization Error",_r.UploadStart="Upload Start",_r.UploadComplete="Upload Complete",_r.UploadFailed="Upload Failed",_r.TestRunStarted="Test Run Started",_r.TestRunEnd="Test Run End",_r.TestRunFailed="Test Run Failed",_r.AllUploadsComplete="All Uploads Complete",_r.UploadsCompleteWithErrors="Upload Complete With Errors",_r.ReportComplete="Report Complete",_r.ReportUploadError="Report Upload Error",_r.RuntimeTimeout="Runtime Timeout",_r.CompletionStatus="Completion Status",_r.RuntimeComplete="Runtime Complete",_r.ChecksumConfig="Checksum Config",_r.PlaywrightConfig="Playwright Config",_r.FallbackStart="Fallback Start",_r.ActionExecutionFailure="Action Execution Failure",_r.AIFallbackStep="AI Fallback Step",_r.ActionFallbackExecution="Action Fallback Execution",_r.AssertionFallbackExecution="Assertion Fallback Execution",_r.AssertionFailure="Assertion Failure",_r.CompoundSelectionFailure="Compound Selection Failure",_r))(cXt||{});var NZe=class NZe extends TOt{constructor(_,g,C){super(g,C);this.traits=_}static getInstance(_={},g={},C={logToConsole:!0}){return NZe.instance||(NZe.instance=new NZe(_,g,C)),NZe.instance}setTestId(_){this.testId=_}event(_){this.trackEvent(_)}eventWithMessage(_,g){this.trackEvent(_,{message:g})}runtimeError(_){this.trackEvent("Runtime Error",_)}completionStatus(_){this.trackEvent("Completion Status",{stats:_})}reportComplete(_,g){this.trackEvent("Report Complete",{stats:_,reportUrl:g})}allUploadsComplete(){this.trackEvent("All Uploads Complete")}uploadsCompleteWithErrors(_){this.trackEvent("Upload Complete With Errors",{errors:_})}testsStart(){this.trackEvent("Test Run Started")}testsEnd(){this.trackEvent("Test Run End")}testsFailed(){this.trackEvent("Test Run Failed")}checksumConfig(_){this.trackEvent("Checksum Config",_)}playwrightConfig(_){this.trackEvent("Playwright Config",_)}uploadStart(_){this.trackEvent("Upload Start",{filename:_})}uploadComplete(_){this.trackEvent("Upload Complete",{filename:_})}uploadFailed(_,g){this.trackEvent("Upload Failed",{filename:_,error:g})}fallbackStart(_){_.shouldSendToAnalytics&&this.trackEvent("Fallback Start",{description:_.toString(),testId:this.testId})}actionFallbackExecution(_,g){g.shouldSendToAnalytics&&this.trackEvent("Action Fallback Execution",{success:_,...g.getAnalyticsPayload(),testId:this.testId})}actionExecutionFailure(_){this.trackEvent("Action Execution Failure",{..._,testId:this.testId})}aiFallbackStep(_,g){this.trackEvent("AI Fallback Step",{sessionId:_,...g,testId:this.testId})}compoundSelectionFailure(_,g){this.trackEvent("Compound Selection Failure",{error:_,compoundSelector:g,testId:this.testId})}assertionFailure(_,g,C){this.trackEvent("Assertion Failure",{thought:_,error:g,matcher:C,testId:this.testId})}assertionFallbackExecution(_,g){g.shouldSendToAnalytics&&this.trackEvent("Assertion Fallback Execution",{success:_,...g.getAnalyticsPayload(),testId:this.testId})}track(_,g){if(!this.getAllowedEvents().includes(_))throw new Error(`Invalid runtime event type: ${_}`);super.track(_,g)}getTraits(){return this.traits}getAllowedEvents(){return[...Object.values(cXt),...Object.values(xOt)]}};e(NZe,"RuntimeAnalytics");var Srt=NZe;var Enr=require("crypto");var LQ=require("fs"),COt=x7(require("child_process")),ice=require("path");var uXt=class uXt{constructor(l,_=!1){this.args=l;this.debugMode=_;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=e(l=>{console.log("\x1B[31m%s\x1B[0m",l,"\x1B[0m")},"printError");this.processConfigArg(),["SIGINT","SIGTERM"].forEach(g=>{process.on(g,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion()}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{return require("./package.json").version}catch{return"unknown"}}loadTracer(){let l=j4.testRun.monitoring.segment;this.trace=Srt.getInstance({version:this.checksumRuntimeVersion},l,{logToConsole:this.debugMode})}async execCmd(l,_={}){let g={...process.env,..._},C=await COt.spawn(l,{env:g,shell:!0,stdio:"inherit"});return this.childProcesses.push(C),new Promise((F,M)=>{C.on("exit",V=>{V===0?F(!0):M(new Error(`Checksum failed execution with code: ${V} `)),this.childProcesses=this.childProcesses.filter(W=>W!==C)})})}async getCmdOutput(l){return new Promise(function(_,g){COt.exec(l,(C,P,F)=>{if(C){g(`Error executing command: ${C.message}`);return}_(P.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let l=(0,ice.join)(this.checksumRoot,".auth");(0,LQ.existsSync)(l)||(0,LQ.writeFileSync)(l,"{}")}loadChecksumData(){this.locateChecksumLibs(),this.setChecksumConfig()}async patchPlaywright(l=!1){gT("Patching playwright",l);let _=(0,ice.join)(__dirname,"./scripts/patch.js");(0,LQ.existsSync)(_)||(_=(0,ice.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let g=`node "${_}"${l?" off":""}`;try{await this.execCmd(g,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(C){console.log("Error patching playwright",C.message)}}getPlaywrightConfigFilePath(){return(0,ice.join)(this.checksumRoot,"playwright.config.ts")}buildVolatileChecksumConfig(){if(!this.volatileChecksumConfig)return;let l=this.getVolatileConfigPath(),_=`
|
|
1891
1891
|
import { RunMode, getChecksumConfig } from "@checksum-ai/runtime";
|
|
1892
1892
|
|
|
1893
1893
|
export default getChecksumConfig(${JSON.stringify(this.config,null,2)});
|
|
@@ -1944,7 +1944,7 @@ if (typeof globalThis.requireTs === "undefined") {
|
|
|
1944
1944
|
}
|
|
1945
1945
|
}`;var oK=x7(X_e());var xer=class xer{transform(l){let _=e(g=>{if(oK.isSourceFile(g)){let C=g.statements.filter(P=>oK.isImportDeclaration(P)?!this.shouldRemoveImport(P):oK.isVariableStatement(P)?!this.shouldRemoveRequireVariableStatement(P):!0);return oK.factory.updateSourceFile(g,C)}return oK.visitEachChild(g,_,l)},"visit");return g=>oK.visitNode(g,_)}shouldRemoveImport(l){let _=l.moduleSpecifier.text;return!_.startsWith(".")&&!_.startsWith("/")}shouldRemoveRequireVariableStatement(l){let _=l.declarationList.declarations[0];if(!_)return!1;let g=_.initializer;if(!g||!oK.isCallExpression(g))return!1;let C=g.expression;if(!oK.isIdentifier(C)||C.text!=="require")return!1;let P=g.arguments[0];return oK.isStringLiteral(P)?!P.text.startsWith(".")&&!P.text.startsWith("/"):!1}};e(xer,"ImportPackagesRemoverTransformer");var XLt=xer;var rde=x7(X_e());var Ser=class Ser{constructor(l){this.requireIdentifier=l}transform(l){return _=>{let g=e(C=>rde.isCallExpression(C)&&rde.isIdentifier(C.expression)&&C.expression.text==="require"&&C.arguments.length===1&&rde.isStringLiteral(C.arguments[0])&&(C.arguments[0].text.startsWith(".")||C.arguments[0].text.startsWith("/"))?rde.factory.updateCallExpression(C,rde.factory.createIdentifier(this.requireIdentifier),C.typeArguments,C.arguments):rde.visitEachChild(C,g,l),"visitor");return rde.visitNode(_,g)}}};e(Ser,"ChangeRelativeRequireTransformer");var QLt=Ser;var Ter=class Ter{constructor(l,_,g,C,P,F,M,V){this.config=l;this.userStoryService=_;this.apiService=g;this.actionsManager=C;this.testAssetsManager=P;this.actionsService=F;this.vtgTestFileRunConfig=M;this.evaluationService=V}saveTestFile(){var M;if(!this.vtgTestFileRunConfig)return;let l=this.vtgTestFileRunConfig.mode==="edit"?this.vtgTestFileRunConfig.internalTestId:"internalTestId",_=(M=this.vtgTestFileRunConfig)==null?void 0:M.sourceFilePath,g=new Vkt(_);g.loadTestsFromFile();let C=this.actionsManager.actions.map(V=>YNe.generateSingleActionCode(V)).join(`
|
|
1946
1946
|
`),P=new zkt(g.sourceFile);P.transformSourceFile([new $Lt(g.sourceFile),new WLt(g.sourceFile,g.testMirrors.filter(V=>V.internalTestId===l).map(V=>V.testBody),Q3r(C))]);let F=this.testAssetsManager.getSavedTestFilePath();return P.write(F),(0,i8r.relative)(process.cwd(),F)}get isLoadedFromTestFile(){return!!this.vtgTestFileRunConfig}async reloadTestFromFile(){if(!this.vtgTestFileRunConfig)return;let l=this.getReloadTestEnvironmentCode();await this.evaluationService.execute(l);let g=new Vkt(this.testAssetsManager.getSavedTestFilePath()).loadActionsFromSingleTest();return await this.actionsManager.reloadTestSteps(g),g}getReloadTestEnvironmentCode(){let l=zLt(X3r(n8r)),_=this.testAssetsManager.getSavedTestFilePath(),g=VLt(_),C=new zkt(g);C.transformSourceFile([new GLt,new XLt,new KLt(_),new HLt,new QLt("requireTs"),new YLt(g)]);let P=C.getFormattedTestFileCode();return[l,P].join(`
|
|
1947
|
-
`)}getLocalSavedData(l){let _=`${this.testAssetsManager.getLocalSavePath()}/${l}/test.json`,g=this.readJsonFile(_);return g?{...g,executedActions:g.executedActions.map(C=>({...C,timestamp:void 0}))}:null}readJsonFile(l){try{let _=(0,HZe.readFileSync)(l,"utf-8");return JSON.parse(_)}catch(_){return Nh.error(`Error reading or parsing JSON file: ${_}`),null}}makeDraftData(){let l=this.userStoryService.getStory(),_=this.userStoryService.getTestGenerationData(),g=this.userStoryService.getEnvInfo();return{actions:this.actionsManager.actions,internalTestId:_.internalTestId,environmentUserId:g.user.username,description:l.goal}}async generateTestFileString(l){try{let _=this.makeDraftData(),g=l?`${l}.draft.spec.ts`:`test-${_.internalTestId}.draft.spec.ts`,C=await this.apiService.post("test-generation/generate-test-file-string",_);if(!C.ok)throw new Error(`test generation request failed: ${C.statusText}`);let P=await C.text();lxr(P,g,this.testAssetsManager.getLocalSavePath())}catch(_){throw Nh.error("Failed to generate test file string",_),new Error("Failed to generate test file string")}}localSave(){let l=JSON.stringify(this.replayJSON,null,2),_=this.testAssetsManager.getAssetsFolderPath();(0,HZe.writeFileSync)(`${_}/test.json`,l),(0,HZe.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/test.json`,l)}get replayJSON(){var l;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(l=this.config.environments.find(_=>_.default))==null?void 0:l.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async localBackup(l){if(l){this.testAssetsManager.setCurrentSaveAsLocation(l);let _=this.testAssetsManager.getLocalSaveAsPath();pxr(this.testAssetsManager.getLocalAutoSavePath(),_)}return this.saveTestFile()}getIsFolderAlreadyExistsInDrafts(l){try{let _=`${this.testAssetsManager.getLocalSavePath()}/${l}`;return(0,HZe.statSync)(_).isDirectory()}catch(_){if(_.code==="ENOENT")return!1;throw _}}async saveToCloud(){try{if(!this.userStoryService.hasTestGenerationData()){Nh("No test generation data, can't upload");return}let l=await this.userStoryService.createTestGeneration(),_=new gLt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${l}/get-upload-url`),g=e(M=>({complete:!1,error:!1,response:void 0,info:M}),"buildUploadAsset"),C=g({type:"trace",path:this.testAssetsManager.getTraceFilePath()}),P=g({type:"har",path:await O4r(this.testAssetsManager.getHarFolderPath())});await Promise.all([_.uploadAsset(C),_.uploadAsset(P)]);let F=this.actionsManager.actions.map(M=>({...M,parentFramesSelectors:M.parentFramesSelectors?M.parentFramesSelectors.filter(V=>V!=="iframe"):void 0}));await this.apiService.post(`test-generation/${l}/completed`,{actions:F})}catch(l){Nh.error("Failed to upload test",l)}}};e(Ter,"VtgStorageService");var ZLt=Ter;var Der=class Der{constructor(l,_){this.apiService=l;this.config=_}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){var l;return!!((l=this.userStoryTestGeneration)!=null&&l.internalTestId)}setStoryInfo(l,_){this.story=l,this.userStoryTestGeneration=_}async fetchStory(l){if(j4.vtg.useFakeStory){console.log("Using fake flow data"),this.story={...j4.vtg.fakeStory,environment:{name:void 0,userRole:void 0}},this.userStoryTestGeneration={internalTestId:j4.vtg.fakeTestGeneration.internalTestId,generationBatchId:j4.vtg.fakeTestGeneration.generationBatchId};return}if(!l)throw new Error("no story id provided");let g=await(await this.apiService.post(`test-generation/info/${l}`)).json();if(!(g!=null&&g.id))throw new Error(`Story ${l} not found`);console.log("Received flow data:",g);let{id:C,title:P,steps:F,startUrl:M,userRole:V,environment:W,internalTestId:Q,generationBatchId:se}=g;this.userStoryTestGeneration={internalTestId:Q,generationBatchId:se},this.story={id:C,goal:P,instructions:F,url:M,environment:{userRole:V,name:W}}}getEnvInfo(){return RCt(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let l=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.userStoryTestGeneration.internalTestId,testGenerationBatchId:this.userStoryTestGeneration.generationBatchId}),{testGenerationId:_}=await l.json();return this.userStoryTestGeneration.testGenerationId=_,_}};e(Der,"VtgUserStoryService");var eMt=Der;var Cer=class Cer{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(l){var _;this._executedActions=l,(_=this.storageService)==null||_.localSave()}addAction(l){var _;this._executedActions.push(l),(_=this.storageService)==null||_.localSave()}setActions(l){this._executedActions=l}updateAssertionById(l,_){this.executedActions=this._executedActions.map(g=>{var C;if(g.id===l){let P=!!((C=g.assertions)!=null&&C.find(({id:M})=>M===_.id)),F={...g};return P?F.assertions=g.assertions.map(M=>M.id===_.id?Object.assign(M,_):M):F.assertions=[...g.assertions??[],_],{...F,assertions:F.assertions.sort((M,V)=>M.timestamp!==V.timestamp?M.timestamp-V.timestamp:M.createdAt-V.createdAt)}}return g})}setStorageService(l){this.storageService=l}createAction(l){var V,W,Q;let{id:_,data:g,options:C,type:P}=l,F={id:_,...g},M=[...this._executedActions];switch(C==null?void 0:C.type){case"insertAfter":{let se=this.findActionOrAssertionById(C.afterStepId),G=M.findIndex(_e=>_e.id===se.action.id);if(se.assertion||(W=(V=se.action)==null?void 0:V.assertions)!=null&&W.length){let _e=se.assertion??se.action.assertions[0],{before:ne,after:ue}=A4n(((Q=M[G])==null?void 0:Q.assertions)??[],_e.id,!!se.assertion);M[G].assertions=ne,F.assertions=ue.map(qe=>({...qe,actionId:F.id}))}G!==-1?M.splice(G+1,0,F):M.push(F);break}case"insertLast":M.push(F);break;case"replace":{let se=M.findIndex(G=>G.id===C.stepId);se!==-1&&M.splice(se,1,F);break}case"replaceLast":M.length>0&&(M[M.length-1]=F);break}this.executedActions=M}pushExecutedActionOrAddAfterParent(l,_={}){if(_.previousActionId){let g=this._executedActions.findIndex(({id:C})=>C===_.previousActionId);if(g!==-1){let C={...l,timestamp:this._executedActions[g].timestamp+1};this._executedActions=[...this._executedActions.slice(0,g+1),C,...this._executedActions.slice(g+1)]}}else this.executedActions=Array.isArray(l)?[...this._executedActions,...l]:[...this._executedActions,l]}addManualActionsToExecuted(l){this.executedActions=[...this._executedActions,l]}updateExecutedAction(l){let _=this._executedActions.findIndex(({id:g})=>g===l.id);_!==-1&&(this.executedActions=[...this._executedActions.slice(0,_),{...this._executedActions[_],...l},...this._executedActions.slice(_+1)])}deleteStep(l,_,g={assertionsOnly:!1}){_==="Action"?g.assertionsOnly?this.executedActions=this._executedActions.map(C=>C.id===l?{...C,assertions:[]}:C):this.executedActions=this._executedActions.filter(C=>C.id!==l):_==="Assertion"&&(this.executedActions=this._executedActions.map(C=>(C.assertions=(C.assertions??[]).filter(P=>P.id!==l),C)))}clearTestSteps(l=!0){if(l){let{navigation:_,login:g}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((C,P)=>([_==null?void 0:_.id,g==null?void 0:g.id].includes(P.id)&&C.push({...P,assertions:[]}),C),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(l){this.clearTestSteps(!1),this.executedActions=l}findLoginAndNavigationActions(){let l=this._executedActions.find(({eventCode:g})=>g==="navigation"),_=this._executedActions.find(({eventCode:g})=>g==="login");return{navigation:l,login:_}}addAssertionToAction(l,_){this.executedActions=this._executedActions.map(g=>{if(g.id!==l.actionId)return g;if(g.assertions||(g.assertions=[]),_){let C=g.assertions.findIndex(({id:P})=>_===P);g.assertions.splice(C+1,0,l)}else g.assertions=[l,...g.assertions??[]];return g})}findActionByAssertionId(l){return this._executedActions.find(({assertions:_=[]})=>_.find(g=>g.id===l))}findActionOrAssertionById(l){let _={action:null,assertion:null};return this._executedActions.forEach(g=>{g.id===l&&(_.action=g);let C=(g.assertions??[]).find(P=>P.id===l);C&&(_={action:g,assertion:C})}),_}};e(Cer,"VtgActionsManager");var tMt=Cer,A4n=e((p,l,_=!0)=>{let g=Number(_),C=p.findIndex(M=>M.id===l);if(C===-1)return{before:p,after:[]};let P=p.slice(0,C+g),F=p.slice(C+g);return{before:P,after:F}},"splitArrayAtId");var mnr=x7(_Ar()),vAr=x7(require("net")),bAr=x7(frr()),xAr=x7(yAr());var _nr=class _nr{constructor(l,_,g){this.app=l;this.assertionsService=_;this.actionsManager=g}setupEndpoints(){this.app.post("/api/createStep",async(l,_)=>{let g=l.body;try{if(g.type==="Assertion"){let C=this.assertionsService.createAssertion(g);return _.status(200).json(C)}if(g.type==="Action")return this.actionsManager.createAction(g),_.send("success")}catch(C){return Nh.error("/api/createStep error:",C),_.status(500).send(C)}}),this.app.patch("/api/updateStep",async(l,_)=>{let g=l.body;try{if(g.type==="Assertion"){let C=await this.assertionsService.updateAssertion({id:g.id,data:g.data});_.status(200).json(C)}if(g.type==="Action")return this.actionsManager.updateExecutedAction({...g.data,id:g.id}),_.send("success")}catch(C){return _.status(500).send(C)}}),this.app.delete("/api/deleteStep",async(l,_)=>{let{id:g,options:C,type:P}=l.body;try{this.actionsManager.deleteStep(g,P,C)}catch(F){return _.status(500).send(F)}return _.status(200).send({message:"Success!"})}),this.app.post("/api/clear-test",async(l,_)=>{try{let g=this.actionsManager.clearTestSteps();return _.status(200).send(g)}catch(g){return _.status(500).send(g)}})}};e(_nr,"VtgStepsController");var xRt=_nr;var dnr=class dnr{constructor(l,_){this.app=l;this.locatorsService=_}setupEndpoints(){this.app.post("/api/locators/play",async(l,_)=>{let g=l.body;try{let C=await this.locatorsService.verifyLocatorOrSelector(g);return _.status(200).send(C)}catch(C){return _.status(400).send({error:C.message})}}),this.app.post("/api/locators/test-identical",async(l,_)=>{let{locator:g,compareLocator:C,timestamp:P}=l.body;try{let F=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(g,C,P);return _.status(200).send(F)}catch(F){return _.status(400).send({error:F.message})}}),this.app.post("/api/ai/locators/generate",async(l,_)=>{let{step:g,target:C,processId:P}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.generateAILocators(g,C,P);let F={processId:P,stepId:C.id,success:!0};_.status(200).send(F)}catch(F){_.status(400).send({processId:P,success:!1,error:F.message})}}),this.app.post("/api/ai/locators/extract-css",async(l,_)=>{let{step:g,target:C,processId:P,llmLocators:F}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.extractCSS(g,C,P,F);let M={processId:P,stepId:C.id,success:!0};_.status(200).send(M)}catch(M){_.status(400).send({processId:P,error:M.message})}}),this.app.post("/api/ai/locators/filter",async(l,_)=>{let{step:g,target:C,processId:P,candidates:F}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.filterLocators(g,C,P,F);let M={processId:P,stepId:C.id,success:!0};_.status(200).send(M)}catch(M){_.status(400).send({processId:P,error:M.message})}}),this.app.delete("/api/ai/locators/process/:id",async(l,_)=>{let g=l.params.id;try{this.locatorsService.cancelProcess(g),Nh("Cancelled process",g),_.status(200).send({success:!0})}catch(C){_.status(400).send({error:C.message})}})}};e(dnr,"VtgLocatorsController");var SRt=dnr;var hnr=class hnr{constructor(l,_,g,C,P,F,M,V,W){this.actionsService=l;this.assertionsService=_;this.locatorsService=g;this.aiTestGenerationService=C;this.aiAssertionsService=P;this.aiThoughtsService=F;this.actionsManager=M;this.storageService=V;this.settingsService=W}async start(){return this.app=(0,mnr.default)(),this.app.use((0,xAr.default)()),this.app.use(bAr.default.json({limit:"50mb"})),this.app.use(mnr.default.raw({type:"multipart/form-data",limit:"50mb"})),this.port=await this.acquirePortNumber(),new xRt(this.app,this.assertionsService,this.actionsManager).setupEndpoints(),this.setupEndpoints(),new SRt(this.app,this.locatorsService).setupEndpoints(),new Promise(l=>{this.app.listen(this.port,()=>{console.log(`Express server running on port ${this.port}`),l()})})}setupEndpoints(){this.app.get("/api",async(l,_)=>{_.send("success")}),this.app.post("/api/test/generate-test-file-string",async(l,_)=>{try{return await this.storageService.generateTestFileString(l.body.fileName),_.send("success")}catch(g){return _.status(400).send({error:g.message})}}),this.app.post("/api/test/upload",async(l,_)=>(await this.storageService.saveToCloud(),_.send("success"))),this.app.post("/api/test/local-save",async(l,_)=>{await this.storageService.localSave(),_.send("success")}),this.app.post("/api/reload-test-from-file",async(l,_)=>{try{if(!this.storageService.isLoadedFromTestFile)return _.status(404).send("No test file found");let g=await this.storageService.reloadTestFromFile();return _.status(200).send(g)}catch(g){return console.log("failed to reload test from file",g),_.status(500).send(g.message)}}),this.app.post("/api/test/verify-save-location",async(l,_)=>{try{let g=this.storageService.getIsFolderAlreadyExistsInDrafts(l.body.location);_.send({exists:g})}catch(g){_.status(400).send({error:g})}}),this.app.post("/api/test/backup",async(l,_)=>{let{backupFolderName:g}=l.body;if(!fxr(g))return _.status(400).send({error:"Invalid folder name"});let C=await this.storageService.localBackup(g);_.send(C)}),this.app.post("/api/ai/init",async(l,_)=>{await this.aiTestGenerationService.init(),_.send("success")}),this.app.post("/api/ai/iterate",async(l,_)=>{let g=l.body,C=await this.aiTestGenerationService.iterate(g);return C?_.status(200).json(C):_.status(400).send("no action generated")}),this.app.post("/api/thoughts/actions/generate",async(l,_)=>{let g=l.body,{processId:C,action:{id:P}}=g;try{this.aiThoughtsService.generateActionThoughts(g);let F={processId:C,stepId:P,success:!0};_.status(200).send(F)}catch(F){return _.status(400).send({processId:C,error:F.message})}}),this.app.post("/api/thoughts/assertions/generate",async(l,_)=>{let g=l.body,{processId:C,assertion:{id:P}}=g;try{this.aiThoughtsService.generateAssertionThought(g);let F={processId:C,stepId:P,success:!0};_.status(200).send(F)}catch(F){return _.status(400).send({processId:C,error:F.message})}}),this.app.post("/api/thoughts/stop-generate",async(l,_)=>{let g=l.body;this.aiThoughtsService.stopGeneratingThought(g.stepId);let C={stepId:g.stepId};return _.status(200).send(C)}),this.app.post("/api/assertions/generate",(l,_)=>{let g=l.body,{processId:C}=g;try{this.aiAssertionsService.generateAiAssertions(g);let P={processId:C,stepId:g.id,success:!0};return _.status(200).json(P)}catch(P){return _.status(500).send({processId:C,error:P.message})}}),this.app.post("/api/assertions/stop-generate",(l,_)=>{let{id:g}=l.body,C={stepId:g};return this.aiAssertionsService.stopGenerateAiAssertions(g),_.status(200).send(C)}),this.app.post("/ai/stop",async(l,_)=>{this.aiTestGenerationService.stop()}),this.app.post("/api/assertion/verify/time-machine",async(l,_)=>{let g=l.body,C=await this.assertionsService.verifyOnTimeMachine(g);return _.status(200).send(C)}),this.app.post("/api/assertion/verify/live",async(l,_)=>{let g=l.body;try{let C=await this.assertionsService.verifyOnLive(g),P=C.success?200:404;return _.status(P).send(C)}catch(C){return _.status(404).send({success:!1,message:String(C)})}}),this.app.post("/api/assertion/save",async(l,_)=>{let g=l.body;try{let C=await this.assertionsService.updateAssertion(g);_.status(200).json(C)}catch(C){_.status(400).send({error:C.message})}}),this.app.post("/api/steps/execute",async(l,_)=>{let g=l.body;try{let C=null;return u9n(g)?C=await this.aiTestGenerationService.executeAction(g):l9n(g)&&(C=await this.actionsService.executeAction(g)),_.status(200).json(C)}catch(C){return _.status(400).send({error:C.message})}}),this.app.post("/api/upload-files",async(l,_)=>{try{await this.actionsService.uploadFiles(l.body.files)}catch(g){return _.status(500).send(g)}return _.status(200).send({message:"File uploaded successfully!"})}),this.app.post("/api/steps/add-manual-action",async(l,_)=>{let g=l.body;return this.actionsManager.addManualActionsToExecuted(g.action),_.send("success")}),this.app.put("/api/steps",async(l,_)=>{let g=l.body;try{this.actionsManager.pushExecutedActionOrAddAfterParent(g.action,g.options)}catch(C){return _.status(500).send(C)}return _.send("success")}),this.app.get("/api/settings",async(l,_)=>{let g=this.settingsService.getSettings();return _.status(200).send(g)}),this.app.post("/api/settings",async(l,_)=>(this.settingsService.updateSettings(l.body),_.status(200).send({message:"Success!"})))}async acquirePortNumber(){return await new Promise((l,_)=>{let g=vAr.default.createServer();g.unref(),g.on("error",_),g.listen(0,()=>{let C=g.address().port;g.close(()=>{l(C)})})})}async evaluateServerPort(l){if(!l)throw new Error("Page not initialized");await l.evaluate(_=>{window.vtg.setServerPort(_)},this.port)}};e(hnr,"VtgExpressServer");var TRt=hnr;function u9n(p){var l;return((l=p.options)==null?void 0:l.isAISuggestion)===!0}e(u9n,"isAIExecuteActionArgs");function l9n(p){var l;return((l=p.options)==null?void 0:l.isAISuggestion)===!1}e(l9n,"isManualExecuteActionArgs");var DRt=require("fs");var gnr=class gnr{constructor(l,_,g){this.projectRootDirectory=l;this.checksumRoot=_;this.vtgTestFileRunConfig=g;this.localSaveFolderPath=`${this.checksumRoot}/drafts`}createTestGenerationAssetsFolders(){this.assetsFolderPath=this.projectRootDirectory+`/tg-assets/${Date.now()}`,(0,DRt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,DRt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(l){this.autoSaveFolderPath=`/auto-save/${l}`,(0,DRt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return this.localSaveFolderPath+this.autoSaveFolderPath}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 l=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${l}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getLogsPath(){return`${this.localSaveFolderPath}/logs`}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(l){l&&!(l!=null&&l.startsWith("auto-save"))&&(this.currentSaveAsLocation=l)}};e(gnr,"VtgTestAssetsManager");var CRt=gnr;var p9n={useCDPSession:!0,trackLoadedResources:!0},ynr=class ynr extends jOt{constructor(_={},g={devtools:!1},C={},P,F){super({...p9n,..._},g,P,F);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(_,g=1e3)=>{try{return await _.waitForFunction(()=>!!window.checksum,void 0,{timeout:g}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async _=>{try{return await _.waitForFunction(()=>{var g;return!!((g=window.checksum)!=null&&g.testGenerator)}),_.evaluate(async({appSpecificRules:g,config:C,initModules:P})=>{window.checksum.testGenerator.init(g,C,P)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(_)})}catch(g){console.log("initInjectedScript exception",g)}},"initInjectedScript");this.settings={...this.settings,...C},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(_={}){let g=await super.prepare(_);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")}),g}setEvaluateWithChecksumTargetFrame(_){this.evaluateWithChecksumTargetFrame=_}getInjectedScriptInitModules(_){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(_,g,C=this.evaluateWithChecksumTargetFrame){let P=this.injectedScriptManager.getNavigationPromise(C);P&&await P;try{return C.evaluate(_,g)}catch(F){throw console.error("evaluateWithChecksum error",F,_.toString()),F}}async getBestMatchingElementSimilarityScore(_){return this.evaluateWithChecksum(async g=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(g),_)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(_){return this.evaluateWithChecksum(g=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(g),_)}async takeElementSnapshot(_,g,C={},P={}){try{let{snapshot:F,elementLocator:M}=await super.takeElementSnapshot(_,g,C);if(!F||!C.takeBodyScreenshot)return F?{snapshot:F}:{};await this.highlightElementByLocator(M,C.mousePosition);let V=await this.takePageSnapshot(P);return await this.clearHighlights(),{snapshot:F,bodySnapshot:V}}catch(F){return console.error("[ChecksumWebDriver] takeElementSnapshot error",F),{}}}async highlightElementByLocator(_,g,C="20px solid rgba(255,0,0,1)",P=!1){return this.evaluateWithChecksum(async([F,M,V,W])=>{window.checksum.testGenerator.highlightElement(F,{highlightStyle:{outline:M},mousePosition:V,scroll:W})},[await _.elementHandle(),C,g,P])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(ynr,"ChecksumWebDriver");var ERt=ynr;var AAr=require("fs"),PAr=x7(require("path"));var vnr=require("fs");var bnr=class bnr{constructor(l,_=j4.vtg.localBuildPath){this.page=l;this.filePath=_;this.filePath=_}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp(),await WC(2e3)}catch(l){Nh.error("An error occurred:",l)}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let l=j4.vtg.appURL;await this.page.goto(l,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(j4.isDevMode){WPt(!0);return}try{let l=await vnr.promises.readFile(this.filePath,"utf8"),_=/(src|href)=(["'])(\/)static/g,g=l.replace(_,"$1=$2.$3static");await vnr.promises.writeFile(this.filePath,g,"utf8"),Nh(`Successfully modified ${this.filePath}`)}catch(l){Nh.error(`Error processing file ${this.filePath}:`,l)}}};e(bnr,"VtgFrontendLauncher");var kRt=bnr;var yFe={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},hai={defaultMerge:yFe.defaultMerge};function f9n(p,l){return l}e(f9n,"defaultMetaDataUpdater");function _9n(p,l){return p.filter(_=>_!==void 0)}e(_9n,"defaultFilterValues");var SAr;(function(p){p[p.NOT=0]="NOT",p[p.RECORD=1]="RECORD",p[p.ARRAY=2]="ARRAY",p[p.SET=3]="SET",p[p.MAP=4]="MAP",p[p.OTHER=5]="OTHER"})(SAr||(SAr={}));function TAr(p){return typeof p!="object"||p===null?0:Array.isArray(p)?2:h9n(p)?1:p instanceof Set?3:p instanceof Map?4:5}e(TAr,"getObjectType");function d9n(p){let l=new Set;for(let _ of p)for(let g of[...Object.keys(_),...Object.getOwnPropertySymbols(_)])l.add(g);return l}e(d9n,"getKeys");function m9n(p,l){return typeof p=="object"&&Object.prototype.propertyIsEnumerable.call(p,l)}e(m9n,"objectHasProperty");function CAr(p){var g;let l=0,_=(g=p[0])==null?void 0:g[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var C;do{if(_===void 0)return{done:!0,value:void 0};let P=_.next();if(P.done===!0){l+=1,_=(C=p[l])==null?void 0:C[Symbol.iterator]();continue}return{done:!1,value:P.value}}while(!0)}}}}}e(CAr,"getIterableOfIterables");var DAr=["[object Object]","[object Module]"];function h9n(p){if(!DAr.includes(Object.prototype.toString.call(p)))return!1;let{constructor:l}=p;if(l===void 0)return!0;let _=l.prototype;return!(_===null||typeof _!="object"||!DAr.includes(Object.prototype.toString.call(_))||!_.hasOwnProperty("isPrototypeOf"))}e(h9n,"isRecord");function g9n(p,l,_){let g={};for(let C of d9n(p)){let P=[];for(let V of p)m9n(V,C)&&P.push(V[C]);if(P.length===0)continue;let F=l.metaDataUpdater(_,{key:C,parents:p}),M=kAr(P,l,F);M!==yFe.skip&&(C==="__proto__"?Object.defineProperty(g,C,{value:M,configurable:!0,enumerable:!0,writable:!0}):g[C]=M)}return g}e(g9n,"mergeRecords$1");function y9n(p){return p.flat()}e(y9n,"mergeArrays$1");function v9n(p){return new Set(CAr(p))}e(v9n,"mergeSets$1");function b9n(p){return new Map(CAr(p))}e(b9n,"mergeMaps$1");function x9n(p){return p.at(-1)}e(x9n,"mergeOthers$1");var wRt={mergeRecords:g9n,mergeArrays:y9n,mergeSets:v9n,mergeMaps:b9n,mergeOthers:x9n};function EAr(...p){return S9n({})(...p)}e(EAr,"deepmerge");function S9n(p,l){let _=T9n(p,g);function g(...C){return kAr(C,_,l)}return e(g,"customizedDeepmerge"),g}e(S9n,"deepmergeCustom");function T9n(p,l){return{defaultMergeFunctions:wRt,mergeFunctions:{...wRt,...Object.fromEntries(Object.entries(p).filter(([_,g])=>Object.hasOwn(wRt,_)).map(([_,g])=>g===!1?[_,wRt.mergeOthers]:[_,g]))},metaDataUpdater:p.metaDataUpdater??f9n,deepmerge:l,useImplicitDefaultMerging:p.enableImplicitDefaultMerging??!1,filterValues:p.filterValues===!1?void 0:p.filterValues??_9n,actions:yFe}}e(T9n,"getUtils");function kAr(p,l,_){var P;let g=((P=l.filterValues)==null?void 0:P.call(l,p,_))??p;if(g.length===0)return;if(g.length===1)return xnr(g,l,_);let C=TAr(g[0]);if(C!==0&&C!==5){for(let F=1;F<g.length;F++)if(TAr(g[F])!==C)return xnr(g,l,_)}switch(C){case 1:return D9n(g,l,_);case 2:return C9n(g,l,_);case 3:return E9n(g,l,_);case 4:return k9n(g,l,_);default:return xnr(g,l,_)}}e(kAr,"mergeUnknowns");function D9n(p,l,_){let g=l.mergeFunctions.mergeRecords(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeRecords!==l.defaultMergeFunctions.mergeRecords?l.defaultMergeFunctions.mergeRecords(p,l,_):g}e(D9n,"mergeRecords");function C9n(p,l,_){let g=l.mergeFunctions.mergeArrays(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeArrays!==l.defaultMergeFunctions.mergeArrays?l.defaultMergeFunctions.mergeArrays(p):g}e(C9n,"mergeArrays");function E9n(p,l,_){let g=l.mergeFunctions.mergeSets(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeSets!==l.defaultMergeFunctions.mergeSets?l.defaultMergeFunctions.mergeSets(p):g}e(E9n,"mergeSets");function k9n(p,l,_){let g=l.mergeFunctions.mergeMaps(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeMaps!==l.defaultMergeFunctions.mergeMaps?l.defaultMergeFunctions.mergeMaps(p):g}e(k9n,"mergeMaps");function xnr(p,l,_){let g=l.mergeFunctions.mergeOthers(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeOthers!==l.defaultMergeFunctions.mergeOthers?l.defaultMergeFunctions.mergeOthers(p):g}e(xnr,"mergeOthers");var w9n=!0,wAr=void 0,PRt=class PRt extends ERt{constructor(_={},g={devtools:!1},C={},P){var F;super(_,g,PRt.makeSettings(C),P==null?void 0:P.getFramesMessageBroker(),P==null?void 0:P.context());this.liveAppPage=P;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async _=>{this.appFrame=_,this.frameMsgBroker.register("live",this.appFrame,j4.vtg.recordEvents),this.setEvaluateWithChecksumTargetFrame(this.appFrame),await this.injectedScriptManager.addTrackedFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new tPe(this.frameMsgBroker,this.injectedScriptManager,{headless:((F=C==null?void 0:C.timeMachine)==null?void 0:F.headless)??!0}),this.liveTimeMachine=new tPe(this.frameMsgBroker,this.injectedScriptManager),this.appViewport=C.viewport}static makeSettings(_={}){return EAr({frontendTestGenerationConfig:{showFrontendLogs:j4.isDevMode,recordOptions:{...wAr?{checkoutEveryNms:wAr}:{},recordCanvas:!0,recordCrossOriginIframes:!0,collectFonts:!0,inlineImages:!0,sampling:{mousemove:!1}}}},_)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(_){this.registeredTimeMachineFrames.push(_)}async prepare(_={}){let g=await super.prepare(_);if(this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.liveAppPage&&await(await this.page.context().newCDPSession(this.page)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new kRt(this.page).start(),this.timeMachineFrame=this.page.frames().find(C=>C.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(C=>C.name()==="live-iframe"),w9n){let C;this.liveAppPage?C=this.liveAppPage:(C=await this.context.newPage(),await C.setViewportSize(this.appViewport)),await this.onAppFrameCreated(C.mainFrame())}else await this.interceptPageRequests(),await this.onAppFrameCreated(this.page.frames()[1]);return await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),g}async exposeFunctionsForVTG(){await this.page.exposeFunction("checksumGetFilesFromLive",async _=>{let g=this.appFrame;if(!g){Nh.info("no live frame detected");return}try{return g.evaluate(C=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(C),_)}catch(C){Nh.error("Error getting frame window",C)}})}async navigate(_){return this.appFrame.goto(_)}async getCurrentURL(){return this.appFrame.url()}getInjectedScriptInitModules(_){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(_)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1}:_===this.appFrame?{...super.getInjectedScriptInitModules(_),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0}:super.getInjectedScriptInitModules(_)}async interceptPageRequests(){async function _(C){try{return await AAr.promises.readFile(C,"utf8")}catch(P){return Nh.error(`Error reading file ${C}:`,P),null}}e(_,"readLocalFile");function g(C){switch(PAr.extname(C).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(g,"getContentType"),await this.page.route("**/*",async C=>{try{let P=C.request().url();if(console.log("intercepted!",P),P.startsWith("file://")){let F=P.replace("file://",""),M=await _(F);M!==null?await C.fulfill({status:200,contentType:g(F),body:M}):await C.abort()}else{let F=0,M=5;for(;F<M;){let V=await C.fetch(),W=V.status();if(W>299&&W<400){F++;let Q=V.headers().location;if(!Q){console.warn("Redirect without Location header"),await C.abort();return}console.log(`Redirect ${F} to: ${Q}`),C.request().url=()=>new URL(Q,P).toString()}else{let Q={};Q["Access-Control-Allow-Origin"]="*",Q["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",Q["Access-Control-Allow-Headers"]="Content-Type, Authorization",await C.fulfill({response:V,headers:{...V.headers(),...Q,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}console.warn(`Max redirects (${M}) exceeded`),await C.abort()}}catch(P){console.warn("intercept error",P)}})}};e(PRt,"ChecksumVTGWebDriver");var ARt=PRt;var _it=require("fs");var A9n=".settings.json",Snr=class Snr{constructor(l){this.checksumRoot=l;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0};this.settingsFilePath=`${this.checksumRoot}/${A9n}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:j4.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:j4.vtg.aiAssertions.disabled,disableAILocators:j4.vtg.aiLocators.disabled}}updateSettings(l){this.settings=Object.assign(this.settings,l),this.writeSettingsData()}readSettings(){if(!(0,_it.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let l=(0,_it.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(l)}writeSettingsData(){(0,_it.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}};e(Snr,"VtgSettingsService");var NRt=Snr;var zwt=require("fs");var Tnr=class Tnr{constructor(l,_,g,C,P,F={logPerformance:!1}){this.timeMachine=l;this.actionsManager=_;this.apiService=g;this.userStoryService=C;this.remoteSessionId=P;this.options=F}async generatePromptData(l,_){let g=l.id;if(this.promptData)return{...this.promptData,action:l};let C=this.getActionTimestamps(g,_);if(!C)return;let P=await this.timeMachine.executeReducedHTMLTask(C.before),F=await this.timeMachine.executeReducedHTMLTask(C.after),M=this.userStoryService.getStory();return this.promptData={reducedHTML:F,previousReducedHTML:P,actionId:g,previousActions:this.actionsManager.actions.slice(0,this.actionsManager.actions.length-1),action:l,title:M.goal,steps:M.instructions},this.promptData}async generatePromptDataForThought(l,_){return this.generatePromptData(l,_)}getVariables(){return[]}getVariablesString(l){return""}getActionTimestamps(l,_){let g=this.actionsManager.actions,C=g.findIndex(M=>M.id===l);if(C===-1){Nh(`[init] No action with id ${l} was found in executed actions`);return}let P=g[C],F=g[C+1];return{before:P.timestamp,after:(F==null?void 0:F.timestamp)??_}}logPerformance(l,_){this.options.logPerformance&&console.log(`${l} in`,Date.now()-_,"ms")}};e(Tnr,"ActionsAgent");var FRt=Tnr;var Dnr=class Dnr extends XNe{constructor(_,g,C,P,F,M={logPerformance:!1}){super(_,g,C);this.actionsManager=_;this.apiService=g;this.userStoryService=C;this.timeMachine=P;this.webDriver=F;this.options=M;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new Art(P,_,g,this.remoteSessionId,this.userStoryService),this.actionsAgent=new FRt(P,_,g,this.userStoryService,this.remoteSessionId)}async init({retriesLeft:_=3,keepActionsWithoutDescription:g=!1,lastActionId:C=void 0}={}){await super.init({retriesLeft:_,keepActionsWithoutDescription:g,lastActionId:C}),this.activeRemoteSessionIdByStepId.set(C,this.remoteSessionId)}async generateActionThoughts({action:_,processId:g}){try{if(this.isRunning(_.id))throw Nh.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let C=await this.actionsAgent.generatePromptDataForThought(_),P=await this.callThoughtApi("actions",C,g);return this.evaluateThoughtResponse({processId:g,id:_.id,thought:P.thought})}catch(C){return Nh.error("Error in AI thought generation",C),this.evaluateThoughtResponse({processId:g,id:_.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(_.id)}}async generateAssertionThought({assertion:_,parentActionId:g,processId:C}){try{if(this.isRunning(_.id))throw Nh.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let P=await this.assertionsAgent.generateThoughtPromptData(g,_),F=await this.callThoughtApi("assertions",P,C);return this.evaluateThoughtResponse({processId:C,id:_.id,thought:F.thought})}catch(P){return Nh.error("Error in AI thought generation",P),this.evaluateThoughtResponse({processId:C,id:_.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(_.id)}}stopGeneratingThought(_){this.activeRemoteSessionIdByStepId.delete(_)}async callThoughtApi(_,g,C){let P=Date.now();if(g)try{P=Date.now();let F=await this.apiService.post(`${_}/thoughts/generate`,{sessionId:this.remoteSessionId,data:g});if(!F.ok){Nh.error(`Request for ${_} thought generation failed with status ${F.status}`);return}let M=await F.json();if(!(M!=null&&M.thought))throw Nh("No thought generated for action, got response",F),new Error("No thought generated");let V=_==="actions"?g.action:g.assertion;return Nh(`Thought generated (${C})`,{type:_,stepId:V.id,locator:V.locator,thought:M.thought}),M}catch(F){throw Nh.error(`Error in AI thought generation (${C})`,F),F}}isRunning(_){return this.activeRemoteSessionIdByStepId.has(_)}async evaluateThoughtResponse({id:_,processId:g,thought:C,error:P=!1}){try{await this.webDriver.page.evaluate(({id:F,thought:M,error:V,processId:W})=>{window.vtg.onAsyncProcessResponse({id:F,processId:W,thought:M,error:V})},{id:_,thought:C,error:P,processId:g})}catch(F){Nh.error("Error in AI thought generation",F)}}};e(Dnr,"VTGThoughtsService");var IRt=Dnr;var Cnr=class Cnr{constructor(l=new Utt){this._variableStore=l}get variableStore(){return this._variableStore}};e(Cnr,"VTGVariableStoreService");var ORt=Cnr;var _VtgEvaluatorService=class _VtgEvaluatorService{constructor(p,l){this.variableStoreService=p;this.vtgTestFileMode=l;this.listenerBody=e(async({vtg})=>{await vtg.eval(async(code,callback)=>{try{callback(null,await eval(`(async () => {
|
|
1947
|
+
`)}getLocalSavedData(l){let _=`${this.testAssetsManager.getLocalSavePath()}/${l}/test.json`,g=this.readJsonFile(_);return g?{...g,executedActions:g.executedActions.map(C=>({...C,timestamp:void 0}))}:null}readJsonFile(l){try{let _=(0,HZe.readFileSync)(l,"utf-8");return JSON.parse(_)}catch(_){return Nh.error(`Error reading or parsing JSON file: ${_}`),null}}makeDraftData(){let l=this.userStoryService.getStory(),_=this.userStoryService.getTestGenerationData(),g=this.userStoryService.getEnvInfo();return{actions:this.actionsManager.actions,internalTestId:_.internalTestId,environmentUserId:g.user.username,description:l.goal}}async generateTestFileString(l){try{let _=this.makeDraftData(),g=l?`${l}.draft.spec.ts`:`test-${_.internalTestId}.draft.spec.ts`,C=await this.apiService.post("test-generation/generate-test-file-string",_);if(!C.ok)throw new Error(`test generation request failed: ${C.statusText}`);let P=await C.text();lxr(P,g,this.testAssetsManager.getLocalSavePath())}catch(_){throw Nh.error("Failed to generate test file string",_),new Error("Failed to generate test file string")}}localSave(){let l=JSON.stringify(this.replayJSON,null,2),_=this.testAssetsManager.getAssetsFolderPath();(0,HZe.writeFileSync)(`${_}/test.json`,l),(0,HZe.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/test.json`,l)}get replayJSON(){var l;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(l=this.config.environments.find(_=>_.default))==null?void 0:l.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async localBackup(l){if(l){this.testAssetsManager.setCurrentSaveAsLocation(l);let _=this.testAssetsManager.getLocalSaveAsPath();pxr(this.testAssetsManager.getLocalAutoSavePath(),_)}return this.saveTestFile()}doesFolderExistInSaveDir(l){try{let _=`${this.testAssetsManager.getLocalSavePath()}/${l}`;return(0,HZe.statSync)(_).isDirectory()}catch(_){if(_.code==="ENOENT")return!1;throw _}}async saveToCloud(){try{if(!this.userStoryService.hasTestGenerationData()){Nh("No test generation data, can't upload");return}let l=await this.userStoryService.createTestGeneration(),_=new gLt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${l}/get-upload-url`),g=e(M=>({complete:!1,error:!1,response:void 0,info:M}),"buildUploadAsset"),C=g({type:"trace",path:this.testAssetsManager.getTraceFilePath()}),P=g({type:"har",path:await O4r(this.testAssetsManager.getHarFolderPath())});await Promise.all([_.uploadAsset(C),_.uploadAsset(P)]);let F=this.actionsManager.actions.map(M=>({...M,parentFramesSelectors:M.parentFramesSelectors?M.parentFramesSelectors.filter(V=>V!=="iframe"):void 0}));await this.apiService.post(`test-generation/${l}/completed`,{actions:F})}catch(l){Nh.error("Failed to upload test",l)}}};e(Ter,"VtgStorageService");var ZLt=Ter;var Der=class Der{constructor(l,_){this.apiService=l;this.config=_}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){var l;return!!((l=this.userStoryTestGeneration)!=null&&l.internalTestId)}setStoryInfo(l,_){this.story=l,this.userStoryTestGeneration=_}async fetchStory(l){if(j4.vtg.useFakeStory){console.log("Using fake flow data"),this.story={...j4.vtg.fakeStory,environment:{name:void 0,userRole:void 0}},this.userStoryTestGeneration={internalTestId:j4.vtg.fakeTestGeneration.internalTestId,generationBatchId:j4.vtg.fakeTestGeneration.generationBatchId};return}if(!l)throw new Error("no story id provided");let g=await(await this.apiService.post(`test-generation/info/${l}`)).json();if(!(g!=null&&g.id))throw new Error(`Story ${l} not found`);console.log("Received flow data:",g);let{id:C,title:P,steps:F,startUrl:M,userRole:V,environment:W,internalTestId:Q,generationBatchId:se}=g;this.userStoryTestGeneration={internalTestId:Q,generationBatchId:se},this.story={id:C,goal:P,instructions:F,url:M,environment:{userRole:V,name:W}}}getEnvInfo(){return RCt(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let l=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.userStoryTestGeneration.internalTestId,testGenerationBatchId:this.userStoryTestGeneration.generationBatchId}),{testGenerationId:_}=await l.json();return this.userStoryTestGeneration.testGenerationId=_,_}};e(Der,"VtgUserStoryService");var eMt=Der;var Cer=class Cer{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(l){var _;this._executedActions=l,(_=this.storageService)==null||_.localSave()}addAction(l){var _;this._executedActions.push(l),(_=this.storageService)==null||_.localSave()}setActions(l){this._executedActions=l}updateAssertionById(l,_){this.executedActions=this._executedActions.map(g=>{var C;if(g.id===l){let P=!!((C=g.assertions)!=null&&C.find(({id:M})=>M===_.id)),F={...g};return P?F.assertions=g.assertions.map(M=>M.id===_.id?Object.assign(M,_):M):F.assertions=[...g.assertions??[],_],{...F,assertions:F.assertions.sort((M,V)=>M.timestamp!==V.timestamp?M.timestamp-V.timestamp:M.createdAt-V.createdAt)}}return g})}setStorageService(l){this.storageService=l}createAction(l){var V,W,Q;let{id:_,data:g,options:C,type:P}=l,F={id:_,...g},M=[...this._executedActions];switch(C==null?void 0:C.type){case"insertAfter":{let se=this.findActionOrAssertionById(C.afterStepId),G=M.findIndex(_e=>_e.id===se.action.id);if(se.assertion||(W=(V=se.action)==null?void 0:V.assertions)!=null&&W.length){let _e=se.assertion??se.action.assertions[0],{before:ne,after:ue}=A4n(((Q=M[G])==null?void 0:Q.assertions)??[],_e.id,!!se.assertion);M[G].assertions=ne,F.assertions=ue.map(qe=>({...qe,actionId:F.id}))}G!==-1?M.splice(G+1,0,F):M.push(F);break}case"insertLast":M.push(F);break;case"replace":{let se=M.findIndex(G=>G.id===C.stepId);se!==-1&&M.splice(se,1,F);break}case"replaceLast":M.length>0&&(M[M.length-1]=F);break}this.executedActions=M}pushExecutedActionOrAddAfterParent(l,_={}){if(_.previousActionId){let g=this._executedActions.findIndex(({id:C})=>C===_.previousActionId);if(g!==-1){let C={...l,timestamp:this._executedActions[g].timestamp+1};this._executedActions=[...this._executedActions.slice(0,g+1),C,...this._executedActions.slice(g+1)]}}else this.executedActions=Array.isArray(l)?[...this._executedActions,...l]:[...this._executedActions,l]}addManualActionsToExecuted(l){this.executedActions=[...this._executedActions,l]}updateExecutedAction(l){let _=this._executedActions.findIndex(({id:g})=>g===l.id);_!==-1&&(this.executedActions=[...this._executedActions.slice(0,_),{...this._executedActions[_],...l},...this._executedActions.slice(_+1)])}deleteStep(l,_,g={assertionsOnly:!1}){_==="Action"?g.assertionsOnly?this.executedActions=this._executedActions.map(C=>C.id===l?{...C,assertions:[]}:C):this.executedActions=this._executedActions.filter(C=>C.id!==l):_==="Assertion"&&(this.executedActions=this._executedActions.map(C=>(C.assertions=(C.assertions??[]).filter(P=>P.id!==l),C)))}clearTestSteps(l=!0){if(l){let{navigation:_,login:g}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((C,P)=>([_==null?void 0:_.id,g==null?void 0:g.id].includes(P.id)&&C.push({...P,assertions:[]}),C),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(l){this.clearTestSteps(!1),this.executedActions=l}findLoginAndNavigationActions(){let l=this._executedActions.find(({eventCode:g})=>g==="navigation"),_=this._executedActions.find(({eventCode:g})=>g==="login");return{navigation:l,login:_}}addAssertionToAction(l,_){this.executedActions=this._executedActions.map(g=>{if(g.id!==l.actionId)return g;if(g.assertions||(g.assertions=[]),_){let C=g.assertions.findIndex(({id:P})=>_===P);g.assertions.splice(C+1,0,l)}else g.assertions=[l,...g.assertions??[]];return g})}findActionByAssertionId(l){return this._executedActions.find(({assertions:_=[]})=>_.find(g=>g.id===l))}findActionOrAssertionById(l){let _={action:null,assertion:null};return this._executedActions.forEach(g=>{g.id===l&&(_.action=g);let C=(g.assertions??[]).find(P=>P.id===l);C&&(_={action:g,assertion:C})}),_}};e(Cer,"VtgActionsManager");var tMt=Cer,A4n=e((p,l,_=!0)=>{let g=Number(_),C=p.findIndex(M=>M.id===l);if(C===-1)return{before:p,after:[]};let P=p.slice(0,C+g),F=p.slice(C+g);return{before:P,after:F}},"splitArrayAtId");var mnr=x7(_Ar()),vAr=x7(require("net")),bAr=x7(frr()),xAr=x7(yAr());var _nr=class _nr{constructor(l,_,g){this.app=l;this.assertionsService=_;this.actionsManager=g}setupEndpoints(){this.app.post("/api/createStep",async(l,_)=>{let g=l.body;try{if(g.type==="Assertion"){let C=this.assertionsService.createAssertion(g);return _.status(200).json(C)}if(g.type==="Action")return this.actionsManager.createAction(g),_.send("success")}catch(C){return Nh.error("/api/createStep error:",C),_.status(500).send(C)}}),this.app.patch("/api/updateStep",async(l,_)=>{let g=l.body;try{if(g.type==="Assertion"){let C=await this.assertionsService.updateAssertion({id:g.id,data:g.data});_.status(200).json(C)}if(g.type==="Action")return this.actionsManager.updateExecutedAction({...g.data,id:g.id}),_.send("success")}catch(C){return _.status(500).send(C)}}),this.app.delete("/api/deleteStep",async(l,_)=>{let{id:g,options:C,type:P}=l.body;try{this.actionsManager.deleteStep(g,P,C)}catch(F){return _.status(500).send(F)}return _.status(200).send({message:"Success!"})}),this.app.post("/api/clear-test",async(l,_)=>{try{let g=this.actionsManager.clearTestSteps();return _.status(200).send(g)}catch(g){return _.status(500).send(g)}})}};e(_nr,"VtgStepsController");var xRt=_nr;var dnr=class dnr{constructor(l,_){this.app=l;this.locatorsService=_}setupEndpoints(){this.app.post("/api/locators/play",async(l,_)=>{let g=l.body;try{let C=await this.locatorsService.verifyLocatorOrSelector(g);return _.status(200).send(C)}catch(C){return _.status(400).send({error:C.message})}}),this.app.post("/api/locators/test-identical",async(l,_)=>{let{locator:g,compareLocator:C,timestamp:P}=l.body;try{let F=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(g,C,P);return _.status(200).send(F)}catch(F){return _.status(400).send({error:F.message})}}),this.app.post("/api/ai/locators/generate",async(l,_)=>{let{step:g,target:C,processId:P}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.generateAILocators(g,C,P);let F={processId:P,stepId:C.id,success:!0};_.status(200).send(F)}catch(F){_.status(400).send({processId:P,success:!1,error:F.message})}}),this.app.post("/api/ai/locators/extract-css",async(l,_)=>{let{step:g,target:C,processId:P,llmLocators:F}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.extractCSS(g,C,P,F);let M={processId:P,stepId:C.id,success:!0};_.status(200).send(M)}catch(M){_.status(400).send({processId:P,error:M.message})}}),this.app.post("/api/ai/locators/filter",async(l,_)=>{let{step:g,target:C,processId:P,candidates:F}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.filterLocators(g,C,P,F);let M={processId:P,stepId:C.id,success:!0};_.status(200).send(M)}catch(M){_.status(400).send({processId:P,error:M.message})}}),this.app.delete("/api/ai/locators/process/:id",async(l,_)=>{let g=l.params.id;try{this.locatorsService.cancelProcess(g),Nh("Cancelled process",g),_.status(200).send({success:!0})}catch(C){_.status(400).send({error:C.message})}})}};e(dnr,"VtgLocatorsController");var SRt=dnr;var hnr=class hnr{constructor(l,_,g,C,P,F,M,V,W){this.actionsService=l;this.assertionsService=_;this.locatorsService=g;this.aiTestGenerationService=C;this.aiAssertionsService=P;this.aiThoughtsService=F;this.actionsManager=M;this.storageService=V;this.settingsService=W}async start(){return this.app=(0,mnr.default)(),this.app.use((0,xAr.default)()),this.app.use(bAr.default.json({limit:"50mb"})),this.app.use(mnr.default.raw({type:"multipart/form-data",limit:"50mb"})),this.port=await this.acquirePortNumber(),new xRt(this.app,this.assertionsService,this.actionsManager).setupEndpoints(),this.setupEndpoints(),new SRt(this.app,this.locatorsService).setupEndpoints(),new Promise(l=>{this.app.listen(this.port,()=>{console.log(`Express server running on port ${this.port}`),l()})})}setupEndpoints(){this.app.get("/api",async(l,_)=>{_.send("success")}),this.app.post("/api/test/generate-test-file-string",async(l,_)=>{try{return await this.storageService.generateTestFileString(l.body.fileName),_.send("success")}catch(g){return _.status(400).send({error:g.message})}}),this.app.post("/api/test/upload",async(l,_)=>(await this.storageService.saveToCloud(),_.send("success"))),this.app.post("/api/test/local-save",async(l,_)=>{await this.storageService.localSave(),_.send("success")}),this.app.post("/api/reload-test-from-file",async(l,_)=>{try{if(!this.storageService.isLoadedFromTestFile)return _.status(404).send("No test file found");let g=await this.storageService.reloadTestFromFile();return _.status(200).send(g)}catch(g){return console.log("failed to reload test from file",g),_.status(500).send(g.message)}}),this.app.post("/api/test/verify-save-location",async(l,_)=>{try{let g=this.storageService.doesFolderExistInSaveDir(l.body.location);_.send({exists:g})}catch(g){_.status(400).send({error:g})}}),this.app.post("/api/test/backup",async(l,_)=>{let{backupFolderName:g}=l.body;if(!fxr(g))return _.status(400).send({error:"Invalid folder name"});let C=await this.storageService.localBackup(g);_.send(C)}),this.app.post("/api/ai/init",async(l,_)=>{await this.aiTestGenerationService.init(),_.send("success")}),this.app.post("/api/ai/iterate",async(l,_)=>{let g=l.body,C=await this.aiTestGenerationService.iterate(g);return C?_.status(200).json(C):_.status(400).send("no action generated")}),this.app.post("/api/thoughts/actions/generate",async(l,_)=>{let g=l.body,{processId:C,action:{id:P}}=g;try{this.aiThoughtsService.generateActionThoughts(g);let F={processId:C,stepId:P,success:!0};_.status(200).send(F)}catch(F){return _.status(400).send({processId:C,error:F.message})}}),this.app.post("/api/thoughts/assertions/generate",async(l,_)=>{let g=l.body,{processId:C,assertion:{id:P}}=g;try{this.aiThoughtsService.generateAssertionThought(g);let F={processId:C,stepId:P,success:!0};_.status(200).send(F)}catch(F){return _.status(400).send({processId:C,error:F.message})}}),this.app.post("/api/thoughts/stop-generate",async(l,_)=>{let g=l.body;this.aiThoughtsService.stopGeneratingThought(g.stepId);let C={stepId:g.stepId};return _.status(200).send(C)}),this.app.post("/api/assertions/generate",(l,_)=>{let g=l.body,{processId:C}=g;try{this.aiAssertionsService.generateAiAssertions(g);let P={processId:C,stepId:g.id,success:!0};return _.status(200).json(P)}catch(P){return _.status(500).send({processId:C,error:P.message})}}),this.app.post("/api/assertions/stop-generate",(l,_)=>{let{id:g}=l.body,C={stepId:g};return this.aiAssertionsService.stopGenerateAiAssertions(g),_.status(200).send(C)}),this.app.post("/ai/stop",async(l,_)=>{this.aiTestGenerationService.stop()}),this.app.post("/api/assertion/verify/time-machine",async(l,_)=>{let g=l.body,C=await this.assertionsService.verifyOnTimeMachine(g);return _.status(200).send(C)}),this.app.post("/api/assertion/verify/live",async(l,_)=>{let g=l.body;try{let C=await this.assertionsService.verifyOnLive(g),P=C.success?200:404;return _.status(P).send(C)}catch(C){return _.status(404).send({success:!1,message:String(C)})}}),this.app.post("/api/assertion/save",async(l,_)=>{let g=l.body;try{let C=await this.assertionsService.updateAssertion(g);_.status(200).json(C)}catch(C){_.status(400).send({error:C.message})}}),this.app.post("/api/steps/execute",async(l,_)=>{let g=l.body;try{let C=null;return u9n(g)?C=await this.aiTestGenerationService.executeAction(g):l9n(g)&&(C=await this.actionsService.executeAction(g)),_.status(200).json(C)}catch(C){return _.status(400).send({error:C.message})}}),this.app.post("/api/upload-files",async(l,_)=>{try{await this.actionsService.uploadFiles(l.body.files)}catch(g){return _.status(500).send(g)}return _.status(200).send({message:"File uploaded successfully!"})}),this.app.post("/api/steps/add-manual-action",async(l,_)=>{let g=l.body;return this.actionsManager.addManualActionsToExecuted(g.action),_.send("success")}),this.app.put("/api/steps",async(l,_)=>{let g=l.body;try{this.actionsManager.pushExecutedActionOrAddAfterParent(g.action,g.options)}catch(C){return _.status(500).send(C)}return _.send("success")}),this.app.get("/api/settings",async(l,_)=>{let g=this.settingsService.getSettings();return _.status(200).send(g)}),this.app.post("/api/settings",async(l,_)=>(this.settingsService.updateSettings(l.body),_.status(200).send({message:"Success!"})))}async acquirePortNumber(){return await new Promise((l,_)=>{let g=vAr.default.createServer();g.unref(),g.on("error",_),g.listen(0,()=>{let C=g.address().port;g.close(()=>{l(C)})})})}async evaluateServerPort(l){if(!l)throw new Error("Page not initialized");await l.evaluate(_=>{window.vtg.setServerPort(_)},this.port)}};e(hnr,"VtgExpressServer");var TRt=hnr;function u9n(p){var l;return((l=p.options)==null?void 0:l.isAISuggestion)===!0}e(u9n,"isAIExecuteActionArgs");function l9n(p){var l;return((l=p.options)==null?void 0:l.isAISuggestion)===!1}e(l9n,"isManualExecuteActionArgs");var DRt=require("fs");var gnr=class gnr{constructor(l,_,g){this.projectRootDirectory=l;this.checksumRoot=_;this.vtgTestFileRunConfig=g;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.checksumRoot}/drafts`}createTestGenerationAssetsFolders(){this.assetsFolderPath=this.projectRootDirectory+`/tg-assets/${Date.now()}`,(0,DRt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,DRt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(l){this.autoSaveFolderPath=`/auto-save/${l}`,(0,DRt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return this.localSaveFolderPath+this.autoSaveFolderPath}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 l=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${l}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getLogsPath(){return`${this.localSaveFolderPath}/logs`}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(l){l&&!(l!=null&&l.startsWith("auto-save"))&&(this.currentSaveAsLocation=l)}};e(gnr,"VtgTestAssetsManager");var CRt=gnr;var p9n={useCDPSession:!0,trackLoadedResources:!0},ynr=class ynr extends jOt{constructor(_={},g={devtools:!1},C={},P,F){super({...p9n,..._},g,P,F);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(_,g=1e3)=>{try{return await _.waitForFunction(()=>!!window.checksum,void 0,{timeout:g}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async _=>{try{return await _.waitForFunction(()=>{var g;return!!((g=window.checksum)!=null&&g.testGenerator)}),_.evaluate(async({appSpecificRules:g,config:C,initModules:P})=>{window.checksum.testGenerator.init(g,C,P)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(_)})}catch(g){console.log("initInjectedScript exception",g)}},"initInjectedScript");this.settings={...this.settings,...C},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(_={}){let g=await super.prepare(_);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")}),g}setEvaluateWithChecksumTargetFrame(_){this.evaluateWithChecksumTargetFrame=_}getInjectedScriptInitModules(_){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(_,g,C=this.evaluateWithChecksumTargetFrame){let P=this.injectedScriptManager.getNavigationPromise(C);P&&await P;try{return C.evaluate(_,g)}catch(F){throw console.error("evaluateWithChecksum error",F,_.toString()),F}}async getBestMatchingElementSimilarityScore(_){return this.evaluateWithChecksum(async g=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(g),_)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(_){return this.evaluateWithChecksum(g=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(g),_)}async takeElementSnapshot(_,g,C={},P={}){try{let{snapshot:F,elementLocator:M}=await super.takeElementSnapshot(_,g,C);if(!F||!C.takeBodyScreenshot)return F?{snapshot:F}:{};await this.highlightElementByLocator(M,C.mousePosition);let V=await this.takePageSnapshot(P);return await this.clearHighlights(),{snapshot:F,bodySnapshot:V}}catch(F){return console.error("[ChecksumWebDriver] takeElementSnapshot error",F),{}}}async highlightElementByLocator(_,g,C="20px solid rgba(255,0,0,1)",P=!1){return this.evaluateWithChecksum(async([F,M,V,W])=>{window.checksum.testGenerator.highlightElement(F,{highlightStyle:{outline:M},mousePosition:V,scroll:W})},[await _.elementHandle(),C,g,P])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(ynr,"ChecksumWebDriver");var ERt=ynr;var AAr=require("fs"),PAr=x7(require("path"));var vnr=require("fs");var bnr=class bnr{constructor(l,_=j4.vtg.localBuildPath){this.page=l;this.filePath=_;this.filePath=_}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp(),await WC(2e3)}catch(l){Nh.error("An error occurred:",l)}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let l=j4.vtg.appURL;await this.page.goto(l,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(j4.isDevMode){WPt(!0);return}try{let l=await vnr.promises.readFile(this.filePath,"utf8"),_=/(src|href)=(["'])(\/)static/g,g=l.replace(_,"$1=$2.$3static");await vnr.promises.writeFile(this.filePath,g,"utf8"),Nh(`Successfully modified ${this.filePath}`)}catch(l){Nh.error(`Error processing file ${this.filePath}:`,l)}}};e(bnr,"VtgFrontendLauncher");var kRt=bnr;var yFe={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},hai={defaultMerge:yFe.defaultMerge};function f9n(p,l){return l}e(f9n,"defaultMetaDataUpdater");function _9n(p,l){return p.filter(_=>_!==void 0)}e(_9n,"defaultFilterValues");var SAr;(function(p){p[p.NOT=0]="NOT",p[p.RECORD=1]="RECORD",p[p.ARRAY=2]="ARRAY",p[p.SET=3]="SET",p[p.MAP=4]="MAP",p[p.OTHER=5]="OTHER"})(SAr||(SAr={}));function TAr(p){return typeof p!="object"||p===null?0:Array.isArray(p)?2:h9n(p)?1:p instanceof Set?3:p instanceof Map?4:5}e(TAr,"getObjectType");function d9n(p){let l=new Set;for(let _ of p)for(let g of[...Object.keys(_),...Object.getOwnPropertySymbols(_)])l.add(g);return l}e(d9n,"getKeys");function m9n(p,l){return typeof p=="object"&&Object.prototype.propertyIsEnumerable.call(p,l)}e(m9n,"objectHasProperty");function CAr(p){var g;let l=0,_=(g=p[0])==null?void 0:g[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var C;do{if(_===void 0)return{done:!0,value:void 0};let P=_.next();if(P.done===!0){l+=1,_=(C=p[l])==null?void 0:C[Symbol.iterator]();continue}return{done:!1,value:P.value}}while(!0)}}}}}e(CAr,"getIterableOfIterables");var DAr=["[object Object]","[object Module]"];function h9n(p){if(!DAr.includes(Object.prototype.toString.call(p)))return!1;let{constructor:l}=p;if(l===void 0)return!0;let _=l.prototype;return!(_===null||typeof _!="object"||!DAr.includes(Object.prototype.toString.call(_))||!_.hasOwnProperty("isPrototypeOf"))}e(h9n,"isRecord");function g9n(p,l,_){let g={};for(let C of d9n(p)){let P=[];for(let V of p)m9n(V,C)&&P.push(V[C]);if(P.length===0)continue;let F=l.metaDataUpdater(_,{key:C,parents:p}),M=kAr(P,l,F);M!==yFe.skip&&(C==="__proto__"?Object.defineProperty(g,C,{value:M,configurable:!0,enumerable:!0,writable:!0}):g[C]=M)}return g}e(g9n,"mergeRecords$1");function y9n(p){return p.flat()}e(y9n,"mergeArrays$1");function v9n(p){return new Set(CAr(p))}e(v9n,"mergeSets$1");function b9n(p){return new Map(CAr(p))}e(b9n,"mergeMaps$1");function x9n(p){return p.at(-1)}e(x9n,"mergeOthers$1");var wRt={mergeRecords:g9n,mergeArrays:y9n,mergeSets:v9n,mergeMaps:b9n,mergeOthers:x9n};function EAr(...p){return S9n({})(...p)}e(EAr,"deepmerge");function S9n(p,l){let _=T9n(p,g);function g(...C){return kAr(C,_,l)}return e(g,"customizedDeepmerge"),g}e(S9n,"deepmergeCustom");function T9n(p,l){return{defaultMergeFunctions:wRt,mergeFunctions:{...wRt,...Object.fromEntries(Object.entries(p).filter(([_,g])=>Object.hasOwn(wRt,_)).map(([_,g])=>g===!1?[_,wRt.mergeOthers]:[_,g]))},metaDataUpdater:p.metaDataUpdater??f9n,deepmerge:l,useImplicitDefaultMerging:p.enableImplicitDefaultMerging??!1,filterValues:p.filterValues===!1?void 0:p.filterValues??_9n,actions:yFe}}e(T9n,"getUtils");function kAr(p,l,_){var P;let g=((P=l.filterValues)==null?void 0:P.call(l,p,_))??p;if(g.length===0)return;if(g.length===1)return xnr(g,l,_);let C=TAr(g[0]);if(C!==0&&C!==5){for(let F=1;F<g.length;F++)if(TAr(g[F])!==C)return xnr(g,l,_)}switch(C){case 1:return D9n(g,l,_);case 2:return C9n(g,l,_);case 3:return E9n(g,l,_);case 4:return k9n(g,l,_);default:return xnr(g,l,_)}}e(kAr,"mergeUnknowns");function D9n(p,l,_){let g=l.mergeFunctions.mergeRecords(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeRecords!==l.defaultMergeFunctions.mergeRecords?l.defaultMergeFunctions.mergeRecords(p,l,_):g}e(D9n,"mergeRecords");function C9n(p,l,_){let g=l.mergeFunctions.mergeArrays(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeArrays!==l.defaultMergeFunctions.mergeArrays?l.defaultMergeFunctions.mergeArrays(p):g}e(C9n,"mergeArrays");function E9n(p,l,_){let g=l.mergeFunctions.mergeSets(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeSets!==l.defaultMergeFunctions.mergeSets?l.defaultMergeFunctions.mergeSets(p):g}e(E9n,"mergeSets");function k9n(p,l,_){let g=l.mergeFunctions.mergeMaps(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeMaps!==l.defaultMergeFunctions.mergeMaps?l.defaultMergeFunctions.mergeMaps(p):g}e(k9n,"mergeMaps");function xnr(p,l,_){let g=l.mergeFunctions.mergeOthers(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeOthers!==l.defaultMergeFunctions.mergeOthers?l.defaultMergeFunctions.mergeOthers(p):g}e(xnr,"mergeOthers");var w9n=!0,wAr=void 0,PRt=class PRt extends ERt{constructor(_={},g={devtools:!1},C={},P){var F;super(_,g,PRt.makeSettings(C),P==null?void 0:P.getFramesMessageBroker(),P==null?void 0:P.context());this.liveAppPage=P;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async _=>{this.appFrame=_,this.frameMsgBroker.register("live",this.appFrame,j4.vtg.recordEvents),this.setEvaluateWithChecksumTargetFrame(this.appFrame),await this.injectedScriptManager.addTrackedFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new tPe(this.frameMsgBroker,this.injectedScriptManager,{headless:((F=C==null?void 0:C.timeMachine)==null?void 0:F.headless)??!0}),this.liveTimeMachine=new tPe(this.frameMsgBroker,this.injectedScriptManager),this.appViewport=C.viewport}static makeSettings(_={}){return EAr({frontendTestGenerationConfig:{showFrontendLogs:j4.isDevMode,recordOptions:{...wAr?{checkoutEveryNms:wAr}:{},recordCanvas:!0,recordCrossOriginIframes:!0,collectFonts:!0,inlineImages:!0,sampling:{mousemove:!1}}}},_)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(_){this.registeredTimeMachineFrames.push(_)}async prepare(_={}){let g=await super.prepare(_);if(this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.liveAppPage&&await(await this.page.context().newCDPSession(this.page)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new kRt(this.page).start(),this.timeMachineFrame=this.page.frames().find(C=>C.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(C=>C.name()==="live-iframe"),w9n){let C;this.liveAppPage?C=this.liveAppPage:(C=await this.context.newPage(),await C.setViewportSize(this.appViewport)),await this.onAppFrameCreated(C.mainFrame())}else await this.interceptPageRequests(),await this.onAppFrameCreated(this.page.frames()[1]);return await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),g}async exposeFunctionsForVTG(){await this.page.exposeFunction("checksumGetFilesFromLive",async _=>{let g=this.appFrame;if(!g){Nh.info("no live frame detected");return}try{return g.evaluate(C=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(C),_)}catch(C){Nh.error("Error getting frame window",C)}})}async navigate(_){return this.appFrame.goto(_)}async getCurrentURL(){return this.appFrame.url()}getInjectedScriptInitModules(_){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(_)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1}:_===this.appFrame?{...super.getInjectedScriptInitModules(_),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0}:super.getInjectedScriptInitModules(_)}async interceptPageRequests(){async function _(C){try{return await AAr.promises.readFile(C,"utf8")}catch(P){return Nh.error(`Error reading file ${C}:`,P),null}}e(_,"readLocalFile");function g(C){switch(PAr.extname(C).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(g,"getContentType"),await this.page.route("**/*",async C=>{try{let P=C.request().url();if(console.log("intercepted!",P),P.startsWith("file://")){let F=P.replace("file://",""),M=await _(F);M!==null?await C.fulfill({status:200,contentType:g(F),body:M}):await C.abort()}else{let F=0,M=5;for(;F<M;){let V=await C.fetch(),W=V.status();if(W>299&&W<400){F++;let Q=V.headers().location;if(!Q){console.warn("Redirect without Location header"),await C.abort();return}console.log(`Redirect ${F} to: ${Q}`),C.request().url=()=>new URL(Q,P).toString()}else{let Q={};Q["Access-Control-Allow-Origin"]="*",Q["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",Q["Access-Control-Allow-Headers"]="Content-Type, Authorization",await C.fulfill({response:V,headers:{...V.headers(),...Q,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}console.warn(`Max redirects (${M}) exceeded`),await C.abort()}}catch(P){console.warn("intercept error",P)}})}};e(PRt,"ChecksumVTGWebDriver");var ARt=PRt;var _it=require("fs");var A9n=".settings.json",Snr=class Snr{constructor(l){this.checksumRoot=l;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0};this.settingsFilePath=`${this.checksumRoot}/${A9n}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:j4.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:j4.vtg.aiAssertions.disabled,disableAILocators:j4.vtg.aiLocators.disabled}}updateSettings(l){this.settings=Object.assign(this.settings,l),this.writeSettingsData()}readSettings(){if(!(0,_it.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let l=(0,_it.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(l)}writeSettingsData(){(0,_it.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}};e(Snr,"VtgSettingsService");var NRt=Snr;var zwt=require("fs");var Tnr=class Tnr{constructor(l,_,g,C,P,F={logPerformance:!1}){this.timeMachine=l;this.actionsManager=_;this.apiService=g;this.userStoryService=C;this.remoteSessionId=P;this.options=F}async generatePromptData(l,_){let g=l.id;if(this.promptData)return{...this.promptData,action:l};let C=this.getActionTimestamps(g,_);if(!C)return;let P=await this.timeMachine.executeReducedHTMLTask(C.before),F=await this.timeMachine.executeReducedHTMLTask(C.after),M=this.userStoryService.getStory();return this.promptData={reducedHTML:F,previousReducedHTML:P,actionId:g,previousActions:this.actionsManager.actions.slice(0,this.actionsManager.actions.length-1),action:l,title:M.goal,steps:M.instructions},this.promptData}async generatePromptDataForThought(l,_){return this.generatePromptData(l,_)}getVariables(){return[]}getVariablesString(l){return""}getActionTimestamps(l,_){let g=this.actionsManager.actions,C=g.findIndex(M=>M.id===l);if(C===-1){Nh(`[init] No action with id ${l} was found in executed actions`);return}let P=g[C],F=g[C+1];return{before:P.timestamp,after:(F==null?void 0:F.timestamp)??_}}logPerformance(l,_){this.options.logPerformance&&console.log(`${l} in`,Date.now()-_,"ms")}};e(Tnr,"ActionsAgent");var FRt=Tnr;var Dnr=class Dnr extends XNe{constructor(_,g,C,P,F,M={logPerformance:!1}){super(_,g,C);this.actionsManager=_;this.apiService=g;this.userStoryService=C;this.timeMachine=P;this.webDriver=F;this.options=M;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new Art(P,_,g,this.remoteSessionId,this.userStoryService),this.actionsAgent=new FRt(P,_,g,this.userStoryService,this.remoteSessionId)}async init({retriesLeft:_=3,keepActionsWithoutDescription:g=!1,lastActionId:C=void 0}={}){await super.init({retriesLeft:_,keepActionsWithoutDescription:g,lastActionId:C}),this.activeRemoteSessionIdByStepId.set(C,this.remoteSessionId)}async generateActionThoughts({action:_,processId:g}){try{if(this.isRunning(_.id))throw Nh.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let C=await this.actionsAgent.generatePromptDataForThought(_),P=await this.callThoughtApi("actions",C,g);return this.evaluateThoughtResponse({processId:g,id:_.id,thought:P.thought})}catch(C){return Nh.error("Error in AI thought generation",C),this.evaluateThoughtResponse({processId:g,id:_.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(_.id)}}async generateAssertionThought({assertion:_,parentActionId:g,processId:C}){try{if(this.isRunning(_.id))throw Nh.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let P=await this.assertionsAgent.generateThoughtPromptData(g,_),F=await this.callThoughtApi("assertions",P,C);return this.evaluateThoughtResponse({processId:C,id:_.id,thought:F.thought})}catch(P){return Nh.error("Error in AI thought generation",P),this.evaluateThoughtResponse({processId:C,id:_.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(_.id)}}stopGeneratingThought(_){this.activeRemoteSessionIdByStepId.delete(_)}async callThoughtApi(_,g,C){let P=Date.now();if(g)try{P=Date.now();let F=await this.apiService.post(`${_}/thoughts/generate`,{sessionId:this.remoteSessionId,data:g});if(!F.ok){Nh.error(`Request for ${_} thought generation failed with status ${F.status}`);return}let M=await F.json();if(!(M!=null&&M.thought))throw Nh("No thought generated for action, got response",F),new Error("No thought generated");let V=_==="actions"?g.action:g.assertion;return Nh(`Thought generated (${C})`,{type:_,stepId:V.id,locator:V.locator,thought:M.thought}),M}catch(F){throw Nh.error(`Error in AI thought generation (${C})`,F),F}}isRunning(_){return this.activeRemoteSessionIdByStepId.has(_)}async evaluateThoughtResponse({id:_,processId:g,thought:C,error:P=!1}){try{await this.webDriver.page.evaluate(({id:F,thought:M,error:V,processId:W})=>{window.vtg.onAsyncProcessResponse({id:F,processId:W,thought:M,error:V})},{id:_,thought:C,error:P,processId:g})}catch(F){Nh.error("Error in AI thought generation",F)}}};e(Dnr,"VTGThoughtsService");var IRt=Dnr;var Cnr=class Cnr{constructor(l=new Utt){this._variableStore=l}get variableStore(){return this._variableStore}};e(Cnr,"VTGVariableStoreService");var ORt=Cnr;var _VtgEvaluatorService=class _VtgEvaluatorService{constructor(p,l){this.variableStoreService=p;this.vtgTestFileMode=l;this.listenerBody=e(async({vtg})=>{await vtg.eval(async(code,callback)=>{try{callback(null,await eval(`(async () => {
|
|
1948
1948
|
${code}
|
|
1949
1949
|
})()`))}catch(p){callback(p,null)}})},"listenerBody")}setPage(p){this.page=p}async execute(p,l={}){return this.vtgTestFileMode?this.executeInPlaywrightTest(p,l):this.executeOnLive(p,l)}get vtgContext(){return{page:this.page,vs:this.variableStoreService.variableStore,expect:IZe.expect,checksumAI:e((p,l)=>l(),"checksumAI")}}async executeOnLive(p,l={}){let _={...this.vtgContext,...l},g=this.wrapCodeInContext(p,_);return await(0,eval)(g)(_)}wrapCodeInContext(p,l){return`(async ({${Object.keys(l).join(", ")}}) => { ${p} })`}async executeInPlaywrightTest(p,l={}){let _=l?this.wrapCodeInContext(p,l)+"(context)":p;return new Promise((g,C)=>{this.listener&&this.listener(_,l,(P,F)=>{P?C(P):g(F)})})}async listenForExecution(p){return new Promise(l=>{this.resolveEvaluator=l,this.listener=p})}stopListening(){var p;(p=this.resolveEvaluator)==null||p.call(this)}getFunctionContentToInject(){return this.listenerBody.toString()}};e(_VtgEvaluatorService,"VtgEvaluatorService");var LRt=_VtgEvaluatorService;var knr=class knr extends DOt{constructor(_,g=!1){g||(g=!!_.find(C=>C==="--debug"));super(_,g);this.checksumScriptFilePath="node_modules/@checksum-ai/runtime/checksumlib.js";this.vtgMode="start";this.initTimeMachine=e(async()=>{await this.webDriver.tmFrame.evaluate(()=>window.checksum.visualTestGenerator.init(!1))},"initTimeMachine");this.initVtgMode(_),Nh.setLogLevel(g?"all":j4.isDevMode?j4.logLevel:"errors")}async run(_){await this.init(_),this.buildServices(),this.buildServer();let g=await this.getInitialServicesData();g&&this.setServicesData(g),await this.start()}async init(_){await this.patchPlaywright(),this.loadChecksumData(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(_),this.webDriver.registerEventListener(this),this.taskTimeMachine=new tPe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!j4.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:j4.vtg.taskTimeMachine.taskTimeout}),this.pageInteractor=new Mtt(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:Nh.info,logError:Nh.error},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new Btt(this.config)),this.testAssetsManager=new CRt(this.projectRootDirectory,this.checksumRoot,this.vtgTestFileRunConfig),(j4.vtg.writeLogFile||this.debugMode)&&this.addLogFile()}buildServices(){this.actionsManager=new tMt,this.apiService=new POt(this.config),this.userStoryService=new eMt(this.apiService,this.config),this.variableStoreService=new ORt,this.evaluatorService=new LRt(this.variableStoreService,this.vtgTestFileMode),this.actionsService=new kOt(this.config,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService),this.assertionsService=new qOt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new XOt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new AOt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new JOt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService),this.aiThoughtsService=new IRt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new ZLt(this.config,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService),this.settingsService=new NRt(this.checksumRoot),this.actionsManager.setStorageService(this.storageService)}buildServer(){this.reactAppServer=new TRt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService)}loadPlaywrightConfigForVTG(){try{let _=`${this.checksumRoot}/playwright.config.ts`;if((0,zwt.existsSync)(_)){let g=require(_).default;g&&(this.playwrightConfigForVTG=g)}}catch{console.warn("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){if(this.vtgMode==="cloud")return this.getInitialServicesDataFromCloud();if(this.vtgMode==="edit")return this.vtgTestFileMode?await this.getInitialServicesDataByInternalTestId():this.getInitialServicesDataFromEditLocationPath()}getInitialServicesDataFromEditLocationPath(){let _=this.storageService.getLocalSavedData(this.editLocationPath);return{actions:_.executedActions,story:_.story,testGenerationData:_.testGenerationData}}async getInitialServicesDataFromCloud(){let g=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:C,story:P,testGenerationData:F}=g,M=await fetch(C,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!M.ok)throw new Error(`HTTP error! Status: ${M.status}`);let V=await M.json();return{actions:this.addIdsToActionsAndAssertions(V),story:P,testGenerationData:F}}addIdsToActionsAndAssertions(_){return _.map((g,C)=>({...g,id:(0,Enr.randomUUID)(),assertions:(g.assertions??[]).map(P=>({...P,id:(0,Enr.randomUUID)()}))}))}async getInitialServicesDataByInternalTestId(){var P,F,M;if(((P=this.vtgTestFileRunConfig)==null?void 0:P.mode)!=="edit")return;let _=[];_=this.storageService.readJsonFile((F=this.vtgTestFileRunConfig)==null?void 0:F.actionsJsonFilePath),_=this.addIdsToActionsAndAssertions(_);let g=await this.apiService.post(`test-generation-by-internal-test-id/${(M=this.vtgTestFileRunConfig)==null?void 0:M.internalTestId}/info`);if(!g.ok)throw new Error(`Error fetching test generation data: ${g.statusText}`);let C=await g.json();return{actions:_,story:C.story,testGenerationData:C.testGenerationData}}setServicesData({actions:_,story:g,testGenerationData:C}){this.actionsManager.setActions(_),this.userStoryService.setStoryInfo(g,C),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=g.id}async start({createAssetsFolder:_=!0}={}){var P,F;(this.vtgMode==="start"||this.vtgTestFileMode)&&await this.userStoryService.fetchStory(this.storyId),_&&this.testAssetsManager.createTestGenerationAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(this.storyId);let{environment:g}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:g.baseURL,shutdown:!this.vtgTestFileMode}),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()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,M=>this.webDriver.registerTimeMachineFrame(M)),await this.reactAppServer.start(),await this.reactAppServer.evaluateServerPort(this.webDriver.page);let C=(()=>{let M=this.config.environments.find(V=>V.name===g.name);return!M||!M.baseURL?"/":M.baseURL})();this.webDriver.appMainFrame?await this.webDriver.appMainFrame.goto(C,{waitUntil:"domcontentloaded",timeout:0}):Nh.error("Iframe not found"),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),console.log("VTG is ready",(P=this.userStoryService.getStory())==null?void 0:P.goal),await this.webDriver.page.evaluate(({localSaveFolderPath:M,actions:V,appViewport:W,userStoryGoal:Q,isLoadedFromFile:se})=>{window.vtg.initClient(M,V,W,this.checksumRuntimeVersion,Q,se)},{localSaveFolderPath:this.editLocationPath,actions:this.actionsManager.actions,appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(F=this.userStoryService.getStory())==null?void 0:F.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var C,P,F,M;let _=((P=(C=this.playwrightConfigForVTG)==null?void 0:C.use)==null?void 0:P.navigationTimeout)||3e4,g=((M=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:M.actionTimeout)||5e3;return{navigationTimeout:_,actionTimeout:g}}getPlaywrightProxySettings(){var F,M;let _=(M=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:M.proxy,{server:g,username:C,password:P}=_||{};if(C&&P&&g)return{username:C,password:P,server:g}}getPlaywrightViewportSettings(){var C,P;let{width:_=1280,height:g=720}=((P=(C=this.playwrightConfigForVTG)==null?void 0:C.use)==null?void 0:P.viewport)||{};return{width:_,height:g}}buildWebDriver(_){var P;let g=this.getPlaywrightProxySettings(),C=this.getPlaywrightViewportSettings();return new ARt({scriptSource:j4.checksumScript.source,scriptURL:j4.checksumScript.url,scriptFile:j4.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(P=this.config.environments.find(F=>F.default))==null?void 0:P.baseURL,useProxy:!!g,webProxy:g,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:j4.vtg.remoteDebugging},{devtools:!1,headless:!1},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:C},_)}async onWebDriverContextClose(){var _,g,C;this.evaluatorService.stopListening(),(_=this.vtgTestFileRunConfig)!=null&&_.evalFilePath&&(0,zwt.rmSync)((g=this.vtgTestFileRunConfig)==null?void 0:g.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,zwt.rmSync)((C=this.vtgTestFileRunConfig)==null?void 0:C.actionsJsonFilePath,{force:!0})}initVtgMode(_){var P;let g=_.indexOf("--edit"),C=_.indexOf("--cloud");if(_.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=((P=this.vtgTestFileRunConfig)==null?void 0:P.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}g!==-1&&(this.vtgMode="edit",this.editLocationPath=_.at(g+1)),C!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=_.at(C+1)),this.vtgMode==="start"&&(this.storyId=_[0])}addLogFile(){let _=require("fs"),g=`${this.testAssetsManager.getLogsPath()}/vtg_${new Date().toISOString()}.log`;_.existsSync(this.testAssetsManager.getLogsPath())||_.mkdirSync(this.testAssetsManager.getLogsPath(),{recursive:!0}),Nh.addLogListener({onLog:e((...C)=>{let P=C.map(F=>{if(typeof F=="object")try{return JSON.stringify(F,null,2)}catch{}return String(F)}).join(" ")+`
|
|
1950
1950
|
`;try{_.appendFile(g,P,F=>{F&&console.error(F)})}catch{}},"onLog")})}async eval(_){return this.evaluatorService.listenForExecution(_)}};e(knr,"VisualTestGenerator");var MRt=knr;var wnr={},RRt=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,NAr=e((p,l,_={},g=!1)=>{let{runMode:C,environments:P}=l,F=p.extend({...RRt?{trace:"off",video:"off",screenshot:"off"}:{},permissions:e(async({},V,W)=>{if(!RRt)await V(W.project.use.permissions);else{let Q=new Set(W.project.use.permissions);Q.add("clipboard-read"),Q.add("clipboard-write"),await V(Array.from(Q))}},"permissions"),proxy:e(async({proxy:V},W)=>{V&&RRt?await W({...V,bypass:"127.0.0.1,localhost"}):await W(V)},"proxy"),launchOptions:e(async({launchOptions:V},W)=>{await W({...V,args:[...V.args??[],..._.useMockData?["--disable-web-security"]:[]]})},"launchOptions"),codeMirror:[async({},V)=>{let W=await cFt.init(C,{generateAssertionCode:e(()=>"","generateAssertionCode")});await V(W)},{scope:"worker"}],variableStore:e(async({},V)=>{let W=new Utt;await V(W)},"variableStore"),vs:e(async({variableStore:V},W)=>{await W(V)},"vs"),variablesStore:e(async({variableStore:V},W)=>{await W(V)},"variablesStore"),analytics:e(async({},V)=>{let W=Srt.getInstance({},j4.testRun.monitoring.segment,{logToConsole:l.options.printLogs}),Q=process.env.CHECKSUM_TEST_SUITE_ID;Q?await W.identify(Q,{},!0):W.setIsolatedMode(),await V(W)},"analytics"),monitorBridge:[async({},V,W)=>{let Q=new uFt(W);await V(Q)},{scope:"worker"}],page:e(async({page:V,codeMirror:W,monitorBridge:Q,variableStore:se,analytics:G},_e,ne)=>{let ue=await oFt.init(V,G,W,Q,se,ne,N9n(ne),F,l,g);Object.defineProperty(ue.constructor,"name",{value:"Page"}),await _e(ue),await ue.shutdown(),await ue.onTestComplete(ne.status==="passed")},"page"),vtg:e(async({page:V},W)=>{if(!RRt)W(null);else{let Q=new MRt(["--test-file"]);await Q.run(V),await W(Q)}},"vtg")}),M=P.find(V=>V.default);return F.use({baseURL:M.baseURL,bypassCSP:!0}),{test:F,defineChecksumTest:P9n}},"createChecksumTestExtension"),P9n=e((p,l)=>{let g=new Error().stack.split(`
|