@checksum-ai/runtime 2.0.24 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -601,7 +601,7 @@ ${r.format(i)}`.trim())}};e(L4r,"MockAgent");var R4r=L4r;xdn.exports=R4r});var j
601
601
  ${p}`;break;case"retry":E1n(p)&&(i[c]=p);break;case"id":C1n(p)&&(i[c]=p);break;case"event":p.length>0&&(i[c]=p);break}}processEvent(r){r.retry&&E1n(r.retry)&&(this.state.reconnectionTime=parseInt(r.retry,10)),r.id!==void 0&&C1n(r.id)&&(this.state.lastEventId=r.id),r.data!==void 0&&this.push({type:r.event||"message",options:{data:r.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event={data:void 0,event:void 0,id:void 0,retry:void 0}}};e(ASr,"EventSourceStream");var vSr=ASr;D1n.exports={EventSourceStream:vSr}});var B1n=Qr((iTa,N1n)=>{"use strict";var{pipeline:fPi}=require("stream"),{fetching:dPi}=dst(),{makeRequest:_Pi}=ije(),{webidl:h$}=qL(),{EventSourceStream:mPi}=S1n(),{parseMIMEType:hPi}=nre(),{createFastMessageEvent:gPi}=eIt(),{isNetworkError:w1n}=lst(),{kEnumerableProperty:LTe}=DA(),{environmentSettingsObject:T1n}=_Y(),k1n=!1,I1n=3e3,bst=0,F1n=1,Est=2,yPi="anonymous",vPi="use-credentials",tO,Cje,Cst,gre,MTe,Dst,Sst,C0e,r6e,xSr,bSr,mIt=class mIt extends EventTarget{constructor(i,s={}){super();wl(this,r6e);wl(this,tO,{open:null,error:null,message:null});wl(this,Cje);wl(this,Cst,!1);wl(this,gre,bst);wl(this,MTe,null);wl(this,Dst,null);wl(this,Sst);wl(this,C0e);h$.util.markAsUncloneable(this);let c="EventSource constructor";h$.argumentLengthCheck(arguments,1,c),k1n||(k1n=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),i=h$.converters.USVString(i),s=h$.converters.EventSourceInitDict(s,c,"eventSourceInitDict"),du(this,Sst,s.node.dispatcher||s.dispatcher),du(this,C0e,{lastEventId:"",reconnectionTime:s.node.reconnectionTime});let p=T1n,_;try{_=new URL(i,p.settingsObject.baseUrl),hr(this,C0e).origin=_.origin}catch(D){throw new DOMException(D,"SyntaxError")}du(this,Cje,_.href);let v=yPi;s.withCredentials===!0&&(v=vPi,du(this,Cst,!0));let E={redirect:"follow",keepalive:!0,mode:"cors",credentials:v==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};E.client=T1n.settingsObject,E.headersList=[["accept",{name:"accept",value:"text/event-stream"}]],E.cache="no-store",E.initiator="other",E.urlList=[new URL(hr(this,Cje))],du(this,MTe,_Pi(E)),gm(this,r6e,xSr).call(this)}get readyState(){return hr(this,gre)}get url(){return hr(this,Cje)}get withCredentials(){return hr(this,Cst)}close(){h$.brandCheck(this,mIt),hr(this,gre)!==Est&&(du(this,gre,Est),hr(this,Dst).abort(),du(this,MTe,null))}get onopen(){return hr(this,tO).open}set onopen(i){hr(this,tO).open&&this.removeEventListener("open",hr(this,tO).open);let s=h$.converters.EventHandlerNonNull(i);s!==null?(this.addEventListener("open",s),hr(this,tO).open=i):hr(this,tO).open=null}get onmessage(){return hr(this,tO).message}set onmessage(i){hr(this,tO).message&&this.removeEventListener("message",hr(this,tO).message);let s=h$.converters.EventHandlerNonNull(i);s!==null?(this.addEventListener("message",s),hr(this,tO).message=i):hr(this,tO).message=null}get onerror(){return hr(this,tO).error}set onerror(i){hr(this,tO).error&&this.removeEventListener("error",hr(this,tO).error);let s=h$.converters.EventHandlerNonNull(i);s!==null?(this.addEventListener("error",s),hr(this,tO).error=i):hr(this,tO).error=null}};tO=new WeakMap,Cje=new WeakMap,Cst=new WeakMap,gre=new WeakMap,MTe=new WeakMap,Dst=new WeakMap,Sst=new WeakMap,C0e=new WeakMap,r6e=new WeakSet,xSr=e(function(){if(hr(this,gre)===Est)return;du(this,gre,bst);let i={request:hr(this,MTe),dispatcher:hr(this,Sst)},s=e(c=>{if(!w1n(c))return gm(this,r6e,bSr).call(this)},"processEventSourceEndOfBody");i.processResponseEndOfBody=s,i.processResponse=c=>{if(w1n(c))if(c.aborted){this.close(),this.dispatchEvent(new Event("error"));return}else{gm(this,r6e,bSr).call(this);return}let p=c.headersList.get("content-type",!0),_=p!==null?hPi(p):"failure",v=_!=="failure"&&_.essence==="text/event-stream";if(c.status!==200||v===!1){this.close(),this.dispatchEvent(new Event("error"));return}du(this,gre,F1n),this.dispatchEvent(new Event("open")),hr(this,C0e).origin=c.urlList[c.urlList.length-1].origin;let E=new mPi({eventSourceSettings:hr(this,C0e),push:e(D=>{this.dispatchEvent(gPi(D.type,D.options))},"push")});fPi(c.body.stream,E,D=>{(D==null?void 0:D.aborted)===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},du(this,Dst,dPi(i))},"#connect"),bSr=e(function(){var i;hr(this,gre)!==Est&&(du(this,gre,bst),this.dispatchEvent(new Event("error")),(i=setTimeout(()=>{hr(this,gre)===bst&&(hr(this,C0e).lastEventId.length&&hr(this,MTe).headersList.set("last-event-id",hr(this,C0e).lastEventId,!0),gm(this,r6e,xSr).call(this))},hr(this,C0e).reconnectionTime))==null||i.unref())},"#reconnect"),e(mIt,"EventSource");var Dje=mIt,P1n={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:bst,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:F1n,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:Est,writable:!1}};Object.defineProperties(Dje,P1n);Object.defineProperties(Dje.prototype,P1n);Object.defineProperties(Dje.prototype,{close:LTe,onerror:LTe,onmessage:LTe,onopen:LTe,readyState:LTe,url:LTe,withCredentials:LTe});h$.converters.EventSourceInitDict=h$.dictionaryConverter([{key:"withCredentials",converter:h$.converters.boolean,defaultValue:e(()=>!1,"defaultValue")},{key:"dispatcher",converter:h$.converters.any},{key:"node",converter:h$.dictionaryConverter([{key:"reconnectionTime",converter:h$.converters["unsigned long"],defaultValue:e(()=>I1n,"defaultValue")},{key:"dispatcher",converter:h$.converters.any}]),defaultValue:e(()=>({}),"defaultValue")}]);N1n.exports={EventSource:Dje,defaultReconnectionTime:I1n}});var U1n=Qr((sTa,K1)=>{"use strict";var APi=CCe(),R1n=oMe(),xPi=eTe(),bPi=rfn(),EPi=sfn(),CPi=nTe(),DPi=s7r(),SPi=A7r(),wPi=d7r(),TPi=Gfn(),kPi=t0n(),IPi=i0n(),L1n=nA(),gIt=DA(),{InvalidArgumentError:hIt}=L1n,Sje=L0n(),FPi=zwe(),PPi=b4r(),{MockCallHistory:NPi,MockCallHistoryLog:BPi}=w4r(),OPi=M4r(),RPi=P4r(),LPi=qdn(),MPi=r4r(),jPi=e9t(),{getGlobalDispatcher:M1n,setGlobalDispatcher:UPi}=h9t(),QPi=LMe(),qPi=Y4r();Object.assign(R1n.prototype,Sje);K1.exports.Dispatcher=R1n;K1.exports.Client=APi;K1.exports.Pool=xPi;K1.exports.BalancedPool=bPi;K1.exports.RoundRobinPool=EPi;K1.exports.Agent=CPi;K1.exports.Dispatcher1Wrapper=DPi;K1.exports.ProxyAgent=SPi;K1.exports.Socks5ProxyAgent=wPi;K1.exports.EnvHttpProxyAgent=TPi;K1.exports.RetryAgent=kPi;K1.exports.H2CClient=IPi;K1.exports.RetryHandler=jPi;K1.exports.DecoratorHandler=QPi;K1.exports.RedirectHandler=qPi;K1.exports.interceptors={redirect:e_n(),responseError:r_n(),retry:i_n(),dump:o_n(),dns:d_n(),cache:P_n(),decompress:Q_n(),deduplicate:W_n()};K1.exports.cacheStores={MemoryCacheStore:_Dr()};var $Pi=X_n();K1.exports.cacheStores.SqliteCacheStore=$Pi;K1.exports.buildConnector=FPi;K1.exports.errors=L1n;K1.exports.util={parseHeaders:gIt.parseHeaders,headerNameToString:gIt.headerNameToString};function wst(n){return(r,i,s)=>{if(typeof i=="function"&&(s=i,i=null),!r||typeof r!="string"&&typeof r!="object"&&!(r instanceof URL))throw new hIt("invalid url");if(i!=null&&typeof i!="object")throw new hIt("invalid opts");if(i&&i.path!=null){if(typeof i.path!="string")throw new hIt("invalid opts.path");let _=i.path;i.path.startsWith("/")||(_=`/${_}`),r=new URL(gIt.parseOrigin(r).origin+_)}else i||(i=typeof r=="object"?r:{}),r=gIt.parseURL(r);let{agent:c,dispatcher:p=M1n()}=i;if(c)throw new hIt("unsupported opts.agent. Did you mean opts.client?");return n.call(p,{...i,origin:r.origin,path:r.search?`${r.pathname}${r.search}`:r.pathname,method:i.method||(i.body?"PUT":"GET")},s)}}e(wst,"makeDispatcher");K1.exports.setGlobalDispatcher=UPi;K1.exports.getGlobalDispatcher=M1n;var VPi=dst().fetch,O1n=typeof __filename<"u"?__filename:void 0;function j1n(n,r){if(!n||typeof n!="object")return;let i=typeof n.stack=="string"?n.stack:"",s=r.replace(/\\/g,"/");if(i&&(i.includes(r)||i.includes(s)))return;let c={};if(Error.captureStackTrace(c,j1n),!c.stack)return;let p=c.stack.split(`
602
602
  `).slice(1).join(`
603
603
  `);n.stack=i?`${i}
604
- ${p}`:c.stack}e(j1n,"appendFetchStackTrace");K1.exports.fetch=e(function(r,i=void 0){return VPi(r,i).catch(s=>{throw O1n?j1n(s,O1n):s&&typeof s=="object"&&Error.captureStackTrace(s,K1.exports.fetch),s})},"fetch");K1.exports.Headers=bTe().Headers;K1.exports.Response=lst().Response;K1.exports.Request=ije().Request;K1.exports.FormData=Dkt().FormData;var{setGlobalOrigin:JPi,getGlobalOrigin:zPi}=RCr();K1.exports.setGlobalOrigin=JPi;K1.exports.getGlobalOrigin=zPi;var{CacheStorage:HPi}=uhn(),{kConstruct:WPi}=B4();K1.exports.caches=new HPi(WPi);var{deleteCookie:GPi,getCookies:KPi,getSetCookies:YPi,setCookie:XPi,parseCookie:ZPi}=bhn();K1.exports.deleteCookie=GPi;K1.exports.getCookies=KPi;K1.exports.getSetCookies=YPi;K1.exports.setCookie=XPi;K1.exports.parseCookie=ZPi;var{parseMIMEType:eNi,serializeAMimeType:tNi}=nre();K1.exports.parseMIMEType=eNi;K1.exports.serializeAMimeType=tNi;var{CloseEvent:rNi,ErrorEvent:nNi,MessageEvent:iNi}=eIt(),{WebSocket:aNi,ping:sNi}=o1n();K1.exports.WebSocket=aNi;K1.exports.CloseEvent=rNi;K1.exports.ErrorEvent=nNi;K1.exports.MessageEvent=iNi;K1.exports.ping=sNi;K1.exports.WebSocketStream=A1n().WebSocketStream;K1.exports.WebSocketError=fSr().WebSocketError;K1.exports.request=wst(Sje.request);K1.exports.stream=wst(Sje.stream);K1.exports.pipeline=wst(Sje.pipeline);K1.exports.connect=wst(Sje.connect);K1.exports.upgrade=wst(Sje.upgrade);K1.exports.MockClient=PPi;K1.exports.MockCallHistory=NPi;K1.exports.MockCallHistoryLog=BPi;K1.exports.MockPool=RPi;K1.exports.MockAgent=OPi;K1.exports.SnapshotAgent=LPi;K1.exports.mockErrors=MPi;var{EventSource:oNi}=B1n();K1.exports.EventSource=oNi;function cNi(){globalThis.fetch=K1.exports.fetch,globalThis.Headers=K1.exports.Headers,globalThis.Response=K1.exports.Response,globalThis.Request=K1.exports.Request,globalThis.FormData=K1.exports.FormData,globalThis.WebSocket=K1.exports.WebSocket,globalThis.CloseEvent=K1.exports.CloseEvent,globalThis.ErrorEvent=K1.exports.ErrorEvent,globalThis.MessageEvent=K1.exports.MessageEvent,globalThis.EventSource=K1.exports.EventSource}e(cNi,"install");K1.exports.install=cNi});var Tst,ESr,kst,Q1n=Ws(()=>{"use strict";g6();Tst=require("perf_hooks"),ESr=class ESr{constructor(r={}){this.options=r;this.priorityQueue=[];this.nonPriorityQueue=[];this.isRunning=!1;this.taskIndex=0;this.timeRunningTasks=0;this.timeGoingBack=0;this.tasksExecuted=0}enqueue(r){let i=this.taskIndex++,s={...r,index:i,queuedAt:Tst.performance.now()};if(r.priority)this.priorityQueue.push(s);else if(this.options.sortByTimestamp){let c=this.nonPriorityQueue.findIndex(p=>p.timestamp>r.timestamp);c===-1?this.nonPriorityQueue.push(s):this.nonPriorityQueue.splice(c,0,s)}else this.nonPriorityQueue.push(s);return i}popTask(){return this.priorityQueue.length>0?this.priorityQueue.shift():this.nonPriorityQueue.shift()}async runTasks(r){if(!this.isRunning){this.isRunning=!0;try{for(;this.getQueueLength()>0;){let i=this.popTask();if(!i)break;let s=Tst.performance.now();try{if(this.options.logPerformance){let p=Tst.performance.now()-i.queuedAt;Yp.info(`Running task, timestamp: ${i.timestamp} \x1B[36m${i.name}\x1B[0m, index: ${i.index}, was pending for ${p}ms`)}await r(i);let c=Tst.performance.now()-s;this.timeRunningTasks+=c,this.options.logPerformance&&Yp.info("Finished running task, took",c,"ms.","Queue lengths:",`priority=${this.priorityQueue.length}`,`non-priority=${this.nonPriorityQueue.length}`),this.tasksExecuted++}catch(c){Yp.error("Task execution error:",c)}}}finally{this.isRunning=!1,this.getQueueLength()>0&&this.options.logPerformance&&Yp.info("Accumulated time running tasks:",this.timeRunningTasks,"ms, from which time spent going back:",this.timeGoingBack)}}}getTasksAtTimestamp(r){return[...this.priorityQueue.filter(i=>i.timestamp===r),...this.nonPriorityQueue.filter(i=>i.timestamp===r)]}removeTasksAtTimestamp(r){this.priorityQueue=this.priorityQueue.filter(i=>i.timestamp!==r),this.nonPriorityQueue=this.nonPriorityQueue.filter(i=>i.timestamp!==r)}getQueueLength(){return this.priorityQueue.length+this.nonPriorityQueue.length}setTimeGoingBack(r){this.timeGoingBack=r}};e(ESr,"TaskTimeMachineQueue");kst=ESr});var q1n,Fst,Ist,CSr,Fge,yIt=Ws(()=>{"use strict";q1n=require("@playwright/test");Qcn();iS();g6();BRe();Fst=H0(U1n());Q1n();Ist=require("perf_hooks"),CSr=class CSr{constructor(r,i,s={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0}){this.frameMsgBroker=r;this.injectedScriptManager=i;this.options=s;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.currentChecksumId="0";this.timeGoingBack=0;this.pagesWithCorsInterception=new Set;this.reducedHTMLCache={};this.getReducedHTMLWithRetries=e(async(r,{retriesLeft:i=3,retryWaitMS:s=1e3}={})=>{try{let{reducedHTML:c,currentChecksumId:p}=await r.evaluate(async _=>{var v,E;return(E=(v=window==null?void 0:window.checksum)==null?void 0:v.testGenerator)==null?void 0:E.reduceHTML({},_)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0});return this.currentChecksumId=p,{reducedHTML:c}}catch(c){if(i>0)return await lb(s),this.getReducedHTMLWithRetries(r,{retriesLeft:i-1,retryWaitMS:s});throw c}},"getReducedHTMLWithRetries");if(this.taskQueue=new kst({sortByTimestamp:s.sortByTimestamp,logPerformance:s.logPerformance}),s.webProxy){let{username:c,password:p,server:_}=s.webProxy;c&&p?this.webProxyAgent=new Fst.ProxyAgent({uri:`http://${c}:${p}@${_.replace("http://","")}`}):this.webProxyAgent=new Fst.ProxyAgent({uri:_})}}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(r,i,s){this.recordingFrame=r,await this.frameMsgBroker.register("live",r),i?this.timeMachineFrame=i:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),await this.preventCrossOriginErrors(this.timeMachineFrame),this.options.frameMsgBrokerRegisterName&&await this.frameMsgBroker.register(this.options.frameMsgBrokerRegisterName,this.timeMachineFrame),s&&s(this.timeMachineFrame),await this.injectedScriptManager.addTrackedFrame(this.timeMachineFrame),this.timeMachineFrame.page().on("framenavigated",async c=>{await this.injectedScriptManager.onFrameNavigated(c)}),this.subscribeToRrwebEvents(),this.taskQueue=new kst({sortByTimestamp:this.options.sortByTimestamp,logPerformance:this.options.logPerformance}),await this.start()}async preventCrossOriginErrors(r){try{let i=r.page(),s=nw(i);if(this.pagesWithCorsInterception.has(s))return;this.pagesWithCorsInterception.add(s),await i.route(/^https?:\/\/(?!(?:localhost|127\.0\.0\.1|::1)).*/,async(c,p)=>{var E;let v=c.request().url();try{let D=this.webProxyAgent?{dispatcher:this.webProxyAgent}:{},w=await(0,Fst.fetch)(v,D),B=w.status,N={};w.headers.forEach((le,de)=>N[de]=le),N["access-control-allow-origin"]="*";let L=parseInt(w.headers.get("content-length")||"0",10),M=25*1024*1024;if(L>M)return c.continue();if(!w.body){await c.fulfill({status:B,headers:N});return}let Z=await w.arrayBuffer(),ue=Buffer.from(Z);await c.fulfill({status:B,headers:N,body:ue})}catch(D){return(E=D.cause)==null||E.code,c.continue()}})}catch{}}async start(){await this.timeMachineFrame.evaluate(async()=>{window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})})}setBrowserContext(r){this.timeMachineBrowserContext=r}async executeTask(r,i=void 0,{name:s,beforeTimestamp:c=!1,priority:p=!1}={}){return new Promise((_,v)=>{let E=e(async({shouldGoBack:D,shouldBatch:w}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{if(this.timeMachineFrame.isDetached()&&v(),D){let L=Ist.performance.now();await this.goBack(i,c),this.timeGoingBack+=Ist.performance.now()-L,this.taskQueue.setTimeGoingBack(this.timeGoingBack)}let B=e(L=>async()=>{try{let M=Ist.performance.now(),V=await WS(L(this.timeMachineFrame),this.options.taskTimeout,()=>`Task execution timeout - ${s}, took ${Ist.performance.now()-M}ms with timeout of ${this.options.taskTimeout}ms`);_(V)}catch(M){Yp.error("Task execution error:",M.message),v(M)}},"makeSafeRunTask"),N=[B(r)];if(this.taskQueue.getQueueLength()>0&&w){let L=this.taskQueue.getTasksAtTimestamp(i);N.push(...L.map(({task:M})=>B(()=>M({shouldGoBack:!1,shouldBatch:!1})))),this.taskQueue.removeTasksAtTimestamp(i),N.length&&console.log(`Batching to task "${s}" ${N.length-1} more tasks`)}for(let L of N)await L()},"taskWrapper");this.taskQueue.enqueue({name:s,task:E,timestamp:c?i-1:i,priority:p}),this.runTasks()})}executeReducedHTMLTask(r,{priority:i=!1}={}){if(this.reducedHTMLCache[r]){let s=new qit(this.reducedHTMLCache[r]);return Promise.resolve(s.getRrwebIdsReducedDomString())}return this.executeTask(async s=>{let c="",p=await this.getReducedHTMLWithRetries(s);return c=p==null?void 0:p.reducedHTML,c&&(this.reducedHTMLCache[r]=c),new qit(c).getRrwebIdsReducedDomString()},r,{name:"getReducedHTMLForTimestamp",priority:i})}goBack(r,i=!1){return this.currentBeforeTimestamp===i&&this.currentTimestamp===r?Promise.resolve():(this.currentTimestamp=r,this.currentBeforeTimestamp=i,this.timeMachineFrame.evaluate(({timestamp:s,beforeTimestamp:c})=>s===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(s,{beforeTimestamp:c}),{timestamp:r,beforeTimestamp:i}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}async runTasks(){await this.taskQueue.runTasks(async r=>{await r.task()})}async rrwebEventHandler(r){let i=JSON.stringify(r);try{await this.timeMachineFrame.evaluate(function(s){let c=JSON.parse(s);return window.checksum.timeMachine.handleEvents(c)},i)}catch{}return r=null,i}async makeBrowserContext(){let r=[];this.options.debugPort&&r.push(`--remote-debugging-port=${this.options.debugPort}`);let i=await q1n.chromium.launch({devtools:!1,headless:this.options.headless,args:r});return this.timeMachineBrowserContext=await i.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}subscribeToRrwebEvents(){let r="rrweb";this.frameMsgBroker.subscribeToChannel(r,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler.bind(this)}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(r,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(r){try{await this.timeMachineFrame.evaluate(i=>window.checksum.timeMachine.setShouldHandleEvents(i),r)}catch{}}};e(CSr,"ChecksumTimeMachine");Fge=CSr});var DSr,Pst,$1n,V1n,J1n,z1n,uNi,SSr,vIt,H1n=Ws(()=>{"use strict";yIt();DSr=require("@playwright/test"),Pst=H0(require("fs")),$1n=H0(require("fs/promises")),V1n=H0(require("readline")),J1n=H0(require("path")),z1n=H0(B8t());xU();aw();uNi=1e3,SSr=class SSr extends Fge{constructor(i,s,c={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0,recordRRwebEventsToFile:!1,recordRRwebEventsToFilePath:"events.json"}){super(i,s,c);this.options=c;this.rrwebEventsBuffer="";this.didPostProcessRRwebEvents=!1;this.postProcessRRwebEvents=(0,z1n.debounce)(async()=>{return;try{let s=Pst.default.createReadStream(this.options.recordRRwebEventsToFilePath),c=V1n.default.createInterface({input:s,crlfDelay:1/0});for await(let p of c)if(p.trim()!=="")try{let _=JSON.parse(p);Array.isArray(_)?i.push(..._):i.push(_)}catch(_){mv(`Failed to parse line: ${p}`,_)}Pst.default.writeFileSync(this.options.recordRRwebEventsToFilePath.replace(/([^\/]+)$/,"postprocessed.$1"),JSON.stringify(i)),this.didPostProcessRRwebEvents=!0}catch(s){mv("Error post-processing RRweb events",s)}},100,{leading:!0,trailing:!0});if(this.options.recordRRwebEventsToFile){let p=this.options.recordRRwebEventsToFilePath,_=J1n.default.dirname(p);Pst.default.mkdirSync(_,{recursive:!0}),Pst.default.writeFileSync(p,"")}}setTimeMachineBrowserContext(i){this.timeMachineBrowserContext=i}getTimeMachineBrowserContext(){return this.timeMachineBrowserContext}async makeBrowserContext(){DSr.chromium._checksumInternal=!0;let i=await DSr.chromium.launch({devtools:!1,headless:this.options.headless,args:Hd.useRemoteDebugging.enabled?["--remote-debugging-port=4444"]:[]});return i._checksumInternal=!0,this.timeMachineBrowserContext=await i.newContext({bypassCSP:!0}),this.timeMachineBrowserContext._checksumInternal=!0,this.timeMachineBrowserContext.tracing.startChunk=async()=>{},this.timeMachineBrowserContext.tracing.stop(),this.timeMachineBrowserContext.tracing.stop=async()=>{},this.timeMachineBrowserContext.tracing.stopChunk=async()=>{},this.timeMachineBrowserContext}async makeFrame(){let i=await this.timeMachineBrowserContext.newPage();i._checksumInternal=!0;let s=i.mainFrame();return s._checksumInternal=!0,s}async rrwebEventHandler(i){let s=await super.rrwebEventHandler(i);if(this.options.recordRRwebEventsToFile){if(this.rrwebEventsBuffer+=s+`
604
+ ${p}`:c.stack}e(j1n,"appendFetchStackTrace");K1.exports.fetch=e(function(r,i=void 0){return VPi(r,i).catch(s=>{throw O1n?j1n(s,O1n):s&&typeof s=="object"&&Error.captureStackTrace(s,K1.exports.fetch),s})},"fetch");K1.exports.Headers=bTe().Headers;K1.exports.Response=lst().Response;K1.exports.Request=ije().Request;K1.exports.FormData=Dkt().FormData;var{setGlobalOrigin:JPi,getGlobalOrigin:zPi}=RCr();K1.exports.setGlobalOrigin=JPi;K1.exports.getGlobalOrigin=zPi;var{CacheStorage:HPi}=uhn(),{kConstruct:WPi}=B4();K1.exports.caches=new HPi(WPi);var{deleteCookie:GPi,getCookies:KPi,getSetCookies:YPi,setCookie:XPi,parseCookie:ZPi}=bhn();K1.exports.deleteCookie=GPi;K1.exports.getCookies=KPi;K1.exports.getSetCookies=YPi;K1.exports.setCookie=XPi;K1.exports.parseCookie=ZPi;var{parseMIMEType:eNi,serializeAMimeType:tNi}=nre();K1.exports.parseMIMEType=eNi;K1.exports.serializeAMimeType=tNi;var{CloseEvent:rNi,ErrorEvent:nNi,MessageEvent:iNi}=eIt(),{WebSocket:aNi,ping:sNi}=o1n();K1.exports.WebSocket=aNi;K1.exports.CloseEvent=rNi;K1.exports.ErrorEvent=nNi;K1.exports.MessageEvent=iNi;K1.exports.ping=sNi;K1.exports.WebSocketStream=A1n().WebSocketStream;K1.exports.WebSocketError=fSr().WebSocketError;K1.exports.request=wst(Sje.request);K1.exports.stream=wst(Sje.stream);K1.exports.pipeline=wst(Sje.pipeline);K1.exports.connect=wst(Sje.connect);K1.exports.upgrade=wst(Sje.upgrade);K1.exports.MockClient=PPi;K1.exports.MockCallHistory=NPi;K1.exports.MockCallHistoryLog=BPi;K1.exports.MockPool=RPi;K1.exports.MockAgent=OPi;K1.exports.SnapshotAgent=LPi;K1.exports.mockErrors=MPi;var{EventSource:oNi}=B1n();K1.exports.EventSource=oNi;function cNi(){globalThis.fetch=K1.exports.fetch,globalThis.Headers=K1.exports.Headers,globalThis.Response=K1.exports.Response,globalThis.Request=K1.exports.Request,globalThis.FormData=K1.exports.FormData,globalThis.WebSocket=K1.exports.WebSocket,globalThis.CloseEvent=K1.exports.CloseEvent,globalThis.ErrorEvent=K1.exports.ErrorEvent,globalThis.MessageEvent=K1.exports.MessageEvent,globalThis.EventSource=K1.exports.EventSource}e(cNi,"install");K1.exports.install=cNi});var Tst,ESr,kst,Q1n=Ws(()=>{"use strict";g6();Tst=require("perf_hooks"),ESr=class ESr{constructor(r={}){this.options=r;this.priorityQueue=[];this.nonPriorityQueue=[];this.isRunning=!1;this.taskIndex=0;this.timeRunningTasks=0;this.timeGoingBack=0;this.tasksExecuted=0}enqueue(r){let i=this.taskIndex++,s={...r,index:i,queuedAt:Tst.performance.now()};if(r.priority)this.priorityQueue.push(s);else if(this.options.sortByTimestamp){let c=this.nonPriorityQueue.findIndex(p=>p.timestamp>r.timestamp);c===-1?this.nonPriorityQueue.push(s):this.nonPriorityQueue.splice(c,0,s)}else this.nonPriorityQueue.push(s);return i}popTask(){return this.priorityQueue.length>0?this.priorityQueue.shift():this.nonPriorityQueue.shift()}async runTasks(r){if(!this.isRunning){this.isRunning=!0;try{for(;this.getQueueLength()>0;){let i=this.popTask();if(!i)break;let s=Tst.performance.now();try{if(this.options.logPerformance){let p=Tst.performance.now()-i.queuedAt;Yp.info(`Running task, timestamp: ${i.timestamp} \x1B[36m${i.name}\x1B[0m, index: ${i.index}, was pending for ${p}ms`)}await r(i);let c=Tst.performance.now()-s;this.timeRunningTasks+=c,this.options.logPerformance&&Yp.info("Finished running task, took",c,"ms.","Queue lengths:",`priority=${this.priorityQueue.length}`,`non-priority=${this.nonPriorityQueue.length}`),this.tasksExecuted++}catch(c){Yp.error("Task execution error:",c)}}}finally{this.isRunning=!1,this.getQueueLength()>0&&this.options.logPerformance&&Yp.info("Accumulated time running tasks:",this.timeRunningTasks,"ms, from which time spent going back:",this.timeGoingBack)}}}getTasksAtTimestamp(r){return[...this.priorityQueue.filter(i=>i.timestamp===r),...this.nonPriorityQueue.filter(i=>i.timestamp===r)]}removeTasksAtTimestamp(r){this.priorityQueue=this.priorityQueue.filter(i=>i.timestamp!==r),this.nonPriorityQueue=this.nonPriorityQueue.filter(i=>i.timestamp!==r)}getQueueLength(){return this.priorityQueue.length+this.nonPriorityQueue.length}setTimeGoingBack(r){this.timeGoingBack=r}};e(ESr,"TaskTimeMachineQueue");kst=ESr});var q1n,Fst,Ist,CSr,Fge,yIt=Ws(()=>{"use strict";q1n=require("@playwright/test");Qcn();iS();g6();BRe();Fst=H0(U1n());Q1n();Ist=require("perf_hooks"),CSr=class CSr{constructor(r,i,s={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0}){this.frameMsgBroker=r;this.injectedScriptManager=i;this.options=s;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.currentChecksumId="0";this.timeGoingBack=0;this.pagesWithCorsInterception=new Set;this.reducedHTMLCache={};this.getReducedHTMLWithRetries=e(async(r,{retriesLeft:i=3,retryWaitMS:s=1e3}={})=>{try{let{reducedHTML:c,currentChecksumId:p}=await r.evaluate(async _=>{var v,E;return(E=(v=window==null?void 0:window.checksum)==null?void 0:v.testGenerator)==null?void 0:E.reduceHTML({},_)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0});return this.currentChecksumId=p,{reducedHTML:c}}catch(c){if(i>0)return await lb(s),this.getReducedHTMLWithRetries(r,{retriesLeft:i-1,retryWaitMS:s});throw c}},"getReducedHTMLWithRetries");if(this.taskQueue=new kst({sortByTimestamp:s.sortByTimestamp,logPerformance:s.logPerformance}),s.webProxy){let{username:c,password:p,server:_}=s.webProxy;c&&p?this.webProxyAgent=new Fst.ProxyAgent({uri:`http://${c}:${p}@${_.replace("http://","")}`}):this.webProxyAgent=new Fst.ProxyAgent({uri:_})}}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(r,i,s){this.recordingFrame=r,await this.frameMsgBroker.register("live",r),i?this.timeMachineFrame=i:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),await this.preventCrossOriginErrors(this.timeMachineFrame),this.options.frameMsgBrokerRegisterName&&await this.frameMsgBroker.register(this.options.frameMsgBrokerRegisterName,this.timeMachineFrame),s&&s(this.timeMachineFrame),await this.injectedScriptManager.addTrackedFrame(this.timeMachineFrame),this.timeMachineFrame.page().on("framenavigated",async c=>{await this.injectedScriptManager.onFrameNavigated(c)}),this.subscribeToRrwebEvents(),this.taskQueue=new kst({sortByTimestamp:this.options.sortByTimestamp,logPerformance:this.options.logPerformance}),await this.start()}async preventCrossOriginErrors(r){try{let i=r.page(),s=nw(i);if(this.pagesWithCorsInterception.has(s))return;this.pagesWithCorsInterception.add(s),await i.route(/^https?:\/\/(?!(?:localhost|127\.0\.0\.1|::1)).*/,async(c,p)=>{var E;let v=c.request().url();try{let D=this.webProxyAgent?{dispatcher:this.webProxyAgent}:{},w=await(0,Fst.fetch)(v,D),B=w.status,N={};w.headers.forEach((le,de)=>N[de]=le),N["access-control-allow-origin"]="*";let L=parseInt(w.headers.get("content-length")||"0",10),M=25*1024*1024;if(L>M)return c.continue();if(!w.body){await c.fulfill({status:B,headers:N});return}let Z=await w.arrayBuffer(),ue=Buffer.from(Z);await c.fulfill({status:B,headers:N,body:ue})}catch(D){return(E=D.cause)==null||E.code,c.continue()}})}catch{}}async start(){await this.timeMachineFrame.evaluate(async()=>{window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})})}setBrowserContext(r){this.timeMachineBrowserContext=r}async executeTask(r,i=void 0,{name:s,beforeTimestamp:c=!1,priority:p=!1}={}){return new Promise((_,v)=>{let E=e(async({shouldGoBack:D,shouldBatch:w}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{if(this.timeMachineFrame.isDetached()&&v(),D){let L=Ist.performance.now();await this.goBack(i,c),this.timeGoingBack+=Ist.performance.now()-L,this.taskQueue.setTimeGoingBack(this.timeGoingBack)}let B=e(L=>async()=>{try{let M=Ist.performance.now(),V=await WS(L(this.timeMachineFrame),this.options.taskTimeout,()=>`Task execution timeout - ${s}, took ${Ist.performance.now()-M}ms with timeout of ${this.options.taskTimeout}ms`);_(V)}catch(M){Yp.error("Task execution error:",M.message),v(M)}},"makeSafeRunTask"),N=[B(r)];if(this.taskQueue.getQueueLength()>0&&w){let L=this.taskQueue.getTasksAtTimestamp(i);N.push(...L.map(({task:M})=>B(()=>M({shouldGoBack:!1,shouldBatch:!1})))),this.taskQueue.removeTasksAtTimestamp(i),N.length&&console.log(`Batching to task "${s}" ${N.length-1} more tasks`)}for(let L of N)await L()},"taskWrapper");this.taskQueue.enqueue({name:s,task:E,timestamp:c?i-1:i,priority:p}),this.runTasks()})}executeReducedHTMLTask(r,{priority:i=!1}={}){if(this.reducedHTMLCache[r]){let s=new qit(this.reducedHTMLCache[r]);return Promise.resolve(s.getRrwebIdsReducedDomString())}return this.executeTask(async s=>{let c="",p=await this.getReducedHTMLWithRetries(s);return c=p==null?void 0:p.reducedHTML,c&&(this.reducedHTMLCache[r]=c),new qit(c).getRrwebIdsReducedDomString()},r,{name:"getReducedHTMLForTimestamp",priority:i})}goBack(r,i=!1){return this.currentBeforeTimestamp===i&&this.currentTimestamp===r?Promise.resolve():(this.currentTimestamp=r,this.currentBeforeTimestamp=i,this.timeMachineFrame.evaluate(({timestamp:s,beforeTimestamp:c})=>s===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(s,{beforeTimestamp:c}),{timestamp:r,beforeTimestamp:i}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}async runTasks(){await this.taskQueue.runTasks(async r=>{await r.task()})}async rrwebEventHandler(r){let i=JSON.stringify(r);try{await this.timeMachineFrame.evaluate(function(s){let c=JSON.parse(s);return window.checksum.timeMachine.handleEvents(c)},i)}catch{}return r=null,i}async makeBrowserContext(){let r=[];this.options.debugPort&&r.push(`--remote-debugging-port=${this.options.debugPort}`);let i=await q1n.chromium.launch({headless:this.options.headless,args:r});return this.timeMachineBrowserContext=await i.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}subscribeToRrwebEvents(){let r="rrweb";this.frameMsgBroker.subscribeToChannel(r,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler.bind(this)}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(r,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(r){try{await this.timeMachineFrame.evaluate(i=>window.checksum.timeMachine.setShouldHandleEvents(i),r)}catch{}}};e(CSr,"ChecksumTimeMachine");Fge=CSr});var DSr,Pst,$1n,V1n,J1n,z1n,uNi,SSr,vIt,H1n=Ws(()=>{"use strict";yIt();DSr=require("@playwright/test"),Pst=H0(require("fs")),$1n=H0(require("fs/promises")),V1n=H0(require("readline")),J1n=H0(require("path")),z1n=H0(B8t());xU();aw();uNi=1e3,SSr=class SSr extends Fge{constructor(i,s,c={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0,recordRRwebEventsToFile:!1,recordRRwebEventsToFilePath:"events.json"}){super(i,s,c);this.options=c;this.rrwebEventsBuffer="";this.didPostProcessRRwebEvents=!1;this.postProcessRRwebEvents=(0,z1n.debounce)(async()=>{return;try{let s=Pst.default.createReadStream(this.options.recordRRwebEventsToFilePath),c=V1n.default.createInterface({input:s,crlfDelay:1/0});for await(let p of c)if(p.trim()!=="")try{let _=JSON.parse(p);Array.isArray(_)?i.push(..._):i.push(_)}catch(_){mv(`Failed to parse line: ${p}`,_)}Pst.default.writeFileSync(this.options.recordRRwebEventsToFilePath.replace(/([^\/]+)$/,"postprocessed.$1"),JSON.stringify(i)),this.didPostProcessRRwebEvents=!0}catch(s){mv("Error post-processing RRweb events",s)}},100,{leading:!0,trailing:!0});if(this.options.recordRRwebEventsToFile){let p=this.options.recordRRwebEventsToFilePath,_=J1n.default.dirname(p);Pst.default.mkdirSync(_,{recursive:!0}),Pst.default.writeFileSync(p,"")}}setTimeMachineBrowserContext(i){this.timeMachineBrowserContext=i}getTimeMachineBrowserContext(){return this.timeMachineBrowserContext}async makeBrowserContext(){DSr.chromium._checksumInternal=!0;let i=await DSr.chromium.launch({headless:this.options.headless,args:Hd.useRemoteDebugging.enabled?["--remote-debugging-port=4444"]:[]});return i._checksumInternal=!0,this.timeMachineBrowserContext=await i.newContext({bypassCSP:!0}),this.timeMachineBrowserContext._checksumInternal=!0,this.timeMachineBrowserContext.tracing.startChunk=async()=>{},this.timeMachineBrowserContext.tracing.stop(),this.timeMachineBrowserContext.tracing.stop=async()=>{},this.timeMachineBrowserContext.tracing.stopChunk=async()=>{},this.timeMachineBrowserContext}async makeFrame(){let i=await this.timeMachineBrowserContext.newPage();i._checksumInternal=!0;let s=i.mainFrame();return s._checksumInternal=!0,s}async rrwebEventHandler(i){let s=await super.rrwebEventHandler(i);if(this.options.recordRRwebEventsToFile){if(this.rrwebEventsBuffer+=s+`
605
605
  `,this.rrwebEventsBuffer.length>uNi){let c=this.rrwebEventsBuffer;this.rrwebEventsBuffer="",this.flushRRwebEventsToFile(c)}return s}}async flushRRwebEventsToFile(i){if(this.options.recordRRwebEventsToFile){i??(i=this.rrwebEventsBuffer);try{await $1n.default.appendFile(this.options.recordRRwebEventsToFilePath,i)}catch(s){mv(s)}}}getRRwebFilePath(){return this.options.recordRRwebEventsToFilePath}};e(SSr,"RuntimeTimeMachine");vIt=SSr});var W1n,TSr,wje,wSr,kSr=Ws(()=>{"use strict";iS();fH();xU();W1n=!1,TSr=class TSr{constructor(r,i,s){this.frame=r;this.base=i;this.getAnalytics=s;this.LOCATORS_TIMEOUT=W1n?9999999:5e3;this.HANDLES_TIMEOUT=W1n?9999999:5e3;this.HANDLES_INTERVAL=300;this.locatorsChain=[];this.base||(this.base=this.frame)}setBase(r){this.base=r}setAnalytics(r){this.getAnalytics=r}init(...r){return this.sanitizeArgs(...r),new Proxy(this,{get:e((i,s)=>s==="setBase"?function(...c){this.setBase(c[0])}.bind(this):s==="setAnalytics"?function(...c){this.setAnalytics(c[0])}.bind(this):this.handleLocatorChain(i,s),"get")})}getLocatorSelector(r){if(r)return r._selector}sanitizeArgs(...r){if(r.length===1&&typeof r[0]=="object"){if(!r[0].anchors||typeof r[0].anchors!="function")throw new Error("Invalid compound selector format. Object must contain anchors property with a method value");this.anchorLocatorMethod=r[0].anchors,this.targetLocatorMethod=r[0].target;return}if(typeof r[0]!="function")throw new Error("Invalid compound selector format. First argument must be an object or a function");if(this.anchorLocatorMethod=r[0],r.length===2){if(typeof r[1]!="function")throw new Error("Invalid compound selector format. Second argument must be a function");this.targetLocatorMethod=r[1]}}async resolveLocator(){if(this.resolvedLocator)return this.resolvedLocator;mv("Waiting for locators..");let r=this.getLocatorsFromMethods();if(r.find(v=>!("_selector"in v)))throw new Error("Can't resolve at least one locator, make sure anchors and target are valid locators or strings");try{await Promise.all(r.map(async v=>WS(v.first().waitFor({bypassChecksum:!0}),this.LOCATORS_TIMEOUT,"Waiting for compound selector locators timeout")))}catch(v){throw new Error(`Error while waiting for locators - ${v.message}`)}let i=await WS(this.getElementHandles(r),this.HANDLES_TIMEOUT);mv(`Resolved to ${wSr(i)} elements from ${r.length} locators`);let s=this.getLocatorSelector(this.getLocatorsFromMethods(!1,!0,this.frame)[0]),c=await this.frame.evaluate(async({handles:v,targetSelector:E})=>window.checksum.testGenerator.getCompoundSelector().select(v,E),{handles:i,targetSelector:s});if(!c||c.length===0)throw new Error("Could not generate selectors from handles");mv(`Resolved compound selector to ${c.length} selectors`);let p=this.getBase(),_=p.locator(c[0]);return c.slice(1,50).forEach(v=>{_=_.or(p.locator(v))}),this.locatorsChain.length&&this.locatorsChain.forEach(({name:v,args:E})=>{_=_[v](...E)}),mv(`Compound locator selector: ${this.getLocatorSelector(_)}`),this.resolvedLocator=_,_}handleLocatorChain(r,i){if(typeof i=="symbol")return;if(i==="constructor")return e(function(..._){return this[i](..._)},"Locator");if(i==="toString")return()=>this.toString();let s=e(()=>new Proxy(r,{get:e((p,_)=>p.handleLocatorChain(p,_),"get")}),"createLocatorProxy");return i==="valueOf"?e(function(){return s()},"Locator"):i==="then"?(p,_)=>{this.resolveLocator().then(v=>p(v)).catch(_)}:Object.values([...Object.values(Sfe),...Object.values(PRe)]).includes(i)?e(function(..._){return r.locatorsChain.push({name:i,args:_}),s()},"Locator"):e(async function(..._){return this.handleAction(i,_)},"Locator").bind(this)}async handleAction(r,i){var s,c;try{if(typeof r=="symbol")return;if(!this.anchorLocatorMethod)throw new Error("Compound selection is missing anchor locators");let p=await this.resolveLocator();return this.frame.executeLocatorAction?await this.frame.executeLocatorAction(p,r,i):await p[r](...i)}catch(p){throw mv(`Failed to execute compound selection action: ${p}`),(c=(s=this.getAnalytics)==null?void 0:s.call(this))==null||c.compoundSelectionFailure({error:p.toString(),selector:this.toString()}),p}}async getElementHandles(r){mv("Resolving compound selector elements");let i,s,c,p,_,v=e(()=>{_=2},"resetSameHandlesCount");do i=s,s=[],await Promise.all(r.map(async E=>{let D=await E.elementHandles({bypassChecksum:!0});if(D.length===0)throw new Error(`No elements found for locator: ${this.getLocatorSelector(E)}`);s.push(D)})),c=wSr(s),p=i?wSr(i):0,mv(`Handles itteration, previous: ${i?p:"-"}, current: ${c}`),p!==c&&v(),await lb(this.HANDLES_INTERVAL);while(!i||p!==c||--_>0);return s}getLocatorsFromMethods(r=!0,i=!0,s=this.getBase()){return(r?this.anchorLocatorMethod(s):[]).concat(i&&this.targetLocatorMethod?[this.targetLocatorMethod(s)]:[]).map(c=>typeof c=="string"?s.getByText(c):c)}getBase(){return this.base}toString(){var r;return`CompoundSelection(${this.resolvedLocator?this.getLocatorSelector(this.resolvedLocator):`${this.anchorLocatorMethod.toString()}, ${(r=this.targetLocatorMethod)==null?void 0:r.toString()})`})`}};e(TSr,"CompoundSelectorLocator");wje=TSr,wSr=e(n=>n.reduce((r,i)=>r+i.length,0),"countHandleElements")});var ISr,G1n,lNi,FSr,Tje,PSr=Ws(()=>{"use strict";ISr=require("path");iS();BRe();G1n=require("fs"),lNi=!0,FSr=class FSr{constructor(r){this.options=r;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async r=>{let i=nw(r);if(this.trackedFramesGuid.includes(i))return this.frameNavigationPromises[i]=new Promise(async s=>{await this.loadScript(r),s()}),this.frameNavigationPromises[i]},"onFrameNavigated");this.loadScript=e(async(r,{retriesLeft:i=3,retryWaitMS:s=2e3,useWrapper:c=!0}={})=>{var E,D;if(c&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(r,{retriesLeft:i,retryWaitMS:s,useWrapper:!1}),r);if(!this.addScriptTagOptions){this.log.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(r))return;let p=!1;try{p=this.scriptLoadCheck?await((E=this.scriptLoadCheck)==null?void 0:E.call(this,r)):!1}catch{}if(p||this.isFrameClosed(r))return;this.options.scriptAddWait&&(this.log.log(`Waiting ${this.options.scriptAddWait}[ms] before adding script...`),await lb(this.options.scriptAddWait),this.log.log("Done waiting before adding script"));try{await r.addScriptTag(await this.makeInjectedScriptOptionsForAddScriptTag())}catch(w){if(i>0)return this.log.warn(`[InjectedScriptManager] Failed to add script to frame ${nw(r)}, trying again in ${s/1e3} seconds, ${i-1} retries left.`,w.message),await lb(s),this.loadScript(r,{retriesLeft:i-1,retryWaitMS:s,useWrapper:c});throw w}let _=nw(r),v=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[_]=v,this.options.scriptInitWait&&(this.log.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await lb(this.options.scriptInitWait),this.log.log("Done waiting before onScriptLoad")),!this.isFrameClosed(r)){if(this.navigatingFrames[_]&&this.navigatingFrames[_]!==v)return this.log.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[_];try{await((D=this.scriptLoadCallback)==null?void 0:D.call(this,r))}catch(w){this.log.error("[WebDriver] onScriptLoad error",w)}}},"loadScript");this.log=new Proxy(console,{get:e((r,i)=>(...s)=>{if(!this.options.silenceLogs)return r[i].apply(r,s)},"get")});this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(r){return this.scriptLoadCallback=r,this}setScriptLoadCheck(r){return this.scriptLoadCheck=r,this}setScriptLoadWrapper(r){return this.scriptLoadWrapper=r,this}async addTrackedFrame(r,i=!0){let s="mainFrame"in r?r.mainFrame():r,c=nw(s);if(this.trackedFramesGuid.includes(c)||this.trackedFramesGuid.push(c),i)return this.onFrameNavigated(s)}getNavigationPromise(r){if(!r){this.log.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let i=typeof r=="string"?r:"mainFrame"in r?nw(r.mainFrame()):nw(r);return this.frameNavigationPromises[i]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,ISr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}async makeInjectedScriptOptionsForAddScriptTag(){if(this.options.scriptSource==="url"&&this.addScriptTagOptions.url&&lNi){let i=await(await fetch(this.addScriptTagOptions.url)).text(),s=(0,ISr.join)(process.cwd(),"checksumlib.js");return(0,G1n.writeFileSync)(s,i),{path:s}}return this.addScriptTagOptions}isFrameClosed(r){return r.isDetached()||r.page().isClosed()}};e(FSr,"InjectedScriptManager");Tje=FSr});var K1n=Ws(()=>{"use strict"});var RSr,AIt,LSr,NSr,MSr,BSr,jSr,OSr,bIt,xIt,Y1n=Ws(()=>{"use strict";iS();K1n();RSr=class RSr{constructor(r){this.options=r}async handleError(r,i,s){let c=`Error in ${i} action during ${r} execution: ${s.message}`;throw new Error(c)}async guardedExecute(){try{return await(this.options.timeout!=null?WS(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(r){return this.handleError(this.options.method,this.constructor.name,r)}}};e(RSr,"Action");AIt=RSr,LSr=class LSr extends AIt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(LSr,"PlaywrightAction");NSr=LSr,MSr=class MSr extends AIt{constructor(i,s){super(i);this.pageInteractor=s}};e(MSr,"APIAction");BSr=MSr,jSr=class jSr extends BSr{constructor(r,i){super(r,i.pageInteractor)}async execute(){try{let{locator:r,args:i}=this.options,[s,c]=i,p=await r.screenshot({timeout:3e4}),v=(await this.pageInteractor.getTextDetection(p)).getRectangleByTextAndSizeRanking(s,c);if(!v)throw new Error("No matching text found");await r.click({position:v.center})}catch(r){throw new Error(`Error in canvas click action: ${r.message}`)}}};e(jSr,"CanvasClickAction");OSr=jSr,bIt=class bIt{static createAction(r,i){return r.method in this.customActionMap?new this.customActionMap[r.method]({...r,timeout:15e3},i):new NSr(r)}};e(bIt,"ActionFactory"),bIt.customActionMap={canvasClick:OSr};xIt=bIt});var CIt,EIt,X1n=Ws(()=>{"use strict";fH();xU();kSr();Y1n();Pyr();CIt=class CIt{constructor(r,i,s,c,p,_,v){this.frame=r;this.checksumPage=i;this.isReplMode=s;this.config=c;this.injectedScriptManager=p;this.getPageInteractor=_;this.onExecutionError=v;this.locatorStack=[];this.setFrameProxy(),this.checksumClient=new lLe({apiURL:this.config.apiURL,apiKey:this.config.apiKey})}static init(r,i,s,c,p,_,v=!1){return new CIt(r,i,v,_,s,c,p).proxy}setFrameProxy(){this.proxy=new Proxy(this,{get:e(function(i,s){return i.handleFrameMethod(s)},"get")})}handleFrameMethod(r){if(typeof r!="symbol")return typeof this[r]=="function"?r==="constructor"?this[r]:this[r].bind(this):[...Object.values(Sfe),...Object.values(PRe)].includes(r)?(this.pushToLocatorStack([{type:r,base:this.frame}]),e(function(s,c){try{return this.executeLocator(s,c)}catch(p){throw this.popLocatorChain(),p}},"Locator").bind(this)):this.frame[r]}page(){return this.checksumPage}compoundSelection(...r){var i;try{let s=this.locatorStack.length?(i=this.getCurrentLocatorInChain())==null?void 0:i.base:this.proxy;return new wje(this.proxy,s).init(...r)}catch{throw new Error("Failed generating compound selector")}}async wrapInternalSteps(r,i=this.frame){try{return i._checksumInternal=!0,await r()}finally{i._checksumInternal=!1}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.frame)}pushToLocatorStack(r){this.locatorStack.push(r)}getCurrentLocatorChain(){return this.locatorStack.length||this.locatorStack.push([]),this.locatorStack[this.locatorStack.length-1]}popLocatorChain(){return this.locatorStack.pop()}getCurrentLocatorInChain(){let r=this.getCurrentLocatorChain();return r==null?void 0:r[r.length-1]}getLocator(r,i){let s=this.getCurrentLocatorInChain();return s.base[s.type](r,i)}executeLocator(r,i){try{mv(`
606
606
  Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof r=="string"?`selector ${r}`:"locator"}`);try{r&&typeof r=="object"&&"has"in r&&this.popLocatorChain()}catch{}let s=this.getLocator(r,i);return new Proxy(s,{get:e((c,p)=>this.getLocatorMethod(s,c,p),"get")})}catch(s){mv("Failed to locate",s)}}getLocatorMethod(r,i,s){return s==="then"?this.handleThen(r,i,s):s==="catch"?this.handleCatch(r,i):s==="finally"?this.handleFinally(r,i):s==="constructor"?e(function(...p){return this.popLocatorChain(),i.constructor(...p)},"Locator"):s in i&&typeof i[s]!="function"||s===Symbol.toPrimitive||s in Object||s==="evaluate"?(this.popLocatorChain(),i[s]):s==="compoundSelection"?function(...c){let p=this.compoundSelection(...c);return p.setBase(r),p}.bind(this):[...Object.values(Sfe),...Object.values(PRe)].includes(s)?["or","and"].includes(s)?(mv("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),i[s]):(this.getCurrentLocatorChain().push({type:s,base:r}),e(function(...p){return this.executeLocator(p[0],p[1])},"Locator").bind(this)):s==="page"?()=>(this.popLocatorChain(),this.proxy.page()):e(async function(...p){let _=await this.executeLocatorAction(r,s,p);return this.popLocatorChain(),_},"Locator").bind(this)}async executeLocatorAction(r,i,s){var E;if(s&&Array.from(s).some(D=>(D==null?void 0:D.bypassChecksum)===!0))return r[i](...s);let c=r._selector;mv("Executing",i,c);let p=i==="_expect"?"assertion":"action",_=((E=this.config.options)==null?void 0:E.consecutiveActionDelay)??100;_>0&&p==="action"&&this.lastLocatorActionType==="action"&&(mv("Adding minimal wait between consecutive actions..."),await new Promise(D=>setTimeout(D,_))),this.lastLocatorActionType=p,mv("Running initial locator...");let v;try{return this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{mv("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{mv("[executeLocatorAction] checksum libs not loaded")}}),await xIt.createAction({locator:r,method:i,args:s,timeout:this.getLocatorActionTimeout(p,i,s)},{api:this.checksumClient,pageInteractor:this.getPageInteractor()}).guardedExecute();v=new Error("Locator action error")}catch(D){mv("Failed initial execution. Exception:",D.message),v=D}if(p==="action"&&this.onExecutionError)return this.onExecutionError({error:v,locator:r,method:i,args:s},this.frame);throw v}setExpectConfiguration(r=void 0){this.expectConfiguration=r}getLocatorActionTimeout(r,i,s=[]){var c;if(this.isReplMode)return null;try{if(r==="assertion"){let v=this.getAssertionTimeout(s);return mv(`Assertion timeout set to ${v}`),v}let p=["fill","dragTo"].includes(i)?1:0,_=(c=s[p])==null?void 0:c.timeout;return isNaN(_)?3e4:_}catch{return 3e4}}getAssertionTimeout(r=[]){var c,p,_,v,E;let i=(c=r[1])==null?void 0:c.timeout;if(i!==void 0)return i;if(((p=this.expectConfiguration)==null?void 0:p.timeout)!==void 0)return(_=this.expectConfiguration)==null?void 0:_.timeout;let s=(E=(v=this.testInfo._projectInternal)==null?void 0:v.expect)==null?void 0:E.timeout;return s!==void 0?s:3e4}handleThen(r,i,s){return(c,p)=>Promise.resolve(r).then(_=>{let v=c?c(_):_;return v instanceof Promise?v:this.getLocatorMethod(v,i,s)},_=>{if(p)return p(_);throw _})}handleCatch(r,i){return s=>Promise.resolve(r).catch(c=>{if(s)return s(c);throw c})}handleFinally(r,i){return s=>Promise.resolve(r).finally(s)}};e(CIt,"ChecksumFrame");EIt=CIt});var Z1n,DIt,kje,USr=Ws(()=>{"use strict";Z1n=H0(require("path"));fH();BEe();kSr();PSr();X1n();xU();aw();DIt=class DIt{constructor(r,i,s,c,p,_){this.page=r;this.config=s;this.getPageInteractor=c;this.injectedScriptManager=p;this._frames={};this.isVTG=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;this._isChecksumPage=!0;var v,E;this._context=i,this.setPageProxy(),this.injectedScriptManager||(this.injectedScriptManager=new Tje({scriptFile:Hd.checksumScript.path,scriptSource:Hd.checksumScript.source,scriptURL:Hd.checksumScript.url,isScriptFileAbsolute:!0,silenceLogs:!Hd.isDevMode,scriptInitWait:(v=s==null?void 0:s.options)==null?void 0:v.browserScriptInitWait,scriptAddWait:(E=s==null?void 0:s.options)==null?void 0:E.browserScriptAddWait})),this.registerPageEvents(),this.page.frames().forEach(D=>this.registerFrame(D)),_&&(this.variableStore=_.variableStore)}static makePage(r,i,s,c){let p=SIt();return new DIt(r,c,p,()=>i,s,void 0).proxy}async registerFrame(r){var c;let i=this.getFrameGuid(r);if(r===this.page.mainFrame()&&(this.mainFrameGuid=i),this._frames[i])return;let s=EIt.init(r,this.proxy,this.injectedScriptManager,this.getPageInteractor,(c=this.onExecutionError)==null?void 0:c.bind(this),this.config);this._frames[i]=s}async onExecutionError(r){throw r.error}getFrameGuid(r){return r._guid}getPageGuid(r){return r._guid}registerPageEvents(){this.page.on("frameattached",async r=>{this.registerFrame(r)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(i,s){return i.getPageMethod(s)},"get")})}getPageMethod(r){if(typeof this[r]=="function")return r==="constructor"?this[r]:this[r].bind(this);switch(r){case"pageInteractor":return this.getPageInteractor();case"variableStore":return this.variableStore;case"_isChecksumPage":return this._isChecksumPage}return Object.values(Sfe).includes(r)?e(function(s,c){try{return this.mainFrame()[r](s,c)}catch(p){throw p}},"Page").bind(this):this.page[r]}mainFrame(){var r;return(r=this._frames)==null?void 0:r[this.mainFrameGuid]}frames(){return Object.values(this._frames)}context(){return this._context}getPage(r){return this._context.getPage(r)}getFrame(r){if(!this.page.frames().find(s=>this.getFrameGuid(s)===r))throw new Error(`Frame with guid ${r} not found`);return this._frames[r]}async waitForDialog(r){try{return this.getPageInteractor().waitForDialog(!0,r)}catch(i){throw new Error(`Failed to handle native dialog: ${i}`)}}async reauthenticate(r){try{await this.getPageInteractor().reauthenticate(r,this.proxy)}catch(i){throw new Error(`Failed to reauthenticate: ${i}`)}}resolveAssetsFolder(r){return r.map(i=>Z1n.join(_nt(Ote()),i))}compoundSelection(...r){try{return new wje(this.mainFrame()).init(...r)}catch{throw new Error("Failed generating compound selector")}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}setExpectConfiguration(r=void 0){this.expectConfiguration=r,Object.values(this._frames).forEach(i=>i.setExpectConfiguration(r))}};e(DIt,"ChecksumPage");kje=DIt});var egn,qC,$C=Ws(()=>{egn=Object.defineProperty,qC=e((n,r)=>{let i={};for(var s in n)egn(i,s,{get:n[s],enumerable:!0});return r||egn(i,Symbol.toStringTag,{value:"Module"}),i},"__exportAll")});function n6e(n){return!!(n&&typeof n=="object"&&"type"in n&&n.type==="tool_call")}function tgn(n){return!!(n&&typeof n=="object"&&"toolCall"in n&&n.toolCall!=null&&typeof n.toolCall=="object"&&"id"in n.toolCall&&typeof n.toolCall.id=="string")}var Ije,Nst,wIt=Ws(()=>{e(n6e,"_isToolCall");e(tgn,"_configHasToolCallId");Nst=(Ije=class extends Error{output;constructor(r,i){super(r),this.output=i}},e(Ije,"ToolInputParsingException"),Ije)});var ngn=Qr((y5a,rgn)=>{"use strict";rgn.exports=function(n,r){if(typeof n!="string")throw new TypeError("Expected a string");return r=typeof r>"u"?"_":r,n.replace(/([a-z\d])([A-Z])/g,"$1"+r+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+r+"$2").toLowerCase()}});var lgn=Qr((v5a,QSr)=>{"use strict";var pNi=/[\p{Lu}]/u,fNi=/[\p{Ll}]/u,ign=/^[\p{Lu}](?![\p{Lu}])/gu,ogn=/([\p{Alpha}\p{N}_]|$)/u,cgn=/[_.\- ]+/,dNi=new RegExp("^"+cgn.source),agn=new RegExp(cgn.source+ogn.source,"gu"),sgn=new RegExp("\\d+"+ogn.source,"gu"),_Ni=e((n,r,i)=>{let s=!1,c=!1,p=!1;for(let _=0;_<n.length;_++){let v=n[_];s&&pNi.test(v)?(n=n.slice(0,_)+"-"+n.slice(_),s=!1,p=c,c=!0,_++):c&&p&&fNi.test(v)?(n=n.slice(0,_-1)+"-"+n.slice(_-1),p=c,c=!1,s=!0):(s=r(v)===v&&i(v)!==v,p=c,c=i(v)===v&&r(v)!==v)}return n},"preserveCamelCase"),mNi=e((n,r)=>(ign.lastIndex=0,n.replace(ign,i=>r(i))),"preserveConsecutiveUppercase"),hNi=e((n,r)=>(agn.lastIndex=0,sgn.lastIndex=0,n.replace(agn,(i,s)=>r(s)).replace(sgn,i=>r(i))),"postProcess"),ugn=e((n,r)=>{if(!(typeof n=="string"||Array.isArray(n)))throw new TypeError("Expected the input to be `string | string[]`");if(r={pascalCase:!1,preserveConsecutiveUppercase:!1,...r},Array.isArray(n)?n=n.map(p=>p.trim()).filter(p=>p.length).join("-"):n=n.trim(),n.length===0)return"";let i=r.locale===!1?p=>p.toLowerCase():p=>p.toLocaleLowerCase(r.locale),s=r.locale===!1?p=>p.toUpperCase():p=>p.toLocaleUpperCase(r.locale);return n.length===1?r.pascalCase?s(n):i(n):(n!==i(n)&&(n=_Ni(n,i,s)),n=n.replace(dNi,""),r.preserveConsecutiveUppercase?n=mNi(n,i):n=i(n),r.pascalCase&&(n=s(n.charAt(0))+n.slice(1)),hNi(n,s))},"camelCase");QSr.exports=ugn;QSr.exports.default=ugn});function fgn(n,r){return(r==null?void 0:r[n])||(0,pgn.default)(n)}function dgn(n,r,i){let s={};for(let c in n)Object.hasOwn(n,c)&&(s[r(c,i)]=n[c]);return s}var pgn,gNi,_gn=Ws(()=>{pgn=H0(ngn(),1),gNi=H0(lgn(),1);e(fgn,"keyToJson");e(dgn,"mapKeys")});function vNi(n){return"lc"in n||Object.keys(n).length===1&&"__lc_escaped__"in n}function ANi(n){return{[yNi]:n}}function xNi(n){return n!==null&&typeof n=="object"&&"lc_serializable"in n&&typeof n.toJSON=="function"}function bNi(n){var i;let r;return n!==null&&typeof n=="object"?"lc_id"in n&&Array.isArray(n.lc_id)?r=n.lc_id:r=[((i=n.constructor)==null?void 0:i.name)??"Object"]:r=[typeof n],{lc:1,type:"not_implemented",id:r}}function TIt(n,r=new WeakSet){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){if(r.has(n))return bNi(n);if(xNi(n))return n;r.add(n);let i=n;if(vNi(i))return r.delete(n),ANi(i);let s={};for(let[c,p]of Object.entries(i))s[c]=TIt(p,r);return r.delete(n),s}return Array.isArray(n)?n.map(i=>TIt(i,r)):n}var yNi,mgn=Ws(()=>{yNi="__lc_escaped__";e(vNi,"needsEscaping");e(ANi,"escapeObject");e(xNi,"isSerializableLike");e(bNi,"createNotImplemented");e(TIt,"escapeIfNeeded")});function hgn(n){return Array.isArray(n)?[...n]:{...n}}function ENi(n,r){let i=hgn(n);for(let[s,c]of Object.entries(r)){let[p,..._]=s.split(".").reverse(),v=i;for(let E of _.reverse()){if(v[E]===void 0)break;v[E]=hgn(v[E]),v=v[E]}v[p]!==void 0&&(v[p]={lc:1,type:"secret",id:[c]})}return i}function qSr(n){let r=Object.getPrototypeOf(n);return typeof n.lc_name=="function"&&(typeof r.lc_name!="function"||n.lc_name()!==r.lc_name())?n.lc_name():n.name}var jTe,Pge,Bst=Ws(()=>{$C();_gn();mgn();e(hgn,"shallowCopy");e(ENi,"replaceSecrets");e(qSr,"get_lc_unique_name");Pge=(jTe=class{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,qSr(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(r,...i){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(r||{}).filter(([s])=>{var c;return(c=this.lc_serializable_keys)==null?void 0:c.includes(s)})):this.lc_kwargs=r??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jTe||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let r={},i={},s=Object.keys(this.lc_kwargs).reduce((v,E)=>(v[E]=E in this?this[E]:this.lc_kwargs[E],v),{});for(let v=Object.getPrototypeOf(this);v;v=Object.getPrototypeOf(v))Object.assign(r,Reflect.get(v,"lc_aliases",this)),Object.assign(i,Reflect.get(v,"lc_secrets",this)),Object.assign(s,Reflect.get(v,"lc_attributes",this));Object.keys(i).forEach(v=>{let E=this,D=s,[w,...B]=v.split(".").reverse();for(let N of B.reverse()){if(!(N in E)||E[N]===void 0)return;(!(N in D)||D[N]===void 0)&&(typeof E[N]=="object"&&E[N]!=null?D[N]={}:Array.isArray(E[N])&&(D[N]=[])),E=E[N],D=D[N]}w in E&&E[w]!==void 0&&(D[w]=D[w]||E[w])});let c={},p=new WeakSet;p.add(this);for(let[v,E]of Object.entries(s))c[v]=TIt(E,p);let _=dgn(Object.keys(i).length?ENi(c,i):c,fgn,r);return{lc:1,type:"constructor",id:this.lc_id,kwargs:_}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}},e(jTe,"Serializable"),jTe)});function i6e(n){return typeof n=="object"&&n!==null&&"type"in n&&typeof n.type=="string"&&"source_type"in n&&(n.source_type==="url"||n.source_type==="base64"||n.source_type==="text"||n.source_type==="id")}function Ost(n){return i6e(n)&&n.source_type==="url"&&"url"in n&&typeof n.url=="string"}function Rst(n){return i6e(n)&&n.source_type==="base64"&&"data"in n&&typeof n.data=="string"}function $Sr(n){return i6e(n)&&n.source_type==="id"&&"id"in n&&typeof n.id=="string"}function VSr(n){if(i6e(n)){if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url}};if(n.source_type==="base64"){if(!n.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${n.mime_type};base64,${n.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function kIt({dataUrl:n,asTypedArray:r=!1}){let i=n.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),s;if(i){s=i[1].toLowerCase();let c=r?Uint8Array.from(atob(i[2]),p=>p.charCodeAt(0)):i[2];return{mime_type:s,data:c}}}var Lst=Ws(()=>{e(i6e,"isDataContentBlock");e(Ost,"isURLContentBlock");e(Rst,"isBase64ContentBlock");e($Sr,"isIDContentBlock");e(VSr,"convertToOpenAIImageBlock");e(kIt,"parseBase64DataUrl")});function M1(n,r){return my(n)&&n.type===r}function my(n){return typeof n=="object"&&n!==null}function XP(n){return Array.isArray(n)}function Q_(n){return typeof n=="string"}function TY(n){return typeof n=="number"}function IIt(n){return n instanceof Uint8Array}function JSr(n){try{return JSON.parse(n)}catch{return}}var kY,yre=Ws(()=>{e(M1,"_isContentBlock");e(my,"_isObject");e(XP,"_isArray");e(Q_,"_isString");e(TY,"_isNumber");e(IIt,"_isBytesArray");e(JSr,"safeParseJson");kY=e(n=>n(),"iife")});function CNi(n){if(n.type==="char_location"&&Q_(n.document_title)&&TY(n.start_char_index)&&TY(n.end_char_index)&&Q_(n.cited_text)){let{document_title:r,start_char_index:i,end_char_index:s,cited_text:c,...p}=n;return{...p,type:"citation",source:"char",title:r??void 0,startIndex:i,endIndex:s,citedText:c}}if(n.type==="page_location"&&Q_(n.document_title)&&TY(n.start_page_number)&&TY(n.end_page_number)&&Q_(n.cited_text)){let{document_title:r,start_page_number:i,end_page_number:s,cited_text:c,...p}=n;return{...p,type:"citation",source:"page",title:r??void 0,startIndex:i,endIndex:s,citedText:c}}if(n.type==="content_block_location"&&Q_(n.document_title)&&TY(n.start_block_index)&&TY(n.end_block_index)&&Q_(n.cited_text)){let{document_title:r,start_block_index:i,end_block_index:s,cited_text:c,...p}=n;return{...p,type:"citation",source:"block",title:r??void 0,startIndex:i,endIndex:s,citedText:c}}if(n.type==="web_search_result_location"&&Q_(n.url)&&Q_(n.title)&&Q_(n.encrypted_index)&&Q_(n.cited_text)){let{url:r,title:i,encrypted_index:s,cited_text:c,...p}=n;return{...p,type:"citation",source:"url",url:r,title:i,startIndex:Number(s),endIndex:Number(s),citedText:c}}if(n.type==="search_result_location"&&Q_(n.source)&&Q_(n.title)&&TY(n.start_block_index)&&TY(n.end_block_index)&&Q_(n.cited_text)){let{source:r,title:i,start_block_index:s,end_block_index:c,cited_text:p,..._}=n;return{..._,type:"citation",source:"search",url:r,title:i??void 0,startIndex:s,endIndex:c,citedText:p}}}function ygn(n){if(M1(n,"document")&&my(n.source)&&"type"in n.source){if(n.source.type==="base64"&&Q_(n.source.media_type)&&Q_(n.source.data))return{type:"file",mimeType:n.source.media_type,data:n.source.data};if(n.source.type==="url"&&Q_(n.source.url))return{type:"file",url:n.source.url};if(n.source.type==="file"&&Q_(n.source.file_id))return{type:"file",fileId:n.source.file_id};if(n.source.type==="text"&&Q_(n.source.data))return{type:"file",mimeType:String(n.source.media_type??"text/plain"),data:n.source.data}}else if(M1(n,"image")&&my(n.source)&&"type"in n.source){if(n.source.type==="base64"&&Q_(n.source.media_type)&&Q_(n.source.data))return{type:"image",mimeType:n.source.media_type,data:n.source.data};if(n.source.type==="url"&&Q_(n.source.url))return{type:"image",url:n.source.url};if(n.source.type==="file"&&Q_(n.source.file_id))return{type:"image",fileId:n.source.file_id}}}function vgn(n){function*r(){for(let i of n){let s=ygn(i);s?yield s:yield i}}return e(r,"iterateContent"),Array.from(r())}function ggn(n){function*r(){var s;let i=typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;for(let c of i){if(M1(c,"text")&&Q_(c.text)){let{text:p,citations:_,...v}=c;if(XP(_)&&_.length){let E=_.reduce((D,w)=>{let B=CNi(w);return B?[...D,B]:D},[]);yield{...v,type:"text",text:p,annotations:E};continue}else{yield{...v,type:"text",text:p};continue}}else if(M1(c,"thinking")&&Q_(c.thinking)){let{thinking:p,signature:_,...v}=c;yield{...v,type:"reasoning",reasoning:p,signature:_};continue}else if(M1(c,"redacted_thinking")){yield{type:"non_standard",value:c};continue}else if(M1(c,"tool_use")&&Q_(c.name)&&Q_(c.id)){yield{type:"tool_call",id:c.id,name:c.name,args:c.input};continue}else if(M1(c,"input_json_delta")){if(DNi(n)&&((s=n.tool_call_chunks)!=null&&s.length)){let p=n.tool_call_chunks[0];yield{type:"tool_call_chunk",id:p.id,name:p.name,args:p.args,index:p.index};continue}}else if(M1(c,"server_tool_use")&&Q_(c.name)&&Q_(c.id)){let{name:p,id:_}=c;if(p==="web_search"){yield{id:_,type:"server_tool_call",name:"web_search",args:{query:kY(()=>{if(typeof c.input=="string")return c.input;if(my(c.input)&&Q_(c.input.query))return c.input.query;if(Q_(c.partial_json)){let v=JSr(c.partial_json);if(v!=null&&v.query)return v.query}return""})}};continue}else if(c.name==="code_execution"){yield{id:_,type:"server_tool_call",name:"code_execution",args:{code:kY(()=>{if(typeof c.input=="string")return c.input;if(my(c.input)&&Q_(c.input.code))return c.input.code;if(Q_(c.partial_json)){let v=JSr(c.partial_json);if(v!=null&&v.code)return v.code}return""})}};continue}}else if(M1(c,"web_search_tool_result")&&Q_(c.tool_use_id)&&XP(c.content)){let{content:p,tool_use_id:_}=c;yield{type:"server_tool_call_result",name:"web_search",toolCallId:_,status:"success",output:{urls:p.reduce((v,E)=>M1(E,"web_search_result")?[...v,E.url]:v,[])}};continue}else if(M1(c,"code_execution_tool_result")&&Q_(c.tool_use_id)&&my(c.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:c.tool_use_id,status:"success",output:c.content};continue}else if(M1(c,"mcp_tool_use")){yield{id:c.id,type:"server_tool_call",name:"mcp_tool_use",args:c.input};continue}else if(M1(c,"mcp_tool_result")&&Q_(c.tool_use_id)&&my(c.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:c.tool_use_id,status:"success",output:c.content};continue}else if(M1(c,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:c.input};continue}else if(M1(c,"search_result")){yield{id:c.id,type:"non_standard",value:c};continue}else if(M1(c,"tool_result")){yield{id:c.id,type:"non_standard",value:c};continue}else{let p=ygn(c);if(p){yield p;continue}}yield{type:"non_standard",value:c}}}return e(r,"iterateContent"),Array.from(r())}function DNi(n){return typeof(n==null?void 0:n._getType)=="function"&&typeof n.concat=="function"&&n._getType()==="ai"}var Agn,zSr=Ws(()=>{yre();e(CNi,"convertAnthropicAnnotation");e(ygn,"convertToV1FromAnthropicContentBlock");e(vgn,"convertToV1FromAnthropicInput");e(ggn,"convertToV1FromAnthropicMessage");Agn={translateContent:ggn,translateContentChunk:ggn};e(DNi,"_isAIMessageChunk")});function SNi(n){return Ost(n)?{type:n.type,mimeType:n.mime_type,url:n.url,metadata:n.metadata}:Rst(n)?{type:n.type,mimeType:n.mime_type??"application/octet-stream",data:n.data,metadata:n.metadata}:$Sr(n)?{type:n.type,mimeType:n.mime_type,fileId:n.id,metadata:n.metadata}:n}function xgn(n){return n.map(SNi)}function bgn(n){return!!(M1(n,"image_url")&&my(n.image_url)||M1(n,"input_audio")&&my(n.input_audio)||M1(n,"file")&&my(n.file))}function Egn(n){if(M1(n,"image_url")&&my(n.image_url)&&Q_(n.image_url.url)){let r=kIt({dataUrl:n.image_url.url});return r?{type:"image",mimeType:r.mime_type,data:r.data}:{type:"image",url:n.image_url.url}}else{if(M1(n,"input_audio")&&my(n.input_audio)&&Q_(n.input_audio.data)&&Q_(n.input_audio.format))return{type:"audio",data:n.input_audio.data,mimeType:`audio/${n.input_audio.format}`};if(M1(n,"file")&&my(n.file)&&Q_(n.file.data)){let r=kIt({dataUrl:n.file.data});if(r)return{type:"file",data:r.data,mimeType:r.mime_type};if(Q_(n.file.file_id))return{type:"file",fileId:n.file.file_id}}}return n}var HSr=Ws(()=>{Lst();yre();e(SNi,"convertToV1FromDataContentBlock");e(xgn,"convertToV1FromDataContent");e(bgn,"isOpenAIDataBlock");e(Egn,"convertToV1FromOpenAIDataBlock")});function wNi(n){let r=[];typeof n.content=="string"?n.content.length>0&&r.push({type:"text",text:n.content}):r.push(...FIt(n.content));for(let i of n.tool_calls??[])r.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return r}function TNi(n){let r=[];typeof n.content=="string"?n.content.length>0&&r.push({type:"text",text:n.content}):r.push(...FIt(n.content));for(let i of n.tool_calls??[])r.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return r}function FIt(n){let r=[];for(let i of n)bgn(i)?r.push(Egn(i)):r.push(i);return r}function kNi(n){if(n.type==="url_citation"){let{url:r,title:i,start_index:s,end_index:c}=n;return{type:"citation",url:r,title:i,startIndex:s,endIndex:c}}if(n.type==="file_citation"){let{file_id:r,filename:i,index:s}=n;return{type:"citation",title:i,startIndex:s,endIndex:s,fileId:r}}return n}function Cgn(n){function*r(){var s;my((s=n.additional_kwargs)==null?void 0:s.reasoning)&&XP(n.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:n.additional_kwargs.reasoning.summary.reduce((c,p)=>my(p)&&Q_(p.text)?`${c}${p.text}`:c,"")});let i=typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;for(let c of i)if(M1(c,"text")){let{text:p,annotations:_,phase:v,extras:E,...D}=c,w=my(E)?{...E}:{};Q_(v)&&(w.phase=v);let B=Object.keys(w).length>0?{extras:w}:{};Array.isArray(_)?yield{...D,...B,type:"text",text:String(p),annotations:_.map(kNi)}:yield{...D,...B,type:"text",text:String(p)}}for(let c of n.tool_calls??[])yield{type:"tool_call",id:c.id,name:c.name,args:c.args};if(my(n.additional_kwargs)&&XP(n.additional_kwargs.tool_outputs))for(let c of n.additional_kwargs.tool_outputs){if(M1(c,"web_search_call")){let p={};if(my(c.action)&&Q_(c.action.query)&&(p.query=c.action.query),yield{id:c.id,type:"server_tool_call",name:"web_search",args:p},c.status==="completed"||c.status==="failed"){let _={};my(c.action)&&(_.action=c.action),yield{type:"server_tool_call_result",toolCallId:Q_(c.id)?c.id:"",status:c.status==="completed"?"success":"error",output:_}}continue}else if(M1(c,"file_search_call")){yield{id:c.id,type:"server_tool_call",name:"file_search",args:{queries:XP(c.queries)?c.queries:[]}},(c.status==="completed"||c.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:Q_(c.id)?c.id:"",status:c.status==="completed"?"success":"error",output:XP(c.results)?{results:c.results}:{}});continue}else if(M1(c,"computer_call")){yield{type:"non_standard",value:c};continue}else if(M1(c,"code_interpreter_call")){if(Q_(c.code)&&(yield{id:c.id,type:"server_tool_call",name:"code_interpreter",args:{code:c.code}}),XP(c.outputs)){let p=kY(()=>{if(c.status!=="in_progress"){if(c.status==="completed")return 0;if(c.status==="incomplete")return 127;if(c.status!=="interpreting"&&c.status==="failed")return 1}});for(let _ of c.outputs)if(M1(_,"logs")){yield{type:"server_tool_call_result",toolCallId:c.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:p??0,stderr:[0,void 0].includes(p)?void 0:String(_.logs),stdout:[0,void 0].includes(p)?String(_.logs):void 0}};continue}}continue}else if(M1(c,"mcp_call")){yield{id:c.id,type:"server_tool_call",name:"mcp_call",args:c.input};continue}else if(M1(c,"mcp_list_tools")){yield{id:c.id,type:"server_tool_call",name:"mcp_list_tools",args:c.input};continue}else if(M1(c,"mcp_approval_request")){yield{type:"non_standard",value:c};continue}else if(M1(c,"tool_search_call")){let p={};my(c.arguments)&&Object.assign(p,c.arguments);let _={};Q_(c.execution)&&(_.execution=c.execution),Q_(c.status)&&(_.status=c.status),Q_(c.call_id)&&(_.call_id=c.call_id),yield{id:Q_(c.id)?c.id:"",type:"server_tool_call",name:"tool_search",args:p,...Object.keys(_).length>0?{extras:_}:{}};continue}else if(M1(c,"tool_search_output")){let p={name:"tool_search"};Q_(c.execution)&&(p.execution=c.execution),yield{type:"server_tool_call_result",toolCallId:Q_(c.id)?c.id:"",status:c.status==="completed"?"success":c.status==="failed"?"error":"success",output:{tools:XP(c.tools)?c.tools:[]},extras:p};continue}else if(M1(c,"image_generation_call")){Q_(c.result)&&(yield{type:"image",mimeType:"image/png",data:c.result,id:Q_(c.id)?c.id:void 0,metadata:{status:Q_(c.status)?c.status:void 0}}),yield{type:"non_standard",value:c};continue}my(c)&&(yield{type:"non_standard",value:c})}}return e(r,"iterateContent"),Array.from(r())}function INi(n){function*r(){yield*Cgn(n);for(let i of n.tool_call_chunks??[])yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args}}return e(r,"iterateContent"),Array.from(r())}var Dgn,WSr=Ws(()=>{yre();HSr();e(wNi,"convertToV1FromChatCompletions");e(TNi,"convertToV1FromChatCompletionsChunk");e(FIt,"convertToV1FromChatCompletionsInput");e(kNi,"convertResponsesAnnotation");e(Cgn,"convertToV1FromResponses");e(INi,"convertToV1FromResponsesChunk");Dgn={translateContent:e(n=>typeof n.content=="string"?wNi(n):Cgn(n),"translateContent"),translateContentChunk:e(n=>typeof n.content=="string"?TNi(n):INi(n),"translateContentChunk")}});function GSr(n){return typeof n=="object"&&n!==null&&"type"in n&&"content"in n&&(typeof n.content=="string"||Array.isArray(n.content))}var KSr=Ws(()=>{e(GSr,"isMessage")});function Sgn(n,r="pretty"){return r==="pretty"?FNi(n):JSON.stringify(n)}function FNi(n){let r=[],i=` ${n.type.charAt(0).toUpperCase()+n.type.slice(1)} Message `,s=Math.floor((80-i.length)/2),c="=".repeat(s),p=i.length%2===0?c:`${c}=`;if(r.push(`${c}${i}${p}`),n.type==="ai"){let _=n;if(_.tool_calls&&_.tool_calls.length>0){r.push("Tool Calls:");for(let v of _.tool_calls){r.push(` ${v.name} (${v.id})`),r.push(` Call ID: ${v.id}`),r.push(" Args:");for(let[E,D]of Object.entries(v.args))r.push(` ${E}: ${typeof D=="object"?JSON.stringify(D):D}`)}}}if(n.type==="tool"){let _=n;_.name&&r.push(`Name: ${_.name}`)}return typeof n.content=="string"&&n.content.trim()&&(r.length>1&&r.push(""),r.push(n.content)),r.join(`
607
607
  `)}var wgn=Ws(()=>{e(Sgn,"convertToFormattedString");e(FNi,"convertToPrettyString")});function Tgn(n){return Array.isArray(n)?n:typeof n=="string"?n===""?[]:[{type:"text",text:n}]:n==null?[]:[n]}function D0e(n,r){if(typeof n=="string")return n===""?r:typeof r=="string"?n+r:Array.isArray(r)&&r.length===0?n:Array.isArray(r)&&r.some(i=>i6e(i))?[{type:"text",source_type:"text",text:n},...r]:[{type:"text",text:n},...r];if(Array.isArray(r)){let i=Tgn(n);return Pje(i,r)??[...i,...r]}else return r===""?n:Array.isArray(n)&&n.some(i=>i6e(i))?[...n,{type:"file",source_type:"text",text:r}]:[...Tgn(n),{type:"text",text:r}]}function PNi(n,r){function i(s,c){if(typeof s!="object"||s===null||s===void 0)return s;if(c>=r)return Array.isArray(s)?"[Array]":"[Object]";if(Array.isArray(s))return s.map(_=>i(_,c+1));let p={};for(let _ of Object.keys(s))p[_]=i(s[_],c+1);return p}return e(i,"helper"),JSON.stringify(i(n,0),null,2)}function vre(n,r,i){let s=(i==null?void 0:i.ignoreKeys)??Fgn;if(n==null&&r==null)return;if(n==null||r==null)return n??r;let c={...n};for(let[p,_]of Object.entries(r))if(c[p]==null)c[p]=_;else{if(_==null)continue;if(typeof c[p]!=typeof _||Array.isArray(c[p])!==Array.isArray(_))throw new Error(`field[${p}] already exists in the message chunk, but with a different type.`);if(typeof c[p]=="string"){if(p==="type")continue;if(["id","name","output_version","model_provider"].includes(p))_&&(c[p]=_);else{if(s.includes(p))continue;c[p]+=_}}else if(typeof c[p]=="number"){if(s.includes(p))continue;c[p]=c[p]+_}else if(typeof c[p]=="object"&&!Array.isArray(c[p]))c[p]=vre(c[p],_,i);else if(Array.isArray(c[p]))c[p]=Pje(c[p],_,i);else{if(c[p]===_)continue;console.warn(`field[${p}] already exists in this message chunk and value has unsupported type.`)}}return c}function NNi(n){return typeof n=="number"||typeof n=="string"}function kgn(n){return typeof n!="object"||n===null||!("index"in n)?!1:NNi(n.index)}function Ign(n){if(typeof n!="object"||n===null||!("id"in n))return!1;let r=n.id;return r!=null&&r!==""}function BNi(n,r){let i=kgn(r),s=Ign(r);return!i&&!s?-1:n.findIndex(c=>{let p=kgn(c),_=Ign(c);return i&&p?c.index!==r.index?!1:_&&s?c.id===r.id:!0:!i&&!p&&s&&_?c.id===r.id:!1})}function Pje(n,r,i){if(!(n==null&&r==null)){if(n==null||r==null)return n||r;{let s=[...n];for(let c of r){let p=BNi(s,c);if(p!==-1)s[p]=vre(s[p],c,i);else{if(typeof c=="object"&&c!==null&&"text"in c&&c.text==="")continue;s.push(c)}}return s}}}function XSr(n){return typeof n.role=="string"}function QTe(n){return typeof(n==null?void 0:n._getType)=="function"}var YSr,Fje,DH,Fgn,UTe,a6e,g$=Ws(()=>{Bst();Lst();zSr();HSr();WSr();KSr();wgn();YSr=Symbol.for("langchain.message");e(Tgn,"contentBlocksFromNonStringFirst");e(D0e,"mergeContent");e(PNi,"stringifyWithDepthLimit");DH=(Fje=class extends Pge{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[YSr]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(r){let i=typeof r=="string"||Array.isArray(r)?{content:r}:r;i.additional_kwargs||(i.additional_kwargs={}),i.response_metadata||(i.response_metadata={}),super(i),this.name=i.name,i.content===void 0&&i.contentBlocks!==void 0?(this.content=i.contentBlocks,this.response_metadata={output_version:"v1",...i.response_metadata}):i.content!==void 0?(this.content=i.content??[],this.response_metadata=i.response_metadata):(this.content=[],this.response_metadata=i.response_metadata),this.additional_kwargs=i.additional_kwargs,this.id=i.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(r=>typeof r=="string"?r:r.type==="text"?r.text:"").join(""):""}get contentBlocks(){let r=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[xgn,FIt,vgn].reduce((i,s)=>s(i),r)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(r){return typeof r=="object"&&r!==null&&YSr in r&&r[YSr]===!0&&GSr(r)}_updateId(r){this.id=r,this.lc_kwargs.id=r}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](r){if(r===null)return this;let i=PNi(this._printableFields,Math.max(4,r));return`${this.constructor.lc_name()} ${i}`}toFormattedString(r="pretty"){return Sgn(this,r)}},e(Fje,"BaseMessage"),Fje),Fgn=["index","created","timestamp"];e(vre,"_mergeDicts");e(NNi,"isMergeableIndex");e(kgn,"hasMergeableIndex");e(Ign,"hasMergeableId");e(BNi,"_findMergeTarget");e(Pje,"_mergeLists");a6e=(UTe=class extends DH{static isInstance(r){if(!super.isInstance(r))return!1;let i=Object.getPrototypeOf(r);for(;i!==null;){if(i===UTe.prototype)return!0;i=Object.getPrototypeOf(i)}return!1}},e(UTe,"BaseMessageChunk"),UTe);e(XSr,"_isMessageFieldWithRole");e(QTe,"isBaseMessage")});function ZSr(n){return n!=null&&typeof n=="object"&&"lc_direct_tool_output"in n&&n.lc_direct_tool_output===!0}function e3r(n){let r=[],i=[];for(let s of n)if(s.function){let c=s.function.name;try{let p=JSON.parse(s.function.arguments);r.push({name:c||"",args:p||{},id:s.id})}catch{i.push({name:c,args:s.function.arguments,id:s.id,error:"Malformed args."})}}else continue;return[r,i]}var Nje,qTe,Bje=Ws(()=>{$C();g$();e(ZSr,"isDirectToolOutput");qTe=(Nje=class extends DH{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(r,i,s){let c=typeof r=="string"||Array.isArray(r)?{content:r,name:s,tool_call_id:i}:r;super(c),this.tool_call_id=c.tool_call_id,this.artifact=c.artifact,this.status=c.status,this.metadata=c.metadata}static isInstance(r){return super.isInstance(r)&&r.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},e(Nje,"ToolMessage"),Nje);e(e3r,"defaultToolCallParser")});function Pgn(n){let r=Symbol.for(n);return{brand(i,s){let c=s?Symbol.for(`${n}.${s}`):r,_=class _ extends i{[c]=!0;constructor(...E){super(...E)}static isInstance(E){return typeof E=="object"&&E!==null&&c in E&&E[c]===!0}};e(_,"_Branded");let p=_;return Object.defineProperty(p,"name",{value:i.name}),p},sub(i){return Pgn(`${n}.${i}`)},isInstance(i){return typeof i=="object"&&i!==null&&r in i&&i[r]===!0}}}var Ngn,Bgn=Ws(()=>{e(Pgn,"createNamespace");Ngn=Pgn("langchain")});function t3r(n,r){return n.lc_error_code=r,n.message=`${n.message}
@@ -1728,7 +1728,7 @@ ${de}${le}${xe}${pwn.default.cursorHide}`});var wOt=H0(require("child_process"))
1728
1728
  }`}renderCodeAssertions(r,i){r&&!i&&(r==null||r.forEach(s=>{this.addAssertion(s)}))}buildClickActionOptionsObject(r){let{clickOffset:i,force:s}=r;if(!i&&!s)return{};let c={};return i&&(c.position={x:i.x,y:i.y}),s&&(c.force=!0),c}getOptionsString(r,i){let{eventCode:s,actionOptions:c,login:p={}}=r,_=ORe[s],v=_&&_>=1;if(c){let D=i?`({
1729
1729
  ...(${c}),
1730
1730
  ...(${this.makeOptions(i)})
1731
- })`:c;return v?`, ${D}`:D}let E=this.buildClickActionOptionsObject(r);return this.makeOptions({...i,...E,...p},v)}buildFillValue(r){return Array.isArray(r)?`[${r.map(this.buildFillValue.bind(this)).join(", ")}]`:typeof r=="object"?`{ ${Object.entries(r).map(([i,s])=>`${i}: ${this.buildFillValue(s)}`).join(", ")} }`:typeof r=="string"?oke(r):r}buildActionCode(r,i,s){let{eventCode:c,unevaluatedFillValue:p,dropTarget:_,files:v,switchToTab:E,userRole:D,canvas:w,nativeDialog:B,codeContext:N}=r,L=this.buildFillValue(p),M=eXr[c],V=this.getOptionsString(r,s),Z=(N==null?void 0:N.frameTargetName)??"page";switch(c){case"navigation":return[`${i}.${M}(${this.formatURL(p)}${V})`];case"drag_and_drop":return[`${i}.${M}(${this.buildLocatorChain(Z,_.locator,_.locatorWithVars,_.parentFramesSelectors,_.selector,_.selectorWithVars)}${V})`];case"click":case"double_click":case"check":case"uncheck":case"hover":return[`${i}.${M}(${V})`];case"input":case"selectoption":case"keystroke":return[`${i}.${M}(${L}${V})`];case"click_and_type":return[`${i}.click(${V})`,`${i}.pressSequentially(${L}${V?`, ${V}`:""})`];case"clear_and_type":return[`${i}.clear(${this.makeOptions(s)})`,`${i}.pressSequentially(${L}${V?`, ${V}`:""})`];case"custom_code":return[p];case"wait":return[`${i}.${M}(${p||1e3}${V})`];case"upload_files":return v!=null&&v.length||console.warn("Input files are required for SetInputFiles event code"),[`${i}.${M}(page.resolveAssetsFolder(["${v.join('", "')}"])${V})`];case"switch_tab":return[`page = ${i}.${M}(${E.index}${V})`];case"logout_and_login":return[`${i}.${M}("${D}")`];case"canvas_click":return[`${i}.${M}("${w.canvasText}"${w.rectSizeIndex?`, ${w.rectSizeIndex}`:""})`];case"native_accept":{let ue=B.dialogResult!=null&&(0,Awn.isString)(B.dialogResult)?`"${B.dialogResult}"`:"";return[`${i}.waitForDialog().then(async (${B.dialogType}) => {await ${B.dialogType}.accept(${ue})})`]}case"native_dismiss":return[`${i}.waitForDialog().then(async (${B.dialogType}) => {await ${B.dialogType}.dismiss()})`];case"login":return[this.makeLoginCode(r)];default:return[]}}buildLocatorChain(r,i,s,c,p,_,v){let E=this.addFrameSelectorsToLocatorChain(r,c),D=this.addFrameSelectorsToLocatorChain("page",c);if(v){let w=this.buildCompoundSelectorLocatorChain(E,v);if(w)return w}return s?E+=`.${P8t(s,D)}`:_?E+=`.locator('${this.escapeSelector(_)}')`:i?E+=`.${P8t(i,D)}`:p&&(E+=`.locator('${this.escapeSelector(p)}')`),E}addFrameSelectorsToLocatorChain(r,i){return(i??[]).reduce((s,c)=>`${s}.frameLocator('${this.escapeSelector(c)}')`,r)}buildCompoundSelectorLocatorChain(r,i){let s=e(c=>c.selection.type==="content"?`"${c.selection.value}"`:c.locator?`base.${c.locator}`:`base.locator('${this.escapeSelector(c.selector)}')`,"getElementSelector");try{return`${r}.compoundSelection((base) => [${i.contextElements.map(c=>s(c.element)).join(", ")}], (base) => ${i.targetRelativeSelector.locator?`base.${i.targetRelativeSelector.locator}`:`base.locator('${this.escapeSelector(i.targetRelativeSelector.selector)}')`}).first()`}catch(c){console.error("Error building compound selector locator chain",c);return}}formatURL(r){let i=this.resolveRelativeURL(r);return oke(decodeURIComponent(i))}resolveRelativeURL(r){if(!r)return"";if(r.startsWith("/"))return r;let i;try{i=new URL(r)}catch(_){if(_ instanceof TypeError)return r;throw _}if(!this.options.environment.baseURL)return r;let s=new URL(this.options.environment.baseURL),c=e(_=>_.replace(/^www\./,""),"normalizeHostname");return!s||s.protocol!==i.protocol||c(s.hostname)!==c(i.hostname)||!i.pathname.startsWith(s.pathname)?r:i.pathname.substring(s.pathname.length).replace(/\/$/,"").replace(/^(?!\/)/,"/")+i.search+i.hash}addVariable(r){this.test.usingVariableStore=!0,this.addCode(nXr([r],{onlyValueExpression:!0}))}addAssertion(r){this.addCode(this.assertionGenerator.generateAssertionCode(r))}addCode(r){Array.isArray(r)||(r=[r]),r.forEach(i=>{if(!i)return;let s=i.trimEnd();s.endsWith(";")||(s+=";"),this.test.lines.push({type:0,content:s})})}addFunction(r){this.test.lines.push({type:0,content:r})}addComment(r){this.test.lines.push({type:1,content:`/* ${r} */`})}getTestMetadata(){return this.test}createFallbackMarkupForSelector(r,i=[],s,c,p){let _=(i||[]).concat(this.test.fallbackMarkups.map(E=>E.id)),v;do v=F8t(5);while(_.indexOf(v)>-1);return{id:v,selector:r,esraMetadata:s,compoundSelector:c==null?void 0:c.metadata,alternateLocators:p}}escapeSelector(r){var i;return(i=r==null?void 0:r.replaceAll("'","\\'"))==null?void 0:i.replaceAll(/\\/g,"\\\\")}};e(out,"SingleTestCode");var Qre=out;g6();var AYi=1e3,xYi=3e4,JBr=class JBr{constructor(r,i,s,c,p,_,v,E,D,w){this.config=r;this.checksumRoot=i;this.pageInteractor=s;this.apiService=c;this.userStoryService=p;this.actionsManager=_;this.testAssetsManager=v;this.webDriver=E;this.evaluatorService=D;this.internalFilesDir=w;this.executeAction=e(async({data:r,id:i,options:s,withPageInteractor:c=!1})=>{try{r.selector=void 0,r.executed=!1;let p=r.eventCode==="custom_code";r.thought="";let _=s.forceUpdateTimestamp?{id:i,timestamp:p?Date.now():void 0}:void 0,v=(()=>{if(s.timeout>=0)return s.timeout;if(s.singlePlay)return r.eventCode==="navigation"?xYi:AYi})();if(c?await this.performActionWithPageInteractor(r,v):await this.performActionWithEvaluation(r,v),_&&!p&&(_.timestamp=Date.now(),!["login","navigation","keystroke","wait","switch_tab","logout_and_login"].includes(r.eventCode))){let D=await this.webDriver.tmFrame.evaluate(w=>window.checksum.timeMachine.sessionReplayer.getLastInteractionEventTimestamp(w),_.timestamp);_.timestamp=Math.max(D??0,s.runStartedAt)}return{data:_,success:!0,message:"Action has been executed successfully"}}catch(p){throw Yp.error(`Error: ${p.message.slice(0,200)}`),new Error(p.message||p)}},"executeAction")}setPage(r){this.page=r}async performActionWithEvaluation(r,i){let s=r.codeValue??Qre.generateSingleActionCode(r,{noFallbacks:!0,generateAssertionsCode:!1,actionOptions:i?{timeout:i}:void 0});await this.evaluatorService.execute(s,void 0,void 0,{stepId:r.id})}async performActionWithPageInteractor(r,i){await this.pageInteractor.performAction(r,{useLocator:!0,timeout:i,monitorFlashingHTML:!1})}async uploadFiles(r){return r.map(({data:s,fileName:c})=>{let p=`${this.testAssetsManager.getLocalAutoSavePath()}/files`;return dwn(s,c,p,this.internalFilesDir),`${p}/${c}`})}async login(r,{role:i,environment:s}){await hye({config:this.config,folder:this.checksumRoot,throwIfEnvInfoInvalid:!0})(r,{role:i,environment:s}),this.didLogin=!0}async performLogin({role:r,environment:i}){return this.login(this.webDriver.appMainFrame.page(),{role:r,environment:i})}async addInitialLoginAction(){this.actionsManager.addAction({thought:"Log into application",eventCode:"login",id:(0,VBr.randomUUID)(),isInitialAction:!0,login:{role:this.userStoryService.getStory().environment.userRole,environment:this.userStoryService.getStory().environment.name},codeContext:{frameTargetName:null}})}async addStartURLNavigationAction(){var i;let r=(i=this.userStoryService.getStory())==null?void 0:i.url;r&&this.actionsManager.addAction({thought:"Navigate to start URL",eventCode:"navigation",isInitialAction:!0,id:(0,VBr.randomUUID)(),fillValue:r,codeContext:{frameTargetName:null}})}hasLoggedIn(){return this.didLogin}};e(JBr,"VtgActionsService");var kOt=JBr;iS();var zBr=class zBr{constructor(r,i={},s=!0){this.requests=[];this.watcherConfig={minimumWaitTime:250,maximumWaitTime:1e4,followingRequestsWaitTime:250};this.resolved=!0;this.hasMinimumWaitTimePassed=!1;this.useLog=!1;this.logStack=[];this.resolve=e(()=>{this.resolved||(this.resolved=!0,clearTimeout(this.minimumWaitTimer),clearTimeout(this.maximumWaitTimer),clearTimeout(this.followingRequestWaitTimeoutId),this.loadResolve({totalTime:Date.now()-this.startTS,logs:this.logStack,pendingRequests:this.requests.length,totalRequests:this.observedRequestsCount}))},"resolve");this.watcherConfig={...this.watcherConfig,...i},this.initListeners(r),this.useLog=s}initListeners(r){r.on("request",i=>{var s;this.hasMinimumWaitTimePassed||(s=this.watcherConfig.whitelist)!=null&&s.length&&!this.watcherConfig.whitelist.some(c=>c.test(i.url()))||(this.useLog&&this.logStack.push(`${i.method()} ${i.url().substring(0,60)}`),this.requests.push(i),this.observedRequestsCount+=1)}),r.on("response",i=>{this.requests=this.requests.filter(s=>s!==i.request()),this.hasMinimumWaitTimePassed&&(this.requests.length||(clearTimeout(this.followingRequestWaitTimeoutId),this.followingRequestWaitTimeoutId=setTimeout(()=>{this.requests.length||this.resolve()},this.watcherConfig.followingRequestsWaitTime)))})}async wait(){return new Promise(r=>{this.loadResolve=r,this.resolved=!1,this.minimumWaitTimer=setTimeout(()=>{this.hasMinimumWaitTimePassed=!0,this.requests.length||this.resolve()},this.watcherConfig.minimumWaitTime),this.maximumWaitTimer=setTimeout(this.resolve,this.watcherConfig.maximumWaitTime)})}startListening(){this.requests=[],this.startTS=Date.now(),this.hasMinimumWaitTimePassed=!1,this.observedRequestsCount=0,this.useLog&&(this.logStack=[])}};e(zBr,"NetworkWatcher");var IOt=zBr;var xwn=require("crypto");iS();RRe();Rte();g6();var bYi=e(n=>({...n.fillValue&&{value:n.fillValue},...n.selector&&{selector:n.selector},type:ZYr[n.eventCode],id:n.id,files:[]}),"webPageActionToNextAction"),HBr=class HBr{constructor(r,i,s){this.actionsManager=r;this.apiService=i;this.userStoryService=s}clear(){this.remoteSessionId=void 0}async init({retriesLeft:r=3,keepActionsWithoutDescription:i=!1,lastActionId:s=void 0}={}){let{goal:c,instructions:p}=this.userStoryService.getStory(),_=this.actionsManager.actions??[];if(s){let D=_.findIndex(({id:w})=>w===s);D===-1&&Yp.error(`[init] No action with id ${s} was found in executed actions`),_=_.slice(0,D+1)}i||(_=_.filter(D=>!!D.thought));let v={previous:_.map(D=>({thought:D.thought,action:bYi(D)}))},E={type:"test-generation",storyTitle:c,storyInstructions:p,testId:void 0,testSuiteId:void 0,thoughtsAndActions:v};try{let D=await this.apiService.post("ai-fallback/init",{data:E,format:"json"}),{sessionId:w}=await D.json();this.remoteSessionId=w}catch(D){if(Yp.error(D),await lb(2e3),r>0)return this.init({retriesLeft:r-1,keepActionsWithoutDescription:i});throw D}}};e(HBr,"VtgAiSessionBaseService");var j6e=HBr;g6();var WBr=class WBr extends j6e{constructor(i,s,c,p,_,v){super(p,_,v);this.webDriver=i;this.pageInteractor=s;this.actionsService=c;this.actionsManager=p;this.apiService=_;this.userStoryService=v;this.previousActionFailed=!1;this.currentChecksumId="0";this.executeAction=e(async({data:i,options:s={isAISuggestion:!0}})=>{await this.webDriver.clearHighlights(),this.previousActionFailed=!1;let c;try{let p=new IOt(this.webDriver.appMainFrame.page());p.startListening(),c=await this.actionsService.executeAction({data:i,id:i.id,options:s}),await p.wait(),await lb(2e3)}catch(p){throw this.previousActionFailed=!0,Yp.error(p),new Error(p)}return s.valueChanged&&await this.init(),c},"executeAction")}async init({keepActionsWithoutDescription:i}={keepActionsWithoutDescription:!0}){return this.clear(),super.init({keepActionsWithoutDescription:i})}clear(){super.clear(),this.previousActionFailed=!1,this.currentChecksumId="0"}async iterate({guidance:i}={}){await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1);let{reducedHTML:s,flashingHTML:c,elementsForNodeInterpretation:p,currentChecksumId:_}=await this.webDriver.evaluateWithChecksum(async({appRules:v,currentChecksumId:E})=>window.checksum.testGenerator.reduceHTML(v,{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:E}),{appRules:{appSpecificInteractableElementsSelectors:[]},currentChecksumId:this.currentChecksumId});this.currentChecksumId=_;try{let v=await this.getNextAction({reducedHTML:s,flashingHTML:c,elementsForNodeInterpretation:p,guidance:i}),D={...await this.pageInteractor.translateActionResponseToAgentPotentialAction(v),id:(0,xwn.randomUUID)(),timestamp:Date.now()};return await this.webDriver.highlightElementByLocator(this.pageInteractor.makeLocator(D.selector,D.parentFramesSelectors),D.clickOffset,"10px solid rgba(255,0,0,1)",!0),D}catch(v){Yp.error("error in ai iterate",v)}}async stop(){}async getNextAction({reducedHTML:i,flashingHTML:s,elementsForNodeInterpretation:c,guidance:p}){let _={reduction:{reducedHTML:i,flashingHTML:s,elementsForNodeInterpretation:c},currentURL:this.webDriver.appMainFrame.url(),previousActionOverview:{success:!this.previousActionFailed,userCorrection:p}};try{return await(await this.apiService.post("ai-fallback/iterate",{sessionId:this.remoteSessionId,iterationData:_})).json()}catch(v){throw console.error(v),v}}};e(WBr,"VtgAITestGenerationService");var FOt=WBr;oNr();dCe();var bye=require("@playwright/test"),sOr=H0(fut());iS();var aOr=class aOr{constructor(r){this.options=r;this.harData={methodIndex:{GET:0,POST:0,PUT:0,DELETE:0}};this.interceptors={recordHar:this.harInterceptor.bind(this),completeOriginHeader:this.completeOriginHeaderInterceptor.bind(this)};this.intercept=e(async(r,i,s,c)=>{let p=c??this.options,_=[],v=e(E=>{if(E)switch(E.type){case"abort":return r.abort(E.errorCode);case"fulfill":return r.fulfill(E.fulfillOptions);default:case"continue":_.push(E)}},"processResult");for(let[E,D]of Object.entries(this.interceptors))if(p[E]){let w=v(await D(r,i,s));if(w)return w}return this.applyContinueResults(r,_)},"intercept")}setOptions(r){this.options=r}mergeOptions(r){this.options={...this.options,...r}}applyContinueResults(r,i){let s=i.filter(p=>!!p),c={};return s.forEach(p=>{p.options&&(p.options.headers&&(c.headers={...c.headers,...p.options.headers}),p.options.method&&(c.method=p.options.method),p.options.postData&&(c.postData=p.options.postData),p.options.url&&(c.url=p.options.url))}),r.continue(c)}async harInterceptor(r){let i=r.request().headers(),s=r.request().method();return i["Checksum-Id"]=(++this.harData.methodIndex[s]).toString(),{options:{headers:i}}}async completeOriginHeaderInterceptor(r,i,{page:s}){if(i.resourceType()==="document")return;let c=r.request().headers();if(!c.Origin&&!c.origin){try{let p=new URL(s.url()).origin;c.origin=p,c.Origin=p}catch{}return{options:{headers:c}}}}};e(aOr,"RouteInterceptors");var tqe=aOr;PSr();BRe();M1r();var oOr=class oOr{constructor(r={},i={},s=new LRe,c=void 0){this.framesMessageBroker=s;this.context=c;this.browserConfig={devtools:!1,executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH??void 0};this.options={fullScreenResolution:!1,disableWebSecurity:!0};this.contextClosePromise=void 0;this.eventListeners=[];this.lastSnapshot={selector:void 0,eventCode:void 0};this.snapshotTimeout=3e4;this.cacheScript=!1;this.pagesIndexToGuid={};this.onRequestFinished=e(async r=>{try{let i=await r.response();if(!i.ok())return;let s=r.resourceType(),c=r.url(),p=e(async()=>{try{return await i.text()}catch{try{return await(await fetch(c)).text()}catch{return}}},"getBody");if(["document","script","stylesheet"].includes(s))try{let _=await p();if(!_)return;let v={url:c,source:_,type:s};await this.forEachEventListener(E=>{var D;return(D=E.onWebDriverResourceLoaded)==null?void 0:D.call(E,v)})}catch(_){console.error("[WebDriver] requestfinished event handler error",s,c,_)}}catch(i){console.error("[WebDriver] requestfinished event handler error",i)}},"onRequestFinished");this.onFrameNavigated=e(async r=>{let i=e(async s=>{await this.forEachEventListener(c=>{var p;return(p=c.onWebDriverFrameNavigated)==null?void 0:p.call(c,r,s)})},"notifyFrameNavigated");await i(!1),await this.injectedScriptManager.onFrameNavigated(r),await i(!0)},"onFrameNavigated");this.tracing=!1;this.tracingChunk=!1;this.chunkIndex=0;var p;if(this.options={...this.options,...r},this.browserConfig={...this.browserConfig,...i},this.injectedScriptManager=new Tje(this.options),this.browserConfig.args||(this.browserConfig.args=[]),this.options.disableWebSecurity&&this.browserConfig.args.push("--disable-web-security"),this.options.allowFileAccess&&this.browserConfig.args.push("--allow-file-access-from-files"),this.browserConfig.args.push("--disable-site-isolation-trials"),this.browserConfig.args.push("--allow-running-insecure-content"),this.options.remoteDebugging&&this.browserConfig.args.push(`--remote-debugging-port=${this.options.remoteDebuggingPort??"9222"}`),this.options.forceHeadless&&(this.browserConfig.headless=!0,this.browserConfig.devtools=!1),this.options.useProxy)if((p=this.options.webProxy)!=null&&p.server){console.log("[WebDriver] using proxy");let{server:_,username:v,password:E}=this.options.webProxy;this.browserConfig.proxy={server:_,username:v,password:E},this.browserConfig.args.push("--proxy-bypass-list=localhost,127.0.0.1")}else console.error("[WebDriver] useProxy=true but proxy not configured");this.routeInterceptor=new tqe({completeOriginHeader:this.options.completeOriginHeader,recordHar:this.options.recordHAR})}async prepare({storageState:r,baseURL:i,shutdown:s=!0}={}){s&&await this.shutdown();let c={};if(c.bypassCSP=!0,c.ignoreHTTPSErrors=!0,c.baseURL=i??this.options.baseURL,this.options.timezoneId&&(c.timezoneId=this.options.timezoneId),this.options.viewport?c.viewport=this.options.viewport:this.options.fullScreenResolution?c.viewport={width:1280,height:720}:this.options.hostWindowViewport&&(c.deviceScaleFactor=void 0,c.viewport=null),r&&(c.storageState=r),this.context)this.browser=this.context.browser();else if(this.options.useStealth){let p=require("puppeteer-extra-plugin-stealth");sOr.chromium.use(p()),this.browser=await sOr.chromium.launch(this.browserConfig)}else this.browser=await bye.chromium.launch(this.browserConfig);return this.context||(this.context=await this.browser.newContext(c)),this.options.defaultTimeout&&this.context.setDefaultTimeout(this.options.defaultTimeout),this.options.defaultNavigationTimeout&&this.context.setDefaultNavigationTimeout(this.options.defaultNavigationTimeout),this.context.on("page",async p=>{await this.onNewPage(p),await this.onFrameNavigated(p.mainFrame()),p.on("framenavigated",this.onFrameNavigated)}),this.context.on("close",async()=>{this.contextClosePromise=this.forEachEventListener(p=>{var _;return(_=p.onWebDriverContextClose)==null?void 0:_.call(p)})}),this.activePage=await this.createPage(),this.options.trackLoadedResources&&this.page.on("requestfinished",this.onRequestFinished),this.options.useCDPSession&&(this.cdpSession=await this.context.newCDPSession(this.originalPage)),!0}getContext(){return this.context}get frameMsgBroker(){return this.framesMessageBroker}async createPage(){return this.originalPage=await this.context.newPage(),this.originalPage}async onNewPage(r){}async applyRouteInterceptors(r,i){try{await(r==null?void 0:r.route("**/*",async(s,c)=>this.routeInterceptor.intercept(s,c,{page:r},i)))}catch(s){console.error("[WebDriver] applyRouteInterceptors error",s)}}switchActivePage(r){let i=this.context.pages().find(s=>nw(s)===r);return!i||i.isClosed()?(console.error(`[WebDriver] Page with guid ${r} not found or has been closed.`),!1):(this.previousPage=this.activePage,this.activePage=i,!0)}getDefaultTimeout(){return this.options.defaultTimeout}getDefaultNavigationTimeout(){return this.options.defaultNavigationTimeout}async addHARMockAPIRecordings(r){if(!this.activePage){console.warn("[addHARMockAPIRecordings] Active page is not set, skipping HAR recording.");return}await this.activePage.routeFromHAR(r,{url:/^(?!.*\.(js|mjs|ts|jsx|tsx|css|jpg|jpeg|png|gif|svg|webp|heif|heic|raw|cr2|nef|arw|bmp|tiff|tif|ico|woff|woff2|ttf|otf|doc|docx|pdf|ws|wasm|mp3|wav|aac|flac|mp4|avi|mov|wmv|flv|zip|rar|7z|tar\.gz|xml|html|py|java|cpp|xls|xlsx|ppt|pptx|gif)$)/i,update:!0,updateMode:"minimal"})}forEachEventListener(r){return Promise.all(this.eventListeners.map(async i=>{try{await r(i)}catch(s){console.log("WebDriver/forEachEventListener exception",s)}}))}registerEventListener(r){this.eventListeners.push(r)}async getScript(){async function r(i){let{exec:s}=require("child_process");return new Promise((c,p)=>{s(i,_=>{_?(console.log("error executing cmd, ",_),p(_)):c()})})}switch(e(r,"execCmd"),this.options.scriptSource){case"file":return this.options.scriptFile;case"url":if(this.cacheScript)return this.options.scriptFile;try{return await r(`curl -o ${this.options.scriptFile} '${this.options.scriptURL}'`),this.options.scriptFile}catch(i){console.log("[web-driver] Failed fetching frontend script",i)}break}}async startJSCoverageTracking(){return await this.page.coverage.startJSCoverage(),[];return await this.cdpSession.send("Debugger.enable"),await this.cdpSession.send("Profiler.enable"),await this.cdpSession.send("Profiler.startPreciseCoverage",{callCount:!1,detailed:!0}),this.getCurrentJSCoverage()}stopJSCoverageTracking(){return this.page.coverage.stopJSCoverage()}async getCurrentJSCoverage(){let r=await this.page.coverage.stopJSCoverage();return await this.page.coverage.startJSCoverage(),r;return(await this.cdpSession.send("Profiler.takePreciseCoverage")).result}async startCSSCoverageTracking(){return await this.cdpSession.send("DOM.enable"),await this.cdpSession.send("CSS.enable"),await this.cdpSession.send("CSS.startRuleUsageTracking"),this.getCurrentCSSCoverage()}async getCurrentCSSCoverage(){return(await this.cdpSession.send("CSS.takeCoverageDelta")).coverage}getCDPSession(){return this.cdpSession}async navigate(r){return this.page.goto(r)}async setViewportSize(r,i){return this.page.setViewportSize({width:r,height:i})}async getStorageState(){return this.page.context().storageState()}async shutdown(){try{this.page&&(await this.page.close(),this.activePage=void 0),this.context&&(await this.context.close(),this.context=void 0),this.browser&&(await this.browser.close(),this.browser=void 0)}catch(r){console.warn("[WebDriver] shutdown error",r)}}async wrapWithBrowserLogs(r,{disabled:i=!1,onErrorOnly:s=!1}={}){if(i)return r();let c=[],p=e(E=>{c.push(E.text())},"log");this.page.on("console",p);let _,v;try{v=await r()}catch(E){_=E}if(this.page.off("console",p),(!s||_)&&console.log("browser console messages:",c),_)throw _;return v}async takeElementSnapshot(r,i,s={},c={}){if(r===this.lastSnapshot.selector&&i===this.lastSnapshot.eventCode)return{};if(!r)return{};try{let{snapshot:p,elementLocator:_}=await this.takeSnapshot(r,c,{frameLocatorSelector:s.frameLocatorSelector});return this.lastSnapshot={selector:r,eventCode:i},{snapshot:p,elementLocator:_}}catch(p){return console.error("takeElementSnapshot error",p),{}}}getScreenshotTimeout(r=!1){return r?this.snapshotTimeout:this.snapshotTimeout+5e3}async takePageSnapshot(r){let i=this.page.screenshot({...r,timeout:this.getScreenshotTimeout()});return await Promise.race([i,lb(this.getScreenshotTimeout(!0))])}async takeSnapshot(r,i,{frameLocatorSelector:s}={}){let c=s?this.page.frameLocator(s).locator(r):this.page.locator(r),p=c.screenshot({...i,timeout:this.getScreenshotTimeout()});return{snapshot:await Promise.race([p,lb(this.getScreenshotTimeout(!0))]),elementLocator:c}}async getCurrentURL(){return this.page.url()}async getClientScreenResolution(){return await this.page.evaluate(async()=>({width:window.screen.width,height:window.screen.height}))}async awaitContextClose(){return this.contextClosePromise||await lb(100),this.contextClosePromise}get page(){return this.activePage}getPage(){return this.activePage}startPlaywrightTrace(){return this.tracing=!0,this.context.tracing.start({name:"trace",screenshots:!0,snapshots:!0})}startPlaywrightTraceChunk(){return this.tracingChunk=!0,this.context.tracing.startChunk({name:`trace-chunk-${this.chunkIndex}`})}stopPlaywrightTraceChunk(r){return this.tracingChunk=!1,this.context.tracing.stopChunk({path:`${r.replace(".zip",`.${this.chunkIndex++}.zip`)}`})}stopPlaywrightTrace(r){return this.tracing=!1,this.context.tracing.stop({path:r})}isTracing(){return this.tracing}isTracingChunk(){return this.tracingChunk}};e(oOr,"WebDriver");var POt=oOr;g6();var NOt=require("perf_hooks");var cOr=class cOr{constructor(r,i,s,c,p){this.timeMachine=r;this.actionsManager=i;this.apiService=s;this.remoteSessionId=c;this.options=p}rewriteLastActionThought(r){throw new Error("Method not implemented.")}async generateReductionPromptData(r,i){let s=this.getActionTimestamps(r,i);if(!s)return;let c=await this.timeMachine.executeReducedHTMLTask(s.before),p=await this.timeMachine.executeReducedHTMLTask(s.after);return{previousReducedHTML:c,reducedHTML:p,timestamp:s.after}}async generatePromptData(r,i,s){if(this.promptData)return{...this.promptData,assertionsData:i};let c=this.getActionTimestamps(r,s);if(!c)return;let p=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after);return this.promptData={reduction:{reducedHTML:_,flashingHTML:[]},currentURL:"",previousReducedHTML:p,previousURL:"",actionId:r,assertionsData:i,timestamp:c.after},this.promptData}async generateThoughtPromptData(r,i){let s=await this.generateReductionPromptData(r,i.timestamp);if(!s)return;let c=this.actionsManager.actions.findIndex(v=>v.id===r);if(c===-1){Yp.error(`Action with id ${r} not found`);return}let p=this.actionsManager.actions[c],_=this.actionsManager.actions[c-1];return{...s,action:p,previousAction:_,assertion:i}}async callApi(r,i,s,c){let p=NOt.performance.now(),_=await this.generatePromptData(i,s,c);if(this.logPerformance(`- Generated prompt data for ${r}`,p),!_)return;p=NOt.performance.now();let v=await this.apiService.post(`assertions/${r}`,{sessionId:this.remoteSessionId,data:_});if(!v.ok){Yp.error(`Request for assertion generation ${r} failed with status ${v.status}`);return}let E=await v.json();return this.logPerformance(`- Received response for assertion generation ${r}`,p),E}async generateAssertions(r,i){try{let s=await this.callApi("generate",r,void 0,i);if(s)return s.timestamps=this.getActionTimestamps(r,i),s}catch(s){throw Yp.error(s),s}}async refactoringAssertions(r){try{return await this.callApi("refactor",r.actionId,r)}catch(i){throw Yp.error(i),i}}async filteringAssertions(r){try{return await this.callApi("filter",r.actionId,r)}catch(i){throw Yp.error(i),i}}getVariables(){return[]}getVariablesString(r){return""}getActionTimestamps(r,i){let s=this.actionsManager.actions,c=s.findIndex(v=>v.id===r);if(c===-1){Yp.warning(`[init] No action with id ${r} was found in executed actions`);return}let p=s[c],_=s[c+1];return{before:p.timestamp,after:(_==null?void 0:_.timestamp)??i}}logPerformance(r,i){this.options.logPerformance&&Yp(`${r} in`,NOt.performance.now()-i,"ms")}};e(cOr,"AssertionsAgent");var rqe=cOr;aw();g6();O1e();var Bwn=require("crypto"),Eye=require("perf_hooks");var uOr=class uOr extends j6e{constructor(i,s,c,p,_,v,E){super(i,s,c);this.actionsManager=i;this.apiService=s;this.userStoryService=c;this.timeMachine=p;this.webDriver=_;this.evaluationService=v;this.options=E;this.activeRemoteSessionIdByActionId=new Map}async init({retriesLeft:i=3,keepActionsWithoutDescription:s=!1,lastActionId:c=void 0}={}){await super.init({retriesLeft:i,keepActionsWithoutDescription:s,lastActionId:c}),this.activeRemoteSessionIdByActionId.set(c,this.remoteSessionId)}async generateAiAssertions({id:i,startedAt:s,processId:c}){this.options.logPerformance&&Yp.info(`generateAiAssertions for action ${i}`);let p=e(async(_=[],v=!1)=>{try{let E=_.map((D,w)=>({...D,id:(0,Bwn.randomUUID)(),source:"ai",verified:!0,actionId:i})).filter(D=>{var w;return!["withChecksumAI()","withChecksumAI"].includes(D.matcher)&&!((w=D.usedVariablesNames)!=null&&w.length)});return Yp.info(`Returned assertions results (${c})`,_.map(({matcher:D,thought:w,locator:B})=>({matcher:D,thought:w,locator:B}))),await this.webDriver.page.evaluate(({assertions:D,actionId:w,error:B,processId:N})=>{window.vtg.onAsyncProcessResponse({actionId:w,assertions:D,error:B,processId:N})},{assertions:E,actionId:i,error:v,processId:c}),E}catch(E){return Yp.error("Error in AI assertions generation",E),[]}},"sendResultToVTGWithoutUnsupported");try{if(this.isRunning(i))return Yp.warning("Already generating assertions for this action"),await p();let _=Eye.performance.now();if(await this.init({keepActionsWithoutDescription:!0,lastActionId:i}),this.logPerformance(`init for action ${i}`,_),!this.isRunning(i))return await p();let v=new rqe(this.timeMachine,this.actionsManager,this.apiService,this.remoteSessionId,this.options),E=await this.generateAssertions(v,i,s);if(!E||!this.isRunning(i))return await p();if(E.assertions.length===0){let{smartAssertion:D}=E;return D?(D.isSelected=!0,await p([D])):await p()}return Hd.vtg.aiAssertions.allowRefactoring&&(E=await this.refactoringAssertions(v,E)),this.isRunning(i)?(Hd.vtg.aiAssertions.allowFiltering?E=await this.filteringAssertions(v,E):E.assertions=E.assertions.map(D=>({...D,isSelected:D.isValid})),this.isRunning(i)?(this.logPerformance(`---------------- Overall - Generated assertions for action ${i} in`,_),await p(vwn(E))):await p()):await p()}catch(_){return Yp.error("Error in AI assertions generation",_),await p([],!0)}finally{this.activeRemoteSessionIdByActionId.delete(i)}}stopGenerateAiAssertions(i){this.activeRemoteSessionIdByActionId.delete(i)}isRunning(i){return this.activeRemoteSessionIdByActionId.has(i)}async generateAssertions(i,s,c=void 0){let p=Eye.performance.now(),_=p,v=await i.generateAssertions(s,c);if(this.logPerformance(`- generateAssertions for action ${s}`,p),!!v)return p=Eye.performance.now(),await this.setSelectionDataForAssertions(v),v.assertions=v.assertions.map(ywn),this.logPerformance(`- setSelectionData for action ${s}`,p),p=Eye.performance.now(),await this.validateAssertions(v.assertions,v.timestamps,i),this.logPerformance(`- validate assertions for action ${s}`,p),this.logPerformance(`Overall - Generated assertions for action ${s}`,_),v}async refactoringAssertions(i,s){let c=Eye.performance.now(),p=c;try{this.options.logPerformance&&Yp.info(`Refactoring assertions for action ${s.actionId}`),s=await i.refactoringAssertions(s),this.logPerformance(`- refactoringAssertions for action ${s.actionId}`,c),c=Eye.performance.now(),await this.validateAssertions(s.assertions,s.timestamps,i),this.logPerformance(`- validate assertions after refactoring for action ${s.actionId}`,c),this.logPerformance(`Overall - Refactored assertions for action ${s.actionId}`,p)}catch(_){Yp.error("[refactoringAssertions] Error in assertions refactoring",_)}return s}async filteringAssertions(i,s){try{let c=Eye.performance.now();this.options.logPerformance&&Yp.info(`Filtering assertions for action ${s.actionId}`);let p=await i.filteringAssertions(s);return this.logPerformance(`Overall - filteringAssertions for action ${s.actionId}`,c),p}catch(c){Yp.error("[filteringAssertions] Error in assertions filtering",c)}}async executeAssertion(i,s){let c=bye.expect.configure({timeout:500}),p=sut(i);await this.evaluationService.execute(p,{expect:c,page:s},{frame:"task-time-machine",expectConfig:{timeout:500}})}async validateLocatorMappedToCorrectRrwebId(i,s,c){if(i.locatorMappedToCorrectRrwebId)return;if(!await this.isLocatorMappedToCorrectRrwebId(i,s,c))return i.locatorMappedToCorrectRrwebId=!1,this.handleAssertionValidityError(new Error(`Locator not mapped to correct rrweb id for assertion: ${i.matcher}`),i,"locator not mapped to correct rrweb id")}async validateAssertionOnPreviousState(i,s,c){try{let p=await this.getLocatorsForLocatorString(i,s,c);if(p.length===0){if(qBr(i)&&!i.appliedBeforeAction)throw new Error(`Element not found before action for assertion: ${i.matcher}`);return}await Promise.all(p.map(async _=>{let v={...i,locator:_.toString(),matcher:i.appliedBeforeAction?i.matcher:eqe.getOppositeMatcherClause(i.matcher)};await this.executeAssertion(v,s)}))}catch(p){this.handleAssertionValidityError(p,i,i.appliedBeforeAction?"didn't apply BEFORE the action was executed and it should have":"applied BEFORE the action was executed and it shouldn't have")}}async validateAssertionOnCurrentState(i,s){try{await this.executeAssertion(i,s.frameLocator("iframe"))}catch(c){this.handleAssertionValidityError(c,i,"didn't apply AFTER the action")}}async getLocatorRrwebIds(i,s,c){let p=await this.getLocatorsForLocatorString(i,s,c);return await Promise.all(p.map(_=>_.evaluate(v=>v._rrwebid)))}async getLocatorsForLocatorString(i,s,c){if(TOt(i))return[];let p=i.locator;if(!p)return[];let _=s.frameLocator("iframe"),v=`return ${$Br(i)}`;try{return await(await this.evaluationService.getLocator(v,_)).all()}catch(E){return Yp.error(`Error getting Locator[] for assertion with locator: ${p}`,v,E.message),[]}}async isLocatorMappedToCorrectRrwebId(i,s,c){if(TOt(i))return!0;let p=await this.getLocatorRrwebIds(i,s,c);return p.length!==1?!1:p[0]===i.rrwebid}async validateAssertions(i,s,c){let p=i.filter(_=>_.isValid===void 0&&!TOt(_));await this.executeValidationTasksOnState(p,s,c,{isPreviousState:!0}),p=p.filter(_=>_.isValid===void 0),await this.executeValidationTasksOnState(p,s,c,{isPreviousState:!1}),p.forEach(_=>{_.isValid??(_.isValid=!0)})}async setSelectionDataForAssertions(i){let s=e(_=>{var v;return(v=_.matcher)==null?void 0:v.startsWith("toBeHidden")},"shouldGetSelectionDataFromPreviousState"),[c,p]=i.assertions.reduce(([_,v],E)=>(s(E)?_.push(E):v.push(E),[_,v]),[[],[]]);await this.setSelectionDataForAssertionsInTimestamp(c,i.timestamps.before),await this.setSelectionDataForAssertionsInTimestamp(p,i.timestamps.after)}async setSelectionDataForAssertionsInTimestamp(i,s){if(!(!i||i.length===0))return this.timeMachine.executeTask(async c=>{await Promise.all(i.map(p=>this.setSelectionData(p,c)))},s,{name:"setSelectionDataForAssertionsInTimestamp"})}async executeValidationTasksOnState(i,s,c,{isPreviousState:p}){let _=p?"validateAssertionOnPreviousState":"validateAssertionOnCurrentState",v=(p?this.validateAssertionOnPreviousState:this.validateAssertionOnCurrentState).bind(this),E=p?s.before:s.after;await this.timeMachine.executeTask(async D=>{for(let w of i){let B=qBr(w)===p;!w.locatorMappedToCorrectRrwebId&&B&&await this.validateLocatorMappedToCorrectRrwebId(w,D,c),await v(w,D,c)}},E,{name:_})}async setSelectionData(i,s){if(!i.rrwebid||i.locator)return;let c;try{let p=await s.evaluate(_=>window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(_,{ignoredIframesSelectors:["iframe"],fromTimeMachine:!0}),parseInt(i.rrwebid,10));if(p){Object.assign(i,p,{locatorMappedToCorrectRrwebId:!0});return}else c=new Error("Inspected element result is undefined")}catch(p){c=p}i.locatorMappedToCorrectRrwebId=!1,this.handleAssertionValidityError(c,i,"invalid locator")}logPerformance(i,s){this.options.logPerformance&&Yp.info(`${i} in ${Eye.performance.now()-s} ms`)}handleAssertionValidityError(i,s,c){let p=i.message.split(`
1731
+ })`:c;return v?`, ${D}`:D}let E=this.buildClickActionOptionsObject(r);return this.makeOptions({...i,...E,...p},v)}buildFillValue(r){return Array.isArray(r)?`[${r.map(this.buildFillValue.bind(this)).join(", ")}]`:typeof r=="object"?`{ ${Object.entries(r).map(([i,s])=>`${i}: ${this.buildFillValue(s)}`).join(", ")} }`:typeof r=="string"?oke(r):r}buildActionCode(r,i,s){let{eventCode:c,unevaluatedFillValue:p,dropTarget:_,files:v,switchToTab:E,userRole:D,canvas:w,nativeDialog:B,codeContext:N}=r,L=this.buildFillValue(p),M=eXr[c],V=this.getOptionsString(r,s),Z=(N==null?void 0:N.frameTargetName)??"page";switch(c){case"navigation":return[`${i}.${M}(${this.formatURL(p)}${V})`];case"drag_and_drop":return[`${i}.${M}(${this.buildLocatorChain(Z,_.locator,_.locatorWithVars,_.parentFramesSelectors,_.selector,_.selectorWithVars)}${V})`];case"click":case"double_click":case"check":case"uncheck":case"hover":return[`${i}.${M}(${V})`];case"input":case"selectoption":case"keystroke":return[`${i}.${M}(${L}${V})`];case"click_and_type":return[`${i}.click(${V})`,`${i}.pressSequentially(${L}${V?`, ${V}`:""})`];case"clear_and_type":return[`${i}.clear(${this.makeOptions(s)})`,`${i}.pressSequentially(${L}${V?`, ${V}`:""})`];case"custom_code":return[p];case"wait":return[`${i}.${M}(${p||1e3}${V})`];case"upload_files":return v!=null&&v.length||console.warn("Input files are required for SetInputFiles event code"),[`${i}.${M}(page.resolveAssetsFolder(["${v.join('", "')}"])${V})`];case"switch_tab":return[`page = ${i}.${M}(${E.index}${V})`];case"logout_and_login":return[`${i}.${M}("${D}")`];case"canvas_click":return[`${i}.${M}("${w.canvasText}"${w.rectSizeIndex?`, ${w.rectSizeIndex}`:""})`];case"native_accept":{let ue=B.dialogResult!=null&&(0,Awn.isString)(B.dialogResult)?`"${B.dialogResult}"`:"";return[`${i}.waitForDialog().then(async (${B.dialogType}) => {await ${B.dialogType}.accept(${ue})})`]}case"native_dismiss":return[`${i}.waitForDialog().then(async (${B.dialogType}) => {await ${B.dialogType}.dismiss()})`];case"login":return[this.makeLoginCode(r)];default:return[]}}buildLocatorChain(r,i,s,c,p,_,v){let E=this.addFrameSelectorsToLocatorChain(r,c),D=this.addFrameSelectorsToLocatorChain("page",c);if(v){let w=this.buildCompoundSelectorLocatorChain(E,v);if(w)return w}return s?E+=`.${P8t(s,D)}`:_?E+=`.locator('${this.escapeSelector(_)}')`:i?E+=`.${P8t(i,D)}`:p&&(E+=`.locator('${this.escapeSelector(p)}')`),E}addFrameSelectorsToLocatorChain(r,i){return(i??[]).reduce((s,c)=>`${s}.frameLocator('${this.escapeSelector(c)}')`,r)}buildCompoundSelectorLocatorChain(r,i){let s=e(c=>c.selection.type==="content"?`"${c.selection.value}"`:c.locator?`base.${c.locator}`:`base.locator('${this.escapeSelector(c.selector)}')`,"getElementSelector");try{return`${r}.compoundSelection((base) => [${i.contextElements.map(c=>s(c.element)).join(", ")}], (base) => ${i.targetRelativeSelector.locator?`base.${i.targetRelativeSelector.locator}`:`base.locator('${this.escapeSelector(i.targetRelativeSelector.selector)}')`}).first()`}catch(c){console.error("Error building compound selector locator chain",c);return}}formatURL(r){let i=this.resolveRelativeURL(r);return oke(decodeURIComponent(i))}resolveRelativeURL(r){if(!r)return"";if(r.startsWith("/"))return r;let i;try{i=new URL(r)}catch(_){if(_ instanceof TypeError)return r;throw _}if(!this.options.environment.baseURL)return r;let s=new URL(this.options.environment.baseURL),c=e(_=>_.replace(/^www\./,""),"normalizeHostname");return!s||s.protocol!==i.protocol||c(s.hostname)!==c(i.hostname)||!i.pathname.startsWith(s.pathname)?r:i.pathname.substring(s.pathname.length).replace(/\/$/,"").replace(/^(?!\/)/,"/")+i.search+i.hash}addVariable(r){this.test.usingVariableStore=!0,this.addCode(nXr([r],{onlyValueExpression:!0}))}addAssertion(r){this.addCode(this.assertionGenerator.generateAssertionCode(r))}addCode(r){Array.isArray(r)||(r=[r]),r.forEach(i=>{if(!i)return;let s=i.trimEnd();s.endsWith(";")||(s+=";"),this.test.lines.push({type:0,content:s})})}addFunction(r){this.test.lines.push({type:0,content:r})}addComment(r){this.test.lines.push({type:1,content:`/* ${r} */`})}getTestMetadata(){return this.test}createFallbackMarkupForSelector(r,i=[],s,c,p){let _=(i||[]).concat(this.test.fallbackMarkups.map(E=>E.id)),v;do v=F8t(5);while(_.indexOf(v)>-1);return{id:v,selector:r,esraMetadata:s,compoundSelector:c==null?void 0:c.metadata,alternateLocators:p}}escapeSelector(r){var i;return(i=r==null?void 0:r.replaceAll("'","\\'"))==null?void 0:i.replaceAll(/\\/g,"\\\\")}};e(out,"SingleTestCode");var Qre=out;g6();var AYi=1e3,xYi=3e4,JBr=class JBr{constructor(r,i,s,c,p,_,v,E,D,w){this.config=r;this.checksumRoot=i;this.pageInteractor=s;this.apiService=c;this.userStoryService=p;this.actionsManager=_;this.testAssetsManager=v;this.webDriver=E;this.evaluatorService=D;this.internalFilesDir=w;this.executeAction=e(async({data:r,id:i,options:s,withPageInteractor:c=!1})=>{try{r.selector=void 0,r.executed=!1;let p=r.eventCode==="custom_code";r.thought="";let _=s.forceUpdateTimestamp?{id:i,timestamp:p?Date.now():void 0}:void 0,v=(()=>{if(s.timeout>=0)return s.timeout;if(s.singlePlay)return r.eventCode==="navigation"?xYi:AYi})();if(c?await this.performActionWithPageInteractor(r,v):await this.performActionWithEvaluation(r,v),_&&!p&&(_.timestamp=Date.now(),!["login","navigation","keystroke","wait","switch_tab","logout_and_login"].includes(r.eventCode))){let D=await this.webDriver.tmFrame.evaluate(w=>window.checksum.timeMachine.sessionReplayer.getLastInteractionEventTimestamp(w),_.timestamp);_.timestamp=Math.max(D??0,s.runStartedAt)}return{data:_,success:!0,message:"Action has been executed successfully"}}catch(p){throw Yp.error(`Error: ${p.message.slice(0,200)}`),new Error(p.message||p)}},"executeAction")}setPage(r){this.page=r}async performActionWithEvaluation(r,i){let s=r.codeValue??Qre.generateSingleActionCode(r,{noFallbacks:!0,generateAssertionsCode:!1,actionOptions:i?{timeout:i}:void 0});await this.evaluatorService.execute(s,void 0,void 0,{stepId:r.id})}async performActionWithPageInteractor(r,i){await this.pageInteractor.performAction(r,{useLocator:!0,timeout:i,monitorFlashingHTML:!1})}async uploadFiles(r){return r.map(({data:s,fileName:c})=>{let p=`${this.testAssetsManager.getLocalAutoSavePath()}/files`;return dwn(s,c,p,this.internalFilesDir),`${p}/${c}`})}async login(r,{role:i,environment:s}){await hye({config:this.config,folder:this.checksumRoot,throwIfEnvInfoInvalid:!0})(r,{role:i,environment:s}),this.didLogin=!0}async performLogin({role:r,environment:i}){return this.login(this.webDriver.appMainFrame.page(),{role:r,environment:i})}async addInitialLoginAction(){this.actionsManager.addAction({thought:"Log into application",eventCode:"login",id:(0,VBr.randomUUID)(),isInitialAction:!0,login:{role:this.userStoryService.getStory().environment.userRole,environment:this.userStoryService.getStory().environment.name},codeContext:{frameTargetName:null}})}async addStartURLNavigationAction(){var i;let r=(i=this.userStoryService.getStory())==null?void 0:i.url;r&&this.actionsManager.addAction({thought:"Navigate to start URL",eventCode:"navigation",isInitialAction:!0,id:(0,VBr.randomUUID)(),fillValue:r,codeContext:{frameTargetName:null}})}hasLoggedIn(){return this.didLogin}};e(JBr,"VtgActionsService");var kOt=JBr;iS();var zBr=class zBr{constructor(r,i={},s=!0){this.requests=[];this.watcherConfig={minimumWaitTime:250,maximumWaitTime:1e4,followingRequestsWaitTime:250};this.resolved=!0;this.hasMinimumWaitTimePassed=!1;this.useLog=!1;this.logStack=[];this.resolve=e(()=>{this.resolved||(this.resolved=!0,clearTimeout(this.minimumWaitTimer),clearTimeout(this.maximumWaitTimer),clearTimeout(this.followingRequestWaitTimeoutId),this.loadResolve({totalTime:Date.now()-this.startTS,logs:this.logStack,pendingRequests:this.requests.length,totalRequests:this.observedRequestsCount}))},"resolve");this.watcherConfig={...this.watcherConfig,...i},this.initListeners(r),this.useLog=s}initListeners(r){r.on("request",i=>{var s;this.hasMinimumWaitTimePassed||(s=this.watcherConfig.whitelist)!=null&&s.length&&!this.watcherConfig.whitelist.some(c=>c.test(i.url()))||(this.useLog&&this.logStack.push(`${i.method()} ${i.url().substring(0,60)}`),this.requests.push(i),this.observedRequestsCount+=1)}),r.on("response",i=>{this.requests=this.requests.filter(s=>s!==i.request()),this.hasMinimumWaitTimePassed&&(this.requests.length||(clearTimeout(this.followingRequestWaitTimeoutId),this.followingRequestWaitTimeoutId=setTimeout(()=>{this.requests.length||this.resolve()},this.watcherConfig.followingRequestsWaitTime)))})}async wait(){return new Promise(r=>{this.loadResolve=r,this.resolved=!1,this.minimumWaitTimer=setTimeout(()=>{this.hasMinimumWaitTimePassed=!0,this.requests.length||this.resolve()},this.watcherConfig.minimumWaitTime),this.maximumWaitTimer=setTimeout(this.resolve,this.watcherConfig.maximumWaitTime)})}startListening(){this.requests=[],this.startTS=Date.now(),this.hasMinimumWaitTimePassed=!1,this.observedRequestsCount=0,this.useLog&&(this.logStack=[])}};e(zBr,"NetworkWatcher");var IOt=zBr;var xwn=require("crypto");iS();RRe();Rte();g6();var bYi=e(n=>({...n.fillValue&&{value:n.fillValue},...n.selector&&{selector:n.selector},type:ZYr[n.eventCode],id:n.id,files:[]}),"webPageActionToNextAction"),HBr=class HBr{constructor(r,i,s){this.actionsManager=r;this.apiService=i;this.userStoryService=s}clear(){this.remoteSessionId=void 0}async init({retriesLeft:r=3,keepActionsWithoutDescription:i=!1,lastActionId:s=void 0}={}){let{goal:c,instructions:p}=this.userStoryService.getStory(),_=this.actionsManager.actions??[];if(s){let D=_.findIndex(({id:w})=>w===s);D===-1&&Yp.error(`[init] No action with id ${s} was found in executed actions`),_=_.slice(0,D+1)}i||(_=_.filter(D=>!!D.thought));let v={previous:_.map(D=>({thought:D.thought,action:bYi(D)}))},E={type:"test-generation",storyTitle:c,storyInstructions:p,testId:void 0,testSuiteId:void 0,thoughtsAndActions:v};try{let D=await this.apiService.post("ai-fallback/init",{data:E,format:"json"}),{sessionId:w}=await D.json();this.remoteSessionId=w}catch(D){if(Yp.error(D),await lb(2e3),r>0)return this.init({retriesLeft:r-1,keepActionsWithoutDescription:i});throw D}}};e(HBr,"VtgAiSessionBaseService");var j6e=HBr;g6();var WBr=class WBr extends j6e{constructor(i,s,c,p,_,v){super(p,_,v);this.webDriver=i;this.pageInteractor=s;this.actionsService=c;this.actionsManager=p;this.apiService=_;this.userStoryService=v;this.previousActionFailed=!1;this.currentChecksumId="0";this.executeAction=e(async({data:i,options:s={isAISuggestion:!0}})=>{await this.webDriver.clearHighlights(),this.previousActionFailed=!1;let c;try{let p=new IOt(this.webDriver.appMainFrame.page());p.startListening(),c=await this.actionsService.executeAction({data:i,id:i.id,options:s}),await p.wait(),await lb(2e3)}catch(p){throw this.previousActionFailed=!0,Yp.error(p),new Error(p)}return s.valueChanged&&await this.init(),c},"executeAction")}async init({keepActionsWithoutDescription:i}={keepActionsWithoutDescription:!0}){return this.clear(),super.init({keepActionsWithoutDescription:i})}clear(){super.clear(),this.previousActionFailed=!1,this.currentChecksumId="0"}async iterate({guidance:i}={}){await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1);let{reducedHTML:s,flashingHTML:c,elementsForNodeInterpretation:p,currentChecksumId:_}=await this.webDriver.evaluateWithChecksum(async({appRules:v,currentChecksumId:E})=>window.checksum.testGenerator.reduceHTML(v,{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:E}),{appRules:{appSpecificInteractableElementsSelectors:[]},currentChecksumId:this.currentChecksumId});this.currentChecksumId=_;try{let v=await this.getNextAction({reducedHTML:s,flashingHTML:c,elementsForNodeInterpretation:p,guidance:i}),D={...await this.pageInteractor.translateActionResponseToAgentPotentialAction(v),id:(0,xwn.randomUUID)(),timestamp:Date.now()};return await this.webDriver.highlightElementByLocator(this.pageInteractor.makeLocator(D.selector,D.parentFramesSelectors),D.clickOffset,"10px solid rgba(255,0,0,1)",!0),D}catch(v){Yp.error("error in ai iterate",v)}}async stop(){}async getNextAction({reducedHTML:i,flashingHTML:s,elementsForNodeInterpretation:c,guidance:p}){let _={reduction:{reducedHTML:i,flashingHTML:s,elementsForNodeInterpretation:c},currentURL:this.webDriver.appMainFrame.url(),previousActionOverview:{success:!this.previousActionFailed,userCorrection:p}};try{return await(await this.apiService.post("ai-fallback/iterate",{sessionId:this.remoteSessionId,iterationData:_})).json()}catch(v){throw console.error(v),v}}};e(WBr,"VtgAITestGenerationService");var FOt=WBr;oNr();dCe();var bye=require("@playwright/test"),sOr=H0(fut());iS();var aOr=class aOr{constructor(r){this.options=r;this.harData={methodIndex:{GET:0,POST:0,PUT:0,DELETE:0}};this.interceptors={recordHar:this.harInterceptor.bind(this),completeOriginHeader:this.completeOriginHeaderInterceptor.bind(this)};this.intercept=e(async(r,i,s,c)=>{let p=c??this.options,_=[],v=e(E=>{if(E)switch(E.type){case"abort":return r.abort(E.errorCode);case"fulfill":return r.fulfill(E.fulfillOptions);default:case"continue":_.push(E)}},"processResult");for(let[E,D]of Object.entries(this.interceptors))if(p[E]){let w=v(await D(r,i,s));if(w)return w}return this.applyContinueResults(r,_)},"intercept")}setOptions(r){this.options=r}mergeOptions(r){this.options={...this.options,...r}}applyContinueResults(r,i){let s=i.filter(p=>!!p),c={};return s.forEach(p=>{p.options&&(p.options.headers&&(c.headers={...c.headers,...p.options.headers}),p.options.method&&(c.method=p.options.method),p.options.postData&&(c.postData=p.options.postData),p.options.url&&(c.url=p.options.url))}),r.continue(c)}async harInterceptor(r){let i=r.request().headers(),s=r.request().method();return i["Checksum-Id"]=(++this.harData.methodIndex[s]).toString(),{options:{headers:i}}}async completeOriginHeaderInterceptor(r,i,{page:s}){if(i.resourceType()==="document")return;let c=r.request().headers();if(!c.Origin&&!c.origin){try{let p=new URL(s.url()).origin;c.origin=p,c.Origin=p}catch{}return{options:{headers:c}}}}};e(aOr,"RouteInterceptors");var tqe=aOr;PSr();BRe();M1r();var oOr=class oOr{constructor(r={},i={},s=new LRe,c=void 0){this.framesMessageBroker=s;this.context=c;this.browserConfig={executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH??void 0};this.options={fullScreenResolution:!1,disableWebSecurity:!0};this.contextClosePromise=void 0;this.eventListeners=[];this.lastSnapshot={selector:void 0,eventCode:void 0};this.snapshotTimeout=3e4;this.cacheScript=!1;this.pagesIndexToGuid={};this.onRequestFinished=e(async r=>{try{let i=await r.response();if(!i.ok())return;let s=r.resourceType(),c=r.url(),p=e(async()=>{try{return await i.text()}catch{try{return await(await fetch(c)).text()}catch{return}}},"getBody");if(["document","script","stylesheet"].includes(s))try{let _=await p();if(!_)return;let v={url:c,source:_,type:s};await this.forEachEventListener(E=>{var D;return(D=E.onWebDriverResourceLoaded)==null?void 0:D.call(E,v)})}catch(_){console.error("[WebDriver] requestfinished event handler error",s,c,_)}}catch(i){console.error("[WebDriver] requestfinished event handler error",i)}},"onRequestFinished");this.onFrameNavigated=e(async r=>{let i=e(async s=>{await this.forEachEventListener(c=>{var p;return(p=c.onWebDriverFrameNavigated)==null?void 0:p.call(c,r,s)})},"notifyFrameNavigated");await i(!1),await this.injectedScriptManager.onFrameNavigated(r),await i(!0)},"onFrameNavigated");this.tracing=!1;this.tracingChunk=!1;this.chunkIndex=0;var p;if(this.options={...this.options,...r},this.browserConfig={...this.browserConfig,...i},this.injectedScriptManager=new Tje(this.options),this.browserConfig.args||(this.browserConfig.args=[]),this.options.disableWebSecurity&&this.browserConfig.args.push("--disable-web-security"),this.options.allowFileAccess&&this.browserConfig.args.push("--allow-file-access-from-files"),this.browserConfig.args.push("--disable-site-isolation-trials"),this.browserConfig.args.push("--allow-running-insecure-content"),this.options.remoteDebugging&&this.browserConfig.args.push(`--remote-debugging-port=${this.options.remoteDebuggingPort??"9222"}`),this.options.forceHeadless&&(this.browserConfig.headless=!0),this.options.useProxy)if((p=this.options.webProxy)!=null&&p.server){console.log("[WebDriver] using proxy");let{server:_,username:v,password:E}=this.options.webProxy;this.browserConfig.proxy={server:_,username:v,password:E},this.browserConfig.args.push("--proxy-bypass-list=localhost,127.0.0.1")}else console.error("[WebDriver] useProxy=true but proxy not configured");this.routeInterceptor=new tqe({completeOriginHeader:this.options.completeOriginHeader,recordHar:this.options.recordHAR})}async prepare({storageState:r,baseURL:i,shutdown:s=!0}={}){s&&await this.shutdown();let c={};if(c.bypassCSP=!0,c.ignoreHTTPSErrors=!0,c.baseURL=i??this.options.baseURL,this.options.timezoneId&&(c.timezoneId=this.options.timezoneId),this.options.viewport?c.viewport=this.options.viewport:this.options.fullScreenResolution?c.viewport={width:1280,height:720}:this.options.hostWindowViewport&&(c.deviceScaleFactor=void 0,c.viewport=null),r&&(c.storageState=r),this.context)this.browser=this.context.browser();else if(this.options.useStealth){let p=require("puppeteer-extra-plugin-stealth");sOr.chromium.use(p()),this.browser=await sOr.chromium.launch(this.browserConfig)}else this.browser=await bye.chromium.launch(this.browserConfig);return this.context||(this.context=await this.browser.newContext(c)),this.options.defaultTimeout&&this.context.setDefaultTimeout(this.options.defaultTimeout),this.options.defaultNavigationTimeout&&this.context.setDefaultNavigationTimeout(this.options.defaultNavigationTimeout),this.context.on("page",async p=>{await this.onNewPage(p),await this.onFrameNavigated(p.mainFrame()),p.on("framenavigated",this.onFrameNavigated)}),this.context.on("close",async()=>{this.contextClosePromise=this.forEachEventListener(p=>{var _;return(_=p.onWebDriverContextClose)==null?void 0:_.call(p)})}),this.activePage=await this.createPage(),this.options.trackLoadedResources&&this.page.on("requestfinished",this.onRequestFinished),this.options.useCDPSession&&(this.cdpSession=await this.context.newCDPSession(this.originalPage)),!0}getContext(){return this.context}get frameMsgBroker(){return this.framesMessageBroker}async createPage(){return this.originalPage=await this.context.newPage(),this.originalPage}async onNewPage(r){}async applyRouteInterceptors(r,i){try{await(r==null?void 0:r.route("**/*",async(s,c)=>this.routeInterceptor.intercept(s,c,{page:r},i)))}catch(s){console.error("[WebDriver] applyRouteInterceptors error",s)}}switchActivePage(r){let i=this.context.pages().find(s=>nw(s)===r);return!i||i.isClosed()?(console.error(`[WebDriver] Page with guid ${r} not found or has been closed.`),!1):(this.previousPage=this.activePage,this.activePage=i,!0)}getDefaultTimeout(){return this.options.defaultTimeout}getDefaultNavigationTimeout(){return this.options.defaultNavigationTimeout}async addHARMockAPIRecordings(r){if(!this.activePage){console.warn("[addHARMockAPIRecordings] Active page is not set, skipping HAR recording.");return}await this.activePage.routeFromHAR(r,{url:/^(?!.*\.(js|mjs|ts|jsx|tsx|css|jpg|jpeg|png|gif|svg|webp|heif|heic|raw|cr2|nef|arw|bmp|tiff|tif|ico|woff|woff2|ttf|otf|doc|docx|pdf|ws|wasm|mp3|wav|aac|flac|mp4|avi|mov|wmv|flv|zip|rar|7z|tar\.gz|xml|html|py|java|cpp|xls|xlsx|ppt|pptx|gif)$)/i,update:!0,updateMode:"minimal"})}forEachEventListener(r){return Promise.all(this.eventListeners.map(async i=>{try{await r(i)}catch(s){console.log("WebDriver/forEachEventListener exception",s)}}))}registerEventListener(r){this.eventListeners.push(r)}async getScript(){async function r(i){let{exec:s}=require("child_process");return new Promise((c,p)=>{s(i,_=>{_?(console.log("error executing cmd, ",_),p(_)):c()})})}switch(e(r,"execCmd"),this.options.scriptSource){case"file":return this.options.scriptFile;case"url":if(this.cacheScript)return this.options.scriptFile;try{return await r(`curl -o ${this.options.scriptFile} '${this.options.scriptURL}'`),this.options.scriptFile}catch(i){console.log("[web-driver] Failed fetching frontend script",i)}break}}async startJSCoverageTracking(){return await this.page.coverage.startJSCoverage(),[];return await this.cdpSession.send("Debugger.enable"),await this.cdpSession.send("Profiler.enable"),await this.cdpSession.send("Profiler.startPreciseCoverage",{callCount:!1,detailed:!0}),this.getCurrentJSCoverage()}stopJSCoverageTracking(){return this.page.coverage.stopJSCoverage()}async getCurrentJSCoverage(){let r=await this.page.coverage.stopJSCoverage();return await this.page.coverage.startJSCoverage(),r;return(await this.cdpSession.send("Profiler.takePreciseCoverage")).result}async startCSSCoverageTracking(){return await this.cdpSession.send("DOM.enable"),await this.cdpSession.send("CSS.enable"),await this.cdpSession.send("CSS.startRuleUsageTracking"),this.getCurrentCSSCoverage()}async getCurrentCSSCoverage(){return(await this.cdpSession.send("CSS.takeCoverageDelta")).coverage}getCDPSession(){return this.cdpSession}async navigate(r){return this.page.goto(r)}async setViewportSize(r,i){return this.page.setViewportSize({width:r,height:i})}async getStorageState(){return this.page.context().storageState()}async shutdown(){try{this.page&&(await this.page.close(),this.activePage=void 0),this.context&&(await this.context.close(),this.context=void 0),this.browser&&(await this.browser.close(),this.browser=void 0)}catch(r){console.warn("[WebDriver] shutdown error",r)}}async wrapWithBrowserLogs(r,{disabled:i=!1,onErrorOnly:s=!1}={}){if(i)return r();let c=[],p=e(E=>{c.push(E.text())},"log");this.page.on("console",p);let _,v;try{v=await r()}catch(E){_=E}if(this.page.off("console",p),(!s||_)&&console.log("browser console messages:",c),_)throw _;return v}async takeElementSnapshot(r,i,s={},c={}){if(r===this.lastSnapshot.selector&&i===this.lastSnapshot.eventCode)return{};if(!r)return{};try{let{snapshot:p,elementLocator:_}=await this.takeSnapshot(r,c,{frameLocatorSelector:s.frameLocatorSelector});return this.lastSnapshot={selector:r,eventCode:i},{snapshot:p,elementLocator:_}}catch(p){return console.error("takeElementSnapshot error",p),{}}}getScreenshotTimeout(r=!1){return r?this.snapshotTimeout:this.snapshotTimeout+5e3}async takePageSnapshot(r){let i=this.page.screenshot({...r,timeout:this.getScreenshotTimeout()});return await Promise.race([i,lb(this.getScreenshotTimeout(!0))])}async takeSnapshot(r,i,{frameLocatorSelector:s}={}){let c=s?this.page.frameLocator(s).locator(r):this.page.locator(r),p=c.screenshot({...i,timeout:this.getScreenshotTimeout()});return{snapshot:await Promise.race([p,lb(this.getScreenshotTimeout(!0))]),elementLocator:c}}async getCurrentURL(){return this.page.url()}async getClientScreenResolution(){return await this.page.evaluate(async()=>({width:window.screen.width,height:window.screen.height}))}async awaitContextClose(){return this.contextClosePromise||await lb(100),this.contextClosePromise}get page(){return this.activePage}getPage(){return this.activePage}startPlaywrightTrace(){return this.tracing=!0,this.context.tracing.start({name:"trace",screenshots:!0,snapshots:!0})}startPlaywrightTraceChunk(){return this.tracingChunk=!0,this.context.tracing.startChunk({name:`trace-chunk-${this.chunkIndex}`})}stopPlaywrightTraceChunk(r){return this.tracingChunk=!1,this.context.tracing.stopChunk({path:`${r.replace(".zip",`.${this.chunkIndex++}.zip`)}`})}stopPlaywrightTrace(r){return this.tracing=!1,this.context.tracing.stop({path:r})}isTracing(){return this.tracing}isTracingChunk(){return this.tracingChunk}};e(oOr,"WebDriver");var POt=oOr;g6();var NOt=require("perf_hooks");var cOr=class cOr{constructor(r,i,s,c,p){this.timeMachine=r;this.actionsManager=i;this.apiService=s;this.remoteSessionId=c;this.options=p}rewriteLastActionThought(r){throw new Error("Method not implemented.")}async generateReductionPromptData(r,i){let s=this.getActionTimestamps(r,i);if(!s)return;let c=await this.timeMachine.executeReducedHTMLTask(s.before),p=await this.timeMachine.executeReducedHTMLTask(s.after);return{previousReducedHTML:c,reducedHTML:p,timestamp:s.after}}async generatePromptData(r,i,s){if(this.promptData)return{...this.promptData,assertionsData:i};let c=this.getActionTimestamps(r,s);if(!c)return;let p=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after);return this.promptData={reduction:{reducedHTML:_,flashingHTML:[]},currentURL:"",previousReducedHTML:p,previousURL:"",actionId:r,assertionsData:i,timestamp:c.after},this.promptData}async generateThoughtPromptData(r,i){let s=await this.generateReductionPromptData(r,i.timestamp);if(!s)return;let c=this.actionsManager.actions.findIndex(v=>v.id===r);if(c===-1){Yp.error(`Action with id ${r} not found`);return}let p=this.actionsManager.actions[c],_=this.actionsManager.actions[c-1];return{...s,action:p,previousAction:_,assertion:i}}async callApi(r,i,s,c){let p=NOt.performance.now(),_=await this.generatePromptData(i,s,c);if(this.logPerformance(`- Generated prompt data for ${r}`,p),!_)return;p=NOt.performance.now();let v=await this.apiService.post(`assertions/${r}`,{sessionId:this.remoteSessionId,data:_});if(!v.ok){Yp.error(`Request for assertion generation ${r} failed with status ${v.status}`);return}let E=await v.json();return this.logPerformance(`- Received response for assertion generation ${r}`,p),E}async generateAssertions(r,i){try{let s=await this.callApi("generate",r,void 0,i);if(s)return s.timestamps=this.getActionTimestamps(r,i),s}catch(s){throw Yp.error(s),s}}async refactoringAssertions(r){try{return await this.callApi("refactor",r.actionId,r)}catch(i){throw Yp.error(i),i}}async filteringAssertions(r){try{return await this.callApi("filter",r.actionId,r)}catch(i){throw Yp.error(i),i}}getVariables(){return[]}getVariablesString(r){return""}getActionTimestamps(r,i){let s=this.actionsManager.actions,c=s.findIndex(v=>v.id===r);if(c===-1){Yp.warning(`[init] No action with id ${r} was found in executed actions`);return}let p=s[c],_=s[c+1];return{before:p.timestamp,after:(_==null?void 0:_.timestamp)??i}}logPerformance(r,i){this.options.logPerformance&&Yp(`${r} in`,NOt.performance.now()-i,"ms")}};e(cOr,"AssertionsAgent");var rqe=cOr;aw();g6();O1e();var Bwn=require("crypto"),Eye=require("perf_hooks");var uOr=class uOr extends j6e{constructor(i,s,c,p,_,v,E){super(i,s,c);this.actionsManager=i;this.apiService=s;this.userStoryService=c;this.timeMachine=p;this.webDriver=_;this.evaluationService=v;this.options=E;this.activeRemoteSessionIdByActionId=new Map}async init({retriesLeft:i=3,keepActionsWithoutDescription:s=!1,lastActionId:c=void 0}={}){await super.init({retriesLeft:i,keepActionsWithoutDescription:s,lastActionId:c}),this.activeRemoteSessionIdByActionId.set(c,this.remoteSessionId)}async generateAiAssertions({id:i,startedAt:s,processId:c}){this.options.logPerformance&&Yp.info(`generateAiAssertions for action ${i}`);let p=e(async(_=[],v=!1)=>{try{let E=_.map((D,w)=>({...D,id:(0,Bwn.randomUUID)(),source:"ai",verified:!0,actionId:i})).filter(D=>{var w;return!["withChecksumAI()","withChecksumAI"].includes(D.matcher)&&!((w=D.usedVariablesNames)!=null&&w.length)});return Yp.info(`Returned assertions results (${c})`,_.map(({matcher:D,thought:w,locator:B})=>({matcher:D,thought:w,locator:B}))),await this.webDriver.page.evaluate(({assertions:D,actionId:w,error:B,processId:N})=>{window.vtg.onAsyncProcessResponse({actionId:w,assertions:D,error:B,processId:N})},{assertions:E,actionId:i,error:v,processId:c}),E}catch(E){return Yp.error("Error in AI assertions generation",E),[]}},"sendResultToVTGWithoutUnsupported");try{if(this.isRunning(i))return Yp.warning("Already generating assertions for this action"),await p();let _=Eye.performance.now();if(await this.init({keepActionsWithoutDescription:!0,lastActionId:i}),this.logPerformance(`init for action ${i}`,_),!this.isRunning(i))return await p();let v=new rqe(this.timeMachine,this.actionsManager,this.apiService,this.remoteSessionId,this.options),E=await this.generateAssertions(v,i,s);if(!E||!this.isRunning(i))return await p();if(E.assertions.length===0){let{smartAssertion:D}=E;return D?(D.isSelected=!0,await p([D])):await p()}return Hd.vtg.aiAssertions.allowRefactoring&&(E=await this.refactoringAssertions(v,E)),this.isRunning(i)?(Hd.vtg.aiAssertions.allowFiltering?E=await this.filteringAssertions(v,E):E.assertions=E.assertions.map(D=>({...D,isSelected:D.isValid})),this.isRunning(i)?(this.logPerformance(`---------------- Overall - Generated assertions for action ${i} in`,_),await p(vwn(E))):await p()):await p()}catch(_){return Yp.error("Error in AI assertions generation",_),await p([],!0)}finally{this.activeRemoteSessionIdByActionId.delete(i)}}stopGenerateAiAssertions(i){this.activeRemoteSessionIdByActionId.delete(i)}isRunning(i){return this.activeRemoteSessionIdByActionId.has(i)}async generateAssertions(i,s,c=void 0){let p=Eye.performance.now(),_=p,v=await i.generateAssertions(s,c);if(this.logPerformance(`- generateAssertions for action ${s}`,p),!!v)return p=Eye.performance.now(),await this.setSelectionDataForAssertions(v),v.assertions=v.assertions.map(ywn),this.logPerformance(`- setSelectionData for action ${s}`,p),p=Eye.performance.now(),await this.validateAssertions(v.assertions,v.timestamps,i),this.logPerformance(`- validate assertions for action ${s}`,p),this.logPerformance(`Overall - Generated assertions for action ${s}`,_),v}async refactoringAssertions(i,s){let c=Eye.performance.now(),p=c;try{this.options.logPerformance&&Yp.info(`Refactoring assertions for action ${s.actionId}`),s=await i.refactoringAssertions(s),this.logPerformance(`- refactoringAssertions for action ${s.actionId}`,c),c=Eye.performance.now(),await this.validateAssertions(s.assertions,s.timestamps,i),this.logPerformance(`- validate assertions after refactoring for action ${s.actionId}`,c),this.logPerformance(`Overall - Refactored assertions for action ${s.actionId}`,p)}catch(_){Yp.error("[refactoringAssertions] Error in assertions refactoring",_)}return s}async filteringAssertions(i,s){try{let c=Eye.performance.now();this.options.logPerformance&&Yp.info(`Filtering assertions for action ${s.actionId}`);let p=await i.filteringAssertions(s);return this.logPerformance(`Overall - filteringAssertions for action ${s.actionId}`,c),p}catch(c){Yp.error("[filteringAssertions] Error in assertions filtering",c)}}async executeAssertion(i,s){let c=bye.expect.configure({timeout:500}),p=sut(i);await this.evaluationService.execute(p,{expect:c,page:s},{frame:"task-time-machine",expectConfig:{timeout:500}})}async validateLocatorMappedToCorrectRrwebId(i,s,c){if(i.locatorMappedToCorrectRrwebId)return;if(!await this.isLocatorMappedToCorrectRrwebId(i,s,c))return i.locatorMappedToCorrectRrwebId=!1,this.handleAssertionValidityError(new Error(`Locator not mapped to correct rrweb id for assertion: ${i.matcher}`),i,"locator not mapped to correct rrweb id")}async validateAssertionOnPreviousState(i,s,c){try{let p=await this.getLocatorsForLocatorString(i,s,c);if(p.length===0){if(qBr(i)&&!i.appliedBeforeAction)throw new Error(`Element not found before action for assertion: ${i.matcher}`);return}await Promise.all(p.map(async _=>{let v={...i,locator:_.toString(),matcher:i.appliedBeforeAction?i.matcher:eqe.getOppositeMatcherClause(i.matcher)};await this.executeAssertion(v,s)}))}catch(p){this.handleAssertionValidityError(p,i,i.appliedBeforeAction?"didn't apply BEFORE the action was executed and it should have":"applied BEFORE the action was executed and it shouldn't have")}}async validateAssertionOnCurrentState(i,s){try{await this.executeAssertion(i,s.frameLocator("iframe"))}catch(c){this.handleAssertionValidityError(c,i,"didn't apply AFTER the action")}}async getLocatorRrwebIds(i,s,c){let p=await this.getLocatorsForLocatorString(i,s,c);return await Promise.all(p.map(_=>_.evaluate(v=>v._rrwebid)))}async getLocatorsForLocatorString(i,s,c){if(TOt(i))return[];let p=i.locator;if(!p)return[];let _=s.frameLocator("iframe"),v=`return ${$Br(i)}`;try{return await(await this.evaluationService.getLocator(v,_)).all()}catch(E){return Yp.error(`Error getting Locator[] for assertion with locator: ${p}`,v,E.message),[]}}async isLocatorMappedToCorrectRrwebId(i,s,c){if(TOt(i))return!0;let p=await this.getLocatorRrwebIds(i,s,c);return p.length!==1?!1:p[0]===i.rrwebid}async validateAssertions(i,s,c){let p=i.filter(_=>_.isValid===void 0&&!TOt(_));await this.executeValidationTasksOnState(p,s,c,{isPreviousState:!0}),p=p.filter(_=>_.isValid===void 0),await this.executeValidationTasksOnState(p,s,c,{isPreviousState:!1}),p.forEach(_=>{_.isValid??(_.isValid=!0)})}async setSelectionDataForAssertions(i){let s=e(_=>{var v;return(v=_.matcher)==null?void 0:v.startsWith("toBeHidden")},"shouldGetSelectionDataFromPreviousState"),[c,p]=i.assertions.reduce(([_,v],E)=>(s(E)?_.push(E):v.push(E),[_,v]),[[],[]]);await this.setSelectionDataForAssertionsInTimestamp(c,i.timestamps.before),await this.setSelectionDataForAssertionsInTimestamp(p,i.timestamps.after)}async setSelectionDataForAssertionsInTimestamp(i,s){if(!(!i||i.length===0))return this.timeMachine.executeTask(async c=>{await Promise.all(i.map(p=>this.setSelectionData(p,c)))},s,{name:"setSelectionDataForAssertionsInTimestamp"})}async executeValidationTasksOnState(i,s,c,{isPreviousState:p}){let _=p?"validateAssertionOnPreviousState":"validateAssertionOnCurrentState",v=(p?this.validateAssertionOnPreviousState:this.validateAssertionOnCurrentState).bind(this),E=p?s.before:s.after;await this.timeMachine.executeTask(async D=>{for(let w of i){let B=qBr(w)===p;!w.locatorMappedToCorrectRrwebId&&B&&await this.validateLocatorMappedToCorrectRrwebId(w,D,c),await v(w,D,c)}},E,{name:_})}async setSelectionData(i,s){if(!i.rrwebid||i.locator)return;let c;try{let p=await s.evaluate(_=>window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(_,{ignoredIframesSelectors:["iframe"],fromTimeMachine:!0}),parseInt(i.rrwebid,10));if(p){Object.assign(i,p,{locatorMappedToCorrectRrwebId:!0});return}else c=new Error("Inspected element result is undefined")}catch(p){c=p}i.locatorMappedToCorrectRrwebId=!1,this.handleAssertionValidityError(c,i,"invalid locator")}logPerformance(i,s){this.options.logPerformance&&Yp.info(`${i} in ${Eye.performance.now()-s} ms`)}handleAssertionValidityError(i,s,c){let p=i.message.split(`
1732
1732
  `);Yp.warning("Failed validating assertion",p.slice(0,Math.min(p.findIndex(_=>_.startsWith("Call log:")),6)).filter(_=>_).map(_=>_.substring(0,100)).join(`
1733
1733
  `)),s&&(s.isValid=!1,s.invalidReason=c)}};e(uOr,"VtgAiAssertionsService");var BOt=uOr;var Rwn=require("@playwright/test");g6();O1e();var lOr=class lOr extends Error{constructor(r){super(`Step with id ${r} was not found`),this.name="StepNotFoundError"}};e(lOr,"StepNotFoundError");var U6e=lOr;var Q4=H0(sw());function Own(n,r,i){let s=Q4.createSourceFile("temp.ts",n,Q4.ScriptTarget.Latest,!0),c=!1,_=Q4.transform(s,[e(w=>{let B=e(N=>{if(Q4.isPropertyAssignment(N)||Q4.isShorthandPropertyAssignment(N)){let L=N.name;if(Q4.isIdentifier(L)&&L.text===r||Q4.isStringLiteral(L)&&L.text===r){c=!0;let M;if(i===void 0)M=Q4.factory.createIdentifier("undefined");else{let V=String(i);isNaN(Number(V))?M=Q4.factory.createStringLiteral(V):M=Q4.factory.createNumericLiteral(V)}return Q4.factory.createPropertyAssignment(L,M)}}return Q4.visitEachChild(N,B,w)},"visit");return N=>Q4.visitNode(N,B)},"transformer")]);if(!c)return n;let v=_.transformed[0],D=Q4.createPrinter({newLine:Q4.NewLineKind.LineFeed,removeComments:!1}).printNode(Q4.EmitHint.Unspecified,v,s);return _.dispose(),D.trim()}e(Own,"overwriteFieldValue");var pOr=class pOr{constructor(r,i,s){this.webDriver=r;this.actionsManager=i;this.evaluatorService=s}setPage(r){this.page=r}async verifyOnLive({data:r,id:i,options:s}){let c=await this.verify({assertion:r,timeout:s.singlePlay?1e3:void 0}),p=s.forceUpdateTimestamp?{id:i,timestamp:Date.now()}:void 0;return{...c,data:p}}async verifyOnTimeMachine({data:r}){try{return this.verify({assertion:r,context:{page:this.webDriver.tmFrame.frameLocator("iframe")},executionFrame:"vtg-time-machine",timeout:1e3})}catch(i){return Yp.error(i),{success:!1,message:String(i)}}}async verify({assertion:r,timeout:i,context:s={},executionFrame:c}){try{let p=r.codeValue||Qre.generateSingleAssertionCode(r),_={frame:c};return i&&(p=Own(p,"timeout",i),s.expect=Rwn.expect.configure({timeout:i}),_.expectConfig={timeout:i}),await this.evaluatorService.execute(p,s,_,{stepId:r.id}),{success:!0,message:"Assertion verified successfully!"}}catch(p){return Yp.error(String(p).slice(0,200)),{success:!1,message:String(p)}}}async updateAssertion({data:r,id:i}){if(this.actionsManager.actions.findIndex(({id:p})=>r.actionId===p)===-1)throw new U6e(r.actionId);let c={...r,selected:!0,id:i};return this.actionsManager.updateAssertionById(r.actionId,c)}createAssertion(r){let{id:i,data:s,options:c,type:p}=r;switch(c==null?void 0:c.type){case"insertAfter":{let _=this.actionsManager.findActionOrAssertionById(c.afterStepId);return _.action||`${c.afterStepId}`,s.actionId=_.action.id,s.selected=!0,s.id=i,_.assertion?this.actionsManager.addAssertionToAction(s,_.assertion.id):this.actionsManager.addAssertionToAction(s),s}case"insertLast":return this.actionsManager.addAssertionToAction(s),s;case"replace":{let _=this.actionsManager.findActionOrAssertionById(c.stepId);if(!_.action)throw new Error(`[generateAssertionForAction findActionOrAssertionById] No action with id ${c.stepId} was found in executed actions`);if(s.actionId=_.action.id,s.selected=!0,s.id=i,!_.assertion)throw new Error(`[generateAssertionForAction findActionOrAssertionById] No assertion with id ${c.stepId} was found in executed actions`);return this.actionsManager.replaceAssertion(s,_.assertion.id),s}case"replaceLast":{let _=this.actionsManager.actions[this.actionsManager.actions.length-1];if(!_)throw new Error("[generateAssertionForAction] No actions found to replace last assertion");s.actionId=_.id,s.selected=!0,s.id=i;let v=_.assertions[_.assertions.length-1];return v?this.actionsManager.replaceAssertion(s,v.id):this.actionsManager.addAssertionToAction(s),s}default:throw new Error("Add all VTGStepAdditionType switch cases handle")}}};e(pOr,"VtgAssertionsService");var OOt=pOr;dCe();g6();dCe();var cke=class cke{constructor(){this.cssFeaturesCache=new Map;this.parentChainCache=new Map}static getInstance(){return cke.instance||(cke.instance=new cke),cke.instance}getCSSKeyFeatures(r){return this.cssFeaturesCache.get(this.makeKey(r))}setCSSKeyFeatures(r,i){this.cssFeaturesCache.set(this.makeKey(r),i)}getParentChain(r){return this.parentChainCache.get(this.makeKey(r))}setParentChain(r,i){this.parentChainCache.set(this.makeKey(r),i)}makeKey(r){let{timestamp:i,rrwebId:s}=r;return`${i}_${s}`}};e(cke,"LocatorsAssetsCache");var Q6e=cke;iS();g6();dCe();var fOr=class fOr{log(...r){console.log(...r)}logError(...r){console.error(...r)}};e(fOr,"TMPAgentLoggerConsole");var ROt=fOr;gnt();var dOr=class dOr{constructor(r,i=null,s=async()=>null,c=new ROt){this.selectorGeneratorApi=r;this.variables=i;this.evaluate=s;this.logger=c}async generateSelectionForAction(r,i){var v,E;let{useCSSExtraction:s,useVariables:c,useArbitrarySelector:p}=i,_=!1;if(p&&!r.contextElements&&r.isPartOfListItem&&r.couldPickAnyListItem)try{this.logger.log("*** Will generate arbitrary selector");let D=await this.evaluate(async({checksumId:w})=>window.checksum.testGenerator.buildArbitraryListItem(w),{checksumId:r.action.checksumid});if(D)return D[0]}catch(D){console.error("Error generating arbitrary selector",D)}if(!_||!r.contextElements||!r.isPartOfListItem){let D=(v=await this.generateWithLLMFiltering(r.action.checksumid,await this.generateLocatorsForElement(r.action.checksumid,{isPartOfListItem:r.isPartOfListItem,isForContextElement:!1,useCSSExtraction:s}),null,this.testCandidates.bind(this),{isPartOfListItem:r.isPartOfListItem,useVariables:c}))==null?void 0:v[0];if(D)return r.isPartOfListItem&&!D.locator.endsWith(".first()")&&(D.selector+=" >> nth=0",D.locator+=".first()",(E=D.selectorWithVars)!=null&&E.length&&(D.selectorWithVars+=" >> nth=0",D.locatorWithVars+=".first()")),D}if(_&&r.contextElements){let D=await this.generateCompoundSelector(r.action.checksumid,r.isPartOfListItem);if(D)return{compoundSelector:D}}console.log("[SelectorGenerator] Failed to generate selection")}async generateLLMLocators(r){try{return await this.selectorGeneratorApi.generateLLMLocators(r)}catch(i){return console.error("Error generating LLM locators",i),[]}}async correctLLMLocators(r){try{return this.selectorGeneratorApi.correctLLMLocators(r)}catch(i){return console.error("Error in LLM locators correction",i),[]}}async generateWithLLMFiltering(r,i,s,c,{useImage:p=!0,useVariables:_=!0,isPartOfListItem:v=!1,isForContextElement:E=!1}={}){var D;try{if(v){let N=i.find(L=>L.isListSelector);if(N)return[N]}let w=i.length>1||_&&Object.keys(((D=this.variables)==null?void 0:D.keyValue)??{}).length>0?await this.selectorGeneratorApi.runLLMFiltering(i,s??await this.getParentChainHTML(r),{useImage:p,useVariables:_}):i;if(!w)return;let B=await c(w.map(N=>({...N,selector:N.selector??""})),r,{testUniqueness:!(v||E),useVariables:_});return B?B.map(N=>({...N,alternateLocators:{origin:"filtered",locators:B.filter(L=>L!==N).map(L=>L.locator)}})):[]}catch(w){this.logger.log("Error generating selector with LLM filtering",w);return}}async generateCompoundSelector(r,i){try{this.logger.log("*** Will generate compound selector");let s=await this.selectorGeneratorApi.extractCompoundSelectionData(r);return this.processContextElements(s,i)}catch(s){this.logger.log("Error generating compound selector",s);return}}async processContextElements(r,i){let s=await this.evaluate(async({contextElementsMetadata:p,isPartOfListItem:_})=>window.checksum.testGenerator.getCompoundSelector().filter(p,{isPartOfListItem:_}).map(({element:v,...E})=>E),{contextElementsMetadata:r,isPartOfListItem:i});if(console.log(`Filtered context elements: ${s.length}`),s.length<2){this.logger.log("<!> No context elements found besides target, skipping");return}let c;try{if(c=await this.evaluate(async({contextElements:p,isPartOfListItem:_})=>window.checksum.testGenerator.getCompoundSelector().generate(p,{isPartOfListItem:_}),{contextElements:s,isPartOfListItem:i}),!c){this.logger.log("Error generating compound selector metadata for context elements");return}this.logger.log(`Generated compound selector metadata for ${s.length} context elements (including target)`)}catch(p){this.logger.log("Error generating compound selector metadata for context elements",p.message)}try{this.logger.log("** Generating selectors for context elements");let p=[];await Promise.all(s.map(async E=>{var w;if(E.selection.type==="content"){p.push({element:{...E,selector:`internal:text="${E.selection.value}"`,locator:`getByText("${E.selection.value}")`}});return}let D=(w=await this.generateWithLLMFiltering(E.selection.checksumid,await this.generateLocatorsForElement(E.selection.checksumid,{isForContextElement:!0,useCSSExtraction:!1,isPartOfListItem:!1}),null,this.testCandidates.bind(this),{useImage:!1,isForContextElement:!0}))==null?void 0:w[0];if(!D)throw new Error("Failed to generate selector for context element");p.push({element:{...E,...D},alternateLocators:D.alternateLocators})}));let{targetSelection:_}=c,v=_.playwrightSelectors.length>0?_.playwrightSelectors[0]:{selector:_.cssSelectors[0]};if(!v.selector)throw new Error("Failed to get target relative selector");return this.logger.log("Generated customer facing compound selector - ",[...p.map(E=>E.element.selector),"target: "+v.selector]),{contextElements:p,targetRelativeSelector:v,metadata:c}}catch(p){this.logger.log("Error generating customer facing compound selector metadata for context elements",p)}}async testCandidates(r,i,{testUniqueness:s=!0,useVariables:c=!0}={}){var _;let p=[];for(let v of r)try{c=c&&!!((_=v.variables)!=null&&_.length);let E=await this.evaluate(async({checksumId:D,locator:w,testVariables:B,testUniqueness:N})=>window.checksum.testGenerator.testElementSelector(w,D,B,N),{checksumId:i,locator:c?this.implantVariablesValues(v):v.locator,testVariables:c?{locatorWithVars:v.locator,variablesCode:this.variables.code}:void 0,testUniqueness:s});E.valid&&p.push(E)}catch(E){console.error("Error testing selector",E);continue}return p}implantVariablesValues(r){var s;return(s=r.variables)!=null&&s.length?Object.entries(this.variables.keyValue).map(([c,p])=>[REe+c,p]).filter(([c])=>r.variables.map(p=>p.name).includes(c)).reduce((c,[p,_])=>c.replace("${"+p+"}",_),r.selector):r.selector}async getParentChainHTML(r){try{return this.parentChainHTML||(this.parentChainHTML={}),this.parentChainHTML[r]||(this.parentChainHTML[r]=await this.evaluate(async({checksumId:i})=>window.checksum.testGenerator.getParentChainHTML(i),{checksumId:r})),this.parentChainHTML[r]}catch(i){throw this.logger.log("Error getting parent chain HTML",i),i}}async getExtractCSSKeyElements(r){try{let i=await this.getParentChainHTML(r);return this.selectorGeneratorApi.extractCSSKeyElements(i)}catch(i){return this.logger.log("Error generating prompt for CSS key elements",i),[]}}async generateLocatorsForElement(r,i={isPartOfListItem:!1,isForContextElement:!1,useCSSExtraction:!0}){try{console.log("Generating custom locators");let s=i.useCSSExtraction?await this.getExtractCSSKeyElements(r):[],c=await this.evaluate(async({checksumId:p,keyFeatures:_,...v})=>window.checksum.testGenerator.buildCustomPlaywrightSelectors(p,_,v),{checksumId:r,keyFeatures:s,...i});return this.logger.log("Generated locators for filtering (first is playwright's)",c),c}catch(s){throw this.logger.log("Error generating prompt for selectors",s),s}}};e(dOr,"SelectorGenerator");var dut=dOr;g6();var _Or=class _Or{constructor(r,i){this.promptAssets=r;this.apiService=i}async runLLMFiltering(r=[],i,{useImage:s=!0,useVariables:c=!0}={}){try{let p={title:this.promptAssets.title,steps:this.promptAssets.steps,thought:this.promptAssets.thought,parentChainHTML:i,generatedLocators:r,...s&&this.promptAssets.image?this.promptAssets.image:{}},_=await this.apiService.post("vtg/locators/filter",p),v,E=await _.text();try{v=JSON.parse(E)}catch(D){throw Yp.error("Failed parsing LLM filtering JSON",E),D}return v}catch(p){return Yp.error("Failed getting LLM filtering response from API",p.message),[]}}async extractCompoundSelectionData(r){throw new Error("Method not implemented.")}async extractCSSKeyElements(r){r||(r=this.promptAssets.parentChainHTML);let{title:i,steps:s,thought:c}=this.promptAssets,p={title:i,steps:s,thought:c,parentChainHTML:r};try{return await(await this.apiService.post("vtg/locators/extract-css",p)).json()}catch(_){throw Yp.error(_),_}}async generateLLMLocators(r){r||(r=this.promptAssets.parentChainHTML);let{title:i,steps:s,thought:c}=this.promptAssets,p={title:i,steps:s,thought:c,parentChainHTML:r};try{let _=await this.apiService.post("vtg/locators/generate",p);if(!_.ok)throw new Error(`HTTP error when calling generate locators, status: ${_.status}`);let v;try{v=await _.json()}catch(D){throw new Error("error parsing JSON, "+D.message)}return v}catch(_){throw Yp.error("Failed getting generate locators response from API",_.message),_}}async correctLLMLocators(r,i){i||(i=this.promptAssets.parentChainHTML);let{title:s,steps:c,thought:p}=this.promptAssets,_={title:s,steps:c,thought:p,parentChainHTML:i,locators:r};try{let v=await this.apiService.post("vtg/locators/correct",_);return JSON.parse(await v.text())}catch(v){throw Yp.error(v),v}}};e(_Or,"VTGSelectorGeneratorAPI");var nqe=_Or;aw();var mOr=e(n=>{if(!n)return n;let r="",i=0,s=n.indexOf('"'),c=n.lastIndexOf('"');for(;i<n.length;)n[i]==='"'&&i!==s&&i!==c&&(i===0||n[i-1]!=="\\")?r+='\\"':r+=n[i],i++;return r},"escapeInnerQuotationMarks");var hOr=class hOr{constructor(r,i,s,c,p,_,v){this.processId=r;this.step=i;this.target=s;this.apiService=c;this.userStoryService=p;this.evaluationService=_;this.locatorInteractor=v;this.didCancel=!1}cancel(){this.didCancel=!0}async generateAILocators(){try{let r=this.getLocatorOwner();if(!r)throw new Error("Failed to get locator owner");let i=await this.locatorInteractor.getParentChainHTML(r);if(!i)throw new Error("Failed to get parent chain HTML");let s=[];return s=await this.generateLLMLocators(r,i),(s==null?void 0:s.length)>0?Array.from(new Set(s.concat(r.locator))):[]}catch(r){throw Yp.error(`Failed to generate AI locators (${this.processId})`,r),r}}async extractCSS(r=[]){try{let i=this.getLocatorOwner();if(!i)throw new Error("Failed to get locator owner");let s=await this.locatorInteractor.getParentChainHTML(i);if(!s)throw new Error("Failed to get parent chain HTML");if(this.didCancel)return;let c=await this.generateCSSKeyFeaturesLocators(s,i);if(!(c!=null&&c.length))throw new Error("No locators generated");let p=(await Promise.all(r.map(async v=>this.locatorExpressionToSelectorAndLocator(v)))).filter(v=>v),_=Array.from(new Set(c.concat(p)));return this.didCancel?void 0:_}catch(i){throw Yp.error(`Failed to extract CSS (${this.processId})`,i.message),i}}async filterLocators(r=[]){try{let i=this.getLocatorOwner();if(!i)throw new Error("Failed to get locator owner");let s=await this.locatorInteractor.getParentChainHTML(i);if(!s)throw new Error("Failed to get parent chain HTML");let c=e(()=>{let v=r.filter(w=>w),E=v.filter(w=>w.length>=100).sort((w,B)=>w.length-B.length).slice(0,5),D=v.filter(w=>w.length<100).concat(E).sort((w,B)=>w.length-B.length).slice(0,10);return Array.from(new Set(D))},"filterCandidates"),p=(await Promise.all(c().map(async v=>this.locatorExpressionToSelectorAndLocator(v)))).filter(v=>v);if(this.didCancel)return;let _=await this.runLLMFilteringForLocator(s,p,i);return this.didCancel?void 0:_}catch(i){throw Yp.error(`Failed to filter locators (${this.processId})`,i),i}}async runLLMFilteringForLocator(r,i,s,c){var D;let p={...this.getSelectorGeneratorBasePromptAssets(),parentChainHTML:r,generatedLocators:i,image:c},_="",v=new dut(new nqe(p,this.apiService)),E=Hd.vtg.aiLocators.useFakeAILocators?await this.getFakeSelectionData(s,i):(D=await v.generateWithLLMFiltering(_,i,r,async w=>(await this.locatorInteractor.candidatesTester(w,s,"runLLMFilteringForLocator",{verifyExactElement:this.isAssertion()})).filter(B=>B.success),{useImage:!!c,useVariables:!1,isPartOfListItem:!1,isForContextElement:!1}))==null?void 0:D[0];if(!E)throw new Error(`Failed generating selection data with LLM filtering (${this.processId})`);return E}async getFakeSelectionData(r,i){if(await lb(2e3),!!i.length)return{selector:`* >> ${i[0].selector}`,locator:r.locator,alternateLocators:{origin:"ai",locators:i.slice(1).map(s=>`* >> ${s.selector}`)}}}async generateCSSKeyFeaturesLocators(r,i){let s=await this.getCSSKeyFeatures(i,r),c=(await this.locatorInteractor.generateCustomPWLocators(i.locator,s,this.step)).filter(_=>_);return c.length?(await this.locatorInteractor.candidatesTester(c,i,"generateCSSKeyFeaturesLocators",{verifyExactElement:this.isAssertion()})).filter(_=>_.success):[]}async getCSSKeyFeatures(r,i){if(r.rrwebId){let c=Q6e.getInstance().getCSSKeyFeatures(r);if(c)return c}if(Hd.vtg.aiLocators.useFakeAILocators)return await lb(3e3),[];let s=await this.getCSSKeyFeaturesFromAPI(i);return r.rrwebId&&Q6e.getInstance().setCSSKeyFeatures(r,s),s}async getCSSKeyFeaturesFromAPI(r){let i={...this.getSelectorGeneratorBasePromptAssets(),parentChainHTML:r};return new nqe(i,this.apiService).extractCSSKeyElements()}async locatorExpressionToSelectorAndLocator(r){try{let i=await this.evaluationService.evaluate(`return ${FL(mOr(r))}`);return{selector:mOr(i._selector),locator:r}}catch(i){Yp.error(i);return}}async generateLLMLocators(r,i){try{let s={...this.getSelectorGeneratorBasePromptAssets(),parentChainHTML:i.replace(/\s*checksumid="[^"]*"/g,"")},c=new dut(new nqe(s,this.apiService)),p=await c.generateLLMLocators();if(!p.length)return[];if(this.didCancel)return[];let _=await this.locatorInteractor.candidatesTester(p.map(v=>({locator:v})),r,"generateLLMLocators",{verifyExactElement:this.isAssertion()});if(_.filter(v=>!v.success).length>=Math.ceil(_.length/2)){let v=await c.correctLLMLocators(_),E=await this.locatorInteractor.candidatesTester(v.map(D=>({locator:D})),r,"generateLLMLocatorsCorrection",{verifyExactElement:this.isAssertion()});if(this.didCancel)return[];_.push(...E)}return _.filter(v=>v.success).map(v=>v.locator)}catch(s){return Yp.error("Failed generating LLM locators",s),[]}}isAssertion(){return this.target.type==="assertion"}getLocatorOwner(){switch(this.target.type){case"assertion":case"action":return this.step;case"dropTarget":return{...this.step.dropTarget,timestamp:this.step.timestamp}}}getSelectorGeneratorBasePromptAssets(){try{let{goal:r,instructions:i}=this.getStory();return{title:r,steps:i,thought:this.step.thought}}catch(r){return Yp.error("Failed getting base prompt assets",r),{title:"",steps:"",thought:this.step.thought}}}getStory(){return this.userStoryService.getStory()}};e(hOr,"LocatorsAIAgent");var LOt=hOr;dCe();g6();iS();function Qwn(n,r=!1){return qYi("javascript",n,r)[0]}e(Qwn,"asLocator");var sqe,PYi=(sqe=class{constructor(r){this.preferredQuote=r;this.preferredQuote=r}generateLocator(r,i,s,c={}){switch(i){case"default":return c.hasText!==void 0?`locator(${this.quote(s)}, { hasText: ${this.toHasText(c.hasText)} })`:c.hasNotText!==void 0?`locator(${this.quote(s)}, { hasNotText: ${this.toHasText(c.hasNotText)} })`:`locator(${this.quote(s)})`;case"frame":return`frameLocator(${this.quote(s)})`;case"nth":return`nth(${s})`;case"first":return"first()";case"last":return"last()";case"role":let p=[];MOt(c.name)?p.push(`name: ${this.regexToSourceString(c.name)}`):typeof c.name=="string"&&(p.push(`name: ${this.quote(c.name)}`),c.exact&&p.push("exact: true"));for(let{name:v,value:E}of c.attrs)p.push(`${v}: ${typeof E=="string"?this.quote(E):E}`);let _=p.length?`, { ${p.join(", ")} }`:"";return`getByRole(${this.quote(s)}${_})`;case"has-text":return`filter({ hasText: ${this.toHasText(s)} })`;case"has-not-text":return`filter({ hasNotText: ${this.toHasText(s)} })`;case"has":return`filter({ has: ${s} })`;case"hasNot":return`filter({ hasNot: ${s} })`;case"and":return`and(${s})`;case"or":return`or(${s})`;case"chain":return`locator(${s})`;case"test-id":return`getByTestId(${this.toTestIdValue(s)})`;case"text":return this.toCallWithExact("getByText",s,!!c.exact);case"alt":return this.toCallWithExact("getByAltText",s,!!c.exact);case"placeholder":return this.toCallWithExact("getByPlaceholder",s,!!c.exact);case"label":return this.toCallWithExact("getByLabel",s,!!c.exact);case"title":return this.toCallWithExact("getByTitle",s,!!c.exact);default:throw new Error("Unknown selector kind "+i)}}chainLocators(r){return r.join(".")}regexToSourceString(r){return WYi(String(r))}toCallWithExact(r,i,s){return MOt(i)?`${r}(${this.regexToSourceString(i)})`:s?`${r}(${this.quote(i)}, { exact: true })`:`${r}(${this.quote(i)})`}toHasText(r){return MOt(r)?this.regexToSourceString(r):this.quote(r)}toTestIdValue(r){return MOt(r)?this.regexToSourceString(r):this.quote(r)}quote(r){let i;return VYi(r,(i=this.preferredQuote)!=null?i:"'")}},e(sqe,"JavaScriptLocatorFactory"),sqe),oqe,_9=(oqe=class{constructor(){this.tokenType=""}toJSON(){return{token:this.tokenType}}toString(){return this.tokenType}toSource(){return""+this}},e(oqe,"CSSParserToken"),oqe),cqe,Qqe=(cqe=class extends _9{constructor(i=void 0,s=void 0){super();this.value=i;this.mirror=s;this.value="",this.mirror=""}},e(cqe,"GroupingToken"),cqe),uqe,qwn=(uqe=class extends Qqe{constructor(){super(),this.tokenType="(",this.value="(",this.mirror=")"}},e(uqe,"OpenParenToken"),uqe),lqe,$wn=(lqe=class extends _9{constructor(){super(),this.tokenType=","}},e(lqe,"CommaToken"),lqe),pqe,Vwn=(pqe=class extends _9{constructor(){super(),this.tokenType=":"}},e(pqe,"ColonToken"),pqe),fqe,NYi=(fqe=class extends _9{constructor(){super(),this.tokenType="~="}},e(fqe,"IncludeMatchToken"),fqe),dqe,BYi=(dqe=class extends _9{constructor(){super(),this.tokenType="|="}},e(dqe,"DashMatchToken"),dqe),_qe,Jwn=(_qe=class extends Qqe{constructor(){super(),this.tokenType="[",this.value="[",this.mirror="]"}},e(_qe,"OpenSquareToken"),_qe),mqe,OYi=(mqe=class extends _9{constructor(){super(),this.tokenType="$="}},e(mqe,"SuffixMatchToken"),mqe),hqe,yOr=(hqe=class extends Qqe{constructor(){super(),this.tokenType="]",this.value="]",this.mirror="["}},e(hqe,"CloseSquareToken"),hqe),gqe,vOr=(gqe=class extends _9{constructor(){super(),this.tokenType="WHITESPACE"}toString(){return"WS"}toSource(){return" "}},e(gqe,"WhitespaceToken"),gqe),yqe,RYi=(yqe=class extends _9{constructor(){super(),this.tokenType="*="}},e(yqe,"SubstringMatchToken"),yqe),vqe,zwn=(vqe=class extends _9{constructor(){super(),this.tokenType=";"}},e(vqe,"SemicolonToken"),vqe),Aqe,jOt=(Aqe=class extends _9{constructor(){super(),this.tokenType="EOF"}toSource(){return""}},e(Aqe,"EOFToken"),Aqe),xqe,LYi=(xqe=class extends _9{constructor(){super(),this.tokenType="^="}},e(xqe,"PrefixMatchToken"),xqe),bqe,Hwn=(bqe=class extends _9{constructor(){super(),this.tokenType="BADSTRING"}},e(bqe,"BadStringToken"),bqe),Eqe,Wwn=(Eqe=class extends _9{constructor(){super(),this.tokenType="CDO"}toSource(){return"<!--"}},e(Eqe,"CDOToken"),Eqe),Cqe,Gwn=(Cqe=class extends _9{constructor(){super(),this.tokenType="CDC"}toSource(){return"-->"}},e(Cqe,"CDCToken"),Cqe),Dqe,Kwn=(Dqe=class extends Qqe{constructor(){super(),this.tokenType="{",this.value="{",this.mirror="}"}},e(Dqe,"OpenCurlyToken"),Dqe),Sqe,Ywn=(Sqe=class extends Qqe{constructor(){super(),this.tokenType="}",this.value="}",this.mirror="{"}},e(Sqe,"CloseCurlyToken"),Sqe),wqe,Xwn=(wqe=class extends _9{constructor(){super(),this.tokenType="||"}},e(wqe,"ColumnToken"),wqe),Tqe,Zwn=(Tqe=class extends Qqe{constructor(){super(),this.tokenType=")",this.value=")",this.mirror="("}},e(Tqe,"CloseParenToken"),Tqe),kqe,qqe=(kqe=class extends _9{constructor(i=void 0){super();this.value=i;this.value=""}ASCIIMatch(i){return this.value.toLowerCase()===i.toLowerCase()}toJSON(){let i=this.constructor.prototype.constructor.prototype.toJSON.call(this);return i.value=this.value,i}},e(kqe,"StringValuedToken"),kqe),Iqe,eTn=(Iqe=class extends qqe{constructor(r){super(),this.tokenType="IDENT",this.value=r}toString(){return"IDENT("+this.value+")"}toSource(){return hut(this.value)}},e(Iqe,"IdentToken"),Iqe),Fqe,UOt=(Fqe=class extends _9{constructor(){super(),this.tokenType="BADURL"}},e(Fqe,"BadURLToken"),Fqe),Pqe,QOt=(Pqe=class extends qqe{constructor(i,s=void 0){super();this.mirror=s;this.tokenType="FUNCTION",this.value=i,this.mirror=")"}toString(){return"FUNCTION("+this.value+")"}toSource(){return hut(this.value)+"("}},e(Pqe,"FunctionToken"),Pqe),Nqe,tTn=(Nqe=class extends qqe{constructor(r){super(),this.tokenType="AT-KEYWORD",this.value=r}toString(){return"AT("+this.value+")"}toSource(){return"@"+hut(this.value)}},e(Nqe,"AtKeywordToken"),Nqe),Bqe,rTn=(Bqe=class extends qqe{constructor(i,s=void 0){super();this.type=s;this.tokenType="HASH",this.value=i,this.type="unrestricted"}toString(){return"HASH("+this.value+")"}toJSON(){let i=this.constructor.prototype.constructor.prototype.toJSON.call(this);return i.value=this.value,i.type=this.type,i}toSource(){return this.type==="id"?"#"+hut(this.value):"#"+tXi(this.value)}},e(Bqe,"HashToken"),Bqe),Oqe,nTn=(Oqe=class extends qqe{constructor(r){super(),this.tokenType="STRING",this.value=r}toString(){return'"'+cTn(this.value)+'"'}},e(Oqe,"StringToken"),Oqe),Rqe,iTn=(Rqe=class extends qqe{constructor(r){super(),this.tokenType="URL",this.value=r}toString(){return"URL("+this.value+")"}toSource(){return'url("'+cTn(this.value)+'")'}},e(Rqe,"URLToken"),Rqe),Lqe,aTn=(Lqe=class extends _9{constructor(i=void 0,s=void 0,c=void 0,p=void 0){super();this.type=i;this.unit=s;this.repr=c;this.value=p;this.tokenType="NUMBER",this.type="integer",this.repr=""}toString(){return this.type==="integer"?"INT("+this.value+")":"NUMBER("+this.value+")"}toJSON(){let i=super.toJSON();return i.value=this.value,i.type=this.type,i.repr=this.repr,i}toSource(){return this.repr}},e(Lqe,"NumberToken"),Lqe),Mqe,sTn=(Mqe=class extends _9{constructor(i=void 0,s=void 0){super();this.repr=i;this.value=s;this.tokenType="PERCENTAGE",this.repr=""}toString(){return"PERCENTAGE("+this.value+")"}toJSON(){let i=this.constructor.prototype.constructor.prototype.toJSON.call(this);return i.value=this.value,i.repr=this.repr,i}toSource(){return this.repr+"%"}},e(Mqe,"PercentageToken"),Mqe),jqe,MYi=(jqe=class extends _9{constructor(i=void 0,s=void 0,c=void 0,p=void 0){super();this.type=i;this.unit=s;this.repr=c;this.value=p;this.tokenType="DIMENSION",this.type="integer",this.repr="",this.unit=""}toString(){return"DIM("+this.value+","+this.unit+")"}toJSON(){let i=this.constructor.prototype.constructor.prototype.toJSON.call(this);return i.value=this.value,i.type=this.type,i.repr=this.repr,i.unit=this.unit,i}toSource(){let i=this.repr,s=hut(this.unit);return s[0].toLowerCase()==="e"&&(s[1]==="-"||aF(s.charCodeAt(1),48,57))&&(s="\\65 "+s.slice(1,s.length)),i+s}},e(jqe,"DimensionToken"),jqe),jYi={javascript:PYi},Uqe,jH=(Uqe=class extends Error{},e(Uqe,"InvalidSelectorError"),Uqe),Mwn=new Set(["internal:has","internal:has-not","internal:and","internal:or","internal:chain","left-of","right-of","above","below","near"]),UYi=new Set(["left-of","right-of","above","below","near"]),QYi=new Set(["not","is","where","has","scope","light","visible","text","text-matches","text-is","has-text","above","below","right-of","left-of","near","nth-match"]);function qYi(n,r,i=!1,s=20,c=void 0){try{return iqe(new jYi[n](c),oTn(r),i,s)}catch(p){return console.error("failed to convert selector to locators",r,p),[`locator('${r}')`]}}e(qYi,"asLocators");function iqe(n,r,i=!1,s=20){let c=[...r.parts];for(let v=0;v<c.length-1;v++)if(c[v].name==="nth"&&c[v+1].name==="internal:control"&&c[v+1].body==="enter-frame"){let[E]=c.splice(v,1);c.splice(v+1,0,E)}let p=[],_=i?"frame-locator":"page";for(let v=0;v<c.length;v++){let E=c[v],D=_;if(_="locator",E.name==="nth"){E.body==="0"?p.push([n.generateLocator(D,"first",""),n.generateLocator(D,"nth","0")]):E.body==="-1"?p.push([n.generateLocator(D,"last",""),n.generateLocator(D,"nth","-1")]):p.push([n.generateLocator(D,"nth",E.body)]);continue}if(E.name==="internal:text"){let{exact:V,text:Z}=_ut(E.body);p.push([n.generateLocator(D,"text",Z,{exact:V})]);continue}if(E.name==="internal:has-text"){let{exact:V,text:Z}=_ut(E.body);if(!V){p.push([n.generateLocator(D,"has-text",Z,{exact:V})]);continue}}if(E.name==="internal:has-not-text"){let{exact:V,text:Z}=_ut(E.body);if(!V){p.push([n.generateLocator(D,"has-not-text",Z,{exact:V})]);continue}}if(E.name==="internal:has"){let V=iqe(n,E.body.parsed,!1,s);p.push(V.map(Z=>n.generateLocator(D,"has",Z)));continue}if(E.name==="internal:has-not"){let V=iqe(n,E.body.parsed,!1,s);p.push(V.map(Z=>n.generateLocator(D,"hasNot",Z)));continue}if(E.name==="internal:and"){let V=iqe(n,E.body.parsed,!1,s);p.push(V.map(Z=>n.generateLocator(D,"and",Z)));continue}if(E.name==="internal:or"){let V=iqe(n,E.body.parsed,!1,s);p.push(V.map(Z=>n.generateLocator(D,"or",Z)));continue}if(E.name==="internal:chain"){let V=iqe(n,E.body.parsed,!1,s);p.push(V.map(Z=>n.generateLocator(D,"chain",Z)));continue}if(E.name==="internal:label"){let{exact:V,text:Z}=_ut(E.body);p.push([n.generateLocator(D,"label",Z,{exact:V})]);continue}if(E.name==="internal:role"){let V=gOr(E.body,!0),Z={attrs:[]};for(let ue of V.attributes)ue.name==="name"?(Z.exact=ue.caseSensitive,Z.name=ue.value):(ue.name==="level"&&typeof ue.value=="string"&&(ue.value=+ue.value),Z.attrs.push({name:ue.name==="include-hidden"?"includeHidden":ue.name,value:ue.value}));p.push([n.generateLocator(D,"role",V.name,Z)]);continue}if(E.name==="internal:testid"){let V=gOr(E.body,!0),{value:Z}=V.attributes[0];p.push([n.generateLocator(D,"test-id",Z)]);continue}if(E.name==="internal:attr"){let V=gOr(E.body,!0),{name:Z,value:ue,caseSensitive:le}=V.attributes[0],de=ue,xe=!!le;if(Z==="placeholder"){p.push([n.generateLocator(D,"placeholder",de,{exact:xe})]);continue}if(Z==="alt"){p.push([n.generateLocator(D,"alt",de,{exact:xe})]);continue}if(Z==="title"){p.push([n.generateLocator(D,"title",de,{exact:xe})]);continue}}let w="default",B=c[v+1];B&&B.name==="internal:control"&&B.body==="enter-frame"&&(w="frame",_="frame-locator",v++);let N=$Ot({parts:[E]}),L=n.generateLocator(D,w,N);if(w==="default"&&B&&["internal:has-text","internal:has-not-text"].includes(B.name)){let{exact:V,text:Z}=_ut(B.body);if(!V){let ue=n.generateLocator("locator",B.name==="internal:has-text"?"has-text":"has-not-text",Z,{exact:V}),le={};B.name==="internal:has-text"?le.hasText=Z:le.hasNotText=Z;let de=n.generateLocator(D,"default",N,le);p.push([n.chainLocators([L,ue]),de]),v++;continue}}let M;if(["xpath","css"].includes(E.name)){let V=$Ot({parts:[E]},!0);M=n.generateLocator(D,w,V)}p.push([L,M].filter(Boolean))}return $Yi(n,p,s)}e(iqe,"innerAsLocators");function $Yi(n,r,i){let s=r.map(()=>""),c=[],p=e(_=>{if(_===r.length)return c.push(n.chainLocators(s)),s.length<i;for(let v of r[_])if(s[_]=v,!p(_+1))return!1;return!0},"visit");return p(0),c}e($Yi,"combineTokens");function $Ot(n,r=void 0){return typeof n=="string"?n:n.parts.map((i,s)=>{let c=!0;!r&&s!==n.capture&&(i.name==="css"||i.name==="xpath"&&i.source.startsWith("//")||i.source.startsWith(".."))&&(c=!1);let p=c?i.name+"=":"";return`${s===n.capture?"*":""}${p}${i.source}`}).join(" >> ")}e($Ot,"stringifySelector");function _ut(n){let r=!1,i=n.match(/^\/(.*)\/([igm]*)$/);return i?{text:new RegExp(i[1],i[2])}:(n.endsWith('"')?(n=JSON.parse(n),r=!0):n.endsWith('"s')?(n=JSON.parse(n.substring(0,n.length-1)),r=!0):n.endsWith('"i')&&(n=JSON.parse(n.substring(0,n.length-1)),r=!1),{exact:r,text:n})}e(_ut,"detectExact");function gOr(n,r){let i=0,s=n.length===0,c=e(()=>n[i]||"","next"),p=e(()=>{let Z=c();return++i,s=i>=n.length,Z},"eat1"),_=e(Z=>{throw s?new jH(`Unexpected end of selector while parsing selector \`${n}\``):new jH(`Error while parsing selector \`${n}\` - unexpected symbol "${c()}" at position ${i}`+(Z?" during "+Z:""))},"syntaxError");function v(){for(;!s&&/\s/.test(c());)p()}e(v,"skipSpaces");function E(Z){return Z>="\x80"||Z>="0"&&Z<="9"||Z>="A"&&Z<="Z"||Z>="a"&&Z<="z"||Z>="0"&&Z<="9"||Z==="_"||Z==="-"}e(E,"isCSSNameChar");function D(){let Z="";for(v();!s&&E(c());)Z+=p();return Z}e(D,"readIdentifier");function w(Z){let ue=p();for(ue!==Z&&_("parsing quoted string");!s&&c()!==Z;)c()==="\\"&&p(),ue+=p();return c()!==Z&&_("parsing quoted string"),ue+=p(),ue}e(w,"readQuotedString");function B(){p()!=="/"&&_("parsing regular expression");let Z="",ue=!1;for(;!s;){if(c()==="\\")Z+=p(),s&&_("parsing regular expression");else if(ue&&c()==="]")ue=!1;else if(!ue&&c()==="[")ue=!0;else if(!ue&&c()==="/")break;Z+=p()}p()!=="/"&&_("parsing regular expression");let le="";for(;!s&&c().match(/[dgimsuy]/);)le+=p();try{return new RegExp(Z,le)}catch(de){throw new jH(`Error while parsing selector \`${n}\`: ${de.message}`)}}e(B,"readRegularExpression");function N(){let Z="";return v(),c()==="'"||c()==='"'?Z=w(c()).slice(1,-1):Z=D(),Z||_("parsing property path"),Z}e(N,"readAttributeToken");function L(){v();let Z="";return s||(Z+=p()),!s&&Z!=="="&&(Z+=p()),["=","*=","^=","$=","|=","~="].includes(Z)||_("parsing operator"),Z}e(L,"readOperator");function M(){p();let Z=[];for(Z.push(N()),v();c()===".";)p(),Z.push(N()),v();if(c()==="]")return p(),{name:Z.join("."),jsonPath:Z,op:"<truthy>",value:null,caseSensitive:!1};let ue=L(),le,de=!0;if(v(),c()==="/"){if(ue!=="=")throw new jH(`Error while parsing selector \`${n}\` - cannot use ${ue} in attribute with regular expression`);le=B()}else if(c()==="'"||c()==='"')le=w(c()).slice(1,-1),v(),c()==="i"||c()==="I"?(de=!1,p()):(c()==="s"||c()==="S")&&(de=!0,p());else{for(le="";!s&&(E(c())||c()==="+"||c()===".");)le+=p();le==="true"?le=!0:le==="false"?le=!1:r||(le=+le,Number.isNaN(le)&&_("parsing attribute value"))}if(v(),c()!=="]"&&_("parsing attribute value"),p(),ue!=="="&&typeof le!="string")throw new jH(`Error while parsing selector \`${n}\` - cannot use ${ue} in attribute with non-string matching value - ${le}`);return{name:Z.join("."),jsonPath:Z,op:ue,value:le,caseSensitive:de}}e(M,"readAttribute");let V={name:"",attributes:[]};for(V.name=D(),v();c()==="[";)V.attributes.push(M()),v();if(s||_(void 0),!V.name&&!V.attributes.length)throw new jH(`Error while parsing selector \`${n}\` - selector cannot be empty`);return V}e(gOr,"parseAttributeSelector");function oTn(n){let r=zYi(n),i=[];for(let s of r.parts){if(s.name==="css"||s.name==="css:light"){s.name==="css:light"&&(s.body=":light("+s.body+")");let c=HYi(s.body,QYi);i.push({name:"css",body:c.selector,source:s.body});continue}if(Mwn.has(s.name)){let c,p;try{let D=JSON.parse("["+s.body+"]");if(!Array.isArray(D)||D.length<1||D.length>2||typeof D[0]!="string")throw new jH(`Malformed selector: ${s.name}=`+s.body);if(c=D[0],D.length===2){if(typeof D[1]!="number"||!UYi.has(s.name))throw new jH(`Malformed selector: ${s.name}=`+s.body);p=D[1]}}catch{throw new jH(`Malformed selector: ${s.name}=`+s.body)}let _={name:s.name,source:s.body,body:{parsed:oTn(c),distance:p}},v=[..._.body.parsed.parts].reverse().find(D=>D.name==="internal:control"&&D.body==="enter-frame"),E=v?_.body.parsed.parts.indexOf(v):-1;E!==-1&&JYi(_.body.parsed.parts.slice(0,E+1),i.slice(0,E+1))&&_.body.parsed.parts.splice(0,E+1),i.push(_);continue}i.push({...s,source:s.body})}if(Mwn.has(i[0].name))throw new jH(`"${i[0].name}" selector cannot be first`);return{capture:r.capture,parts:i}}e(oTn,"parseSelector");function VYi(n,r="'"){let i=JSON.stringify(n),s=i.substring(1,i.length-1).replace(/\\"/g,'"');if(r==="'")return r+s.replace(/[']/g,"\\'")+r;if(r==='"')return r+s.replace(/["]/g,'\\"')+r;if(r==="`")return r+s.replace(/[`]/g,"`")+r;throw new Error("Invalid escape char")}e(VYi,"escapeWithQuotes");function MOt(n){return n instanceof RegExp}e(MOt,"isRegExp");function JYi(n,r){return $Ot({parts:n})===$Ot({parts:r})}e(JYi,"selectorPartsEqual");function zYi(n){let r=0,i,s=0,c={parts:[]},p=e(()=>{let v=n.substring(s,r).trim(),E=v.indexOf("="),D,w;E!==-1&&v.substring(0,E).trim().match(/^[a-zA-Z_0-9-+:*]+$/)?(D=v.substring(0,E).trim(),w=v.substring(E+1)):v.length>1&&v[0]==='"'&&v[v.length-1]==='"'||v.length>1&&v[0]==="'"&&v[v.length-1]==="'"?(D="text",w=v):/^\(*\/\//.test(v)||v.startsWith("..")?(D="xpath",w=v):(D="css",w=v);let B=!1;if(D[0]==="*"&&(B=!0,D=D.substring(1)),c.parts.push({name:D,body:w}),B){if(c.capture!==void 0)throw new jH("Only one of the selectors can capture using * modifier");c.capture=c.parts.length-1}},"append");if(!n.includes(">>"))return r=n.length,p(),c;let _=e(()=>{let E=n.substring(s,r).match(/^\s*text\s*=(.*)$/);return!!E&&!!E[1]},"shouldIgnoreTextSelectorQuote");for(;r<n.length;){let v=n[r];v==="\\"&&r+1<n.length?r+=2:v===i?(i=void 0,r++):!i&&(v==='"'||v==="'"||v==="`")&&!_()?(i=v,r++):!i&&v===">"&&n[r+1]===">"?(p(),r+=2,s=r):r++}return p(),c}e(zYi,"parseSelectorString");function HYi(n,r){let i;try{i=GYi(n),i[i.length-1]instanceof jOt||i.push(new jOt)}catch(We){let mt=We.message+` while parsing selector "${n}"`,Ve=(We.stack||"").indexOf(We.message);throw Ve!==-1&&(We.stack=We.stack.substring(0,Ve)+mt+We.stack.substring(Ve+We.message.length)),We.message=mt,We}let s=i.find(We=>We instanceof tTn||We instanceof Hwn||We instanceof UOt||We instanceof Xwn||We instanceof Wwn||We instanceof Gwn||We instanceof zwn||We instanceof Kwn||We instanceof Ywn||We instanceof iTn||We instanceof sTn);if(s)throw new jH(`Unsupported token "${s.toSource()}" while parsing selector "${n}"`);let c=0,p=new Set;function _(){return new jH(`Unexpected token "${i[c].toSource()}" while parsing selector "${n}"`)}e(_,"unexpected");function v(){for(;i[c]instanceof vOr;)c++}e(v,"skipWhitespace");function E(We=c){return i[We]instanceof eTn}e(E,"isIdent");function D(We=c){return i[We]instanceof nTn}e(D,"isString");function w(We=c){return i[We]instanceof aTn}e(w,"isNumber");function B(We=c){return i[We]instanceof $wn}e(B,"isComma");function N(We=c){return i[We]instanceof qwn}e(N,"isOpenParen");function L(We=c){return i[We]instanceof Zwn}e(L,"isCloseParen");function M(We=c){return i[We]instanceof QOt}e(M,"isFunction");function V(We=c){return i[We]instanceof cO&&i[We].value==="*"}e(V,"isStar");function Z(We=c){return i[We]instanceof jOt}e(Z,"isEOF");function ue(We=c){return i[We]instanceof cO&&[">","+","~"].includes(i[We].value)}e(ue,"isClauseCombinator");function le(We=c){return B(We)||L(We)||Z(We)||ue(We)||i[We]instanceof vOr}e(le,"isSelectorClauseEnd");function de(){let We=[xe()];for(;v(),!!B();)c++,We.push(xe());return We}e(de,"consumeFunctionArguments");function xe(){return v(),w()||D()?i[c++].value:Re()}e(xe,"consumeArgument");function Re(){let We={simples:[]};for(v(),ue()?We.simples.push({selector:{functions:[{name:"scope",args:[]}]},combinator:""}):We.simples.push({selector:$e(),combinator:""});;){if(v(),ue())We.simples[We.simples.length-1].combinator=i[c++].value,v();else if(le())break;We.simples.push({combinator:"",selector:$e()})}return We}e(Re,"consumeComplexSelector");function $e(){let We="",mt=[];for(;!le();)if(E()||V())We+=i[c++].toSource();else if(i[c]instanceof rTn)We+=i[c++].toSource();else if(i[c]instanceof cO&&i[c].value===".")if(c++,E())We+="."+i[c++].toSource();else throw _();else if(i[c]instanceof Vwn)if(c++,E())if(!r.has(i[c].value.toLowerCase()))We+=":"+i[c++].toSource();else{let Ve=i[c++].value.toLowerCase();mt.push({name:Ve,args:[]}),p.add(Ve)}else if(M()){let Ve=i[c++].value.toLowerCase();if(r.has(Ve)?(mt.push({name:Ve,args:de()}),p.add(Ve)):We+=`:${Ve}(${Ke()})`,v(),!L())throw _();c++}else throw _();else if(i[c]instanceof Jwn){for(We+="[",c++;!(i[c]instanceof yOr)&&!Z();)We+=i[c++].toSource();if(!(i[c]instanceof yOr))throw _();We+="]",c++}else throw _();if(!We&&!mt.length)throw _();return{css:We||void 0,functions:mt}}e($e,"consumeSimpleSelector");function Ke(){let We="",mt=1;for(;!Z()&&((N()||M())&&mt++,L()&&mt--,!!mt);)We+=i[c++].toSource();return We}e(Ke,"consumeBuiltinFunctionArguments");let Ce=de();if(!Z())throw _();if(Ce.some(We=>typeof We!="object"||!("simples"in We)))throw new jH(`Error while parsing selector "${n}"`);return{selector:Ce,names:Array.from(p)}}e(HYi,"parseCSS");function WYi(n){return n.replace(/(^|[^\\])(\\\\)*\\(['"`])/g,"$1$2$3")}e(WYi,"normalizeEscapedRegexQuotes");function GYi(n){let r=KYi(n),i=-1,s=[],c,p=0,_=0,v=0,E=e(function(){p+=1,v=_,_=0},"incrLineno"),D={line:p,column:_},w=e(function(Pt){return Pt>=r.length?-1:r[Pt]},"codepoint"),B=e(function(Pt=void 0){if(Pt===void 0&&(Pt=1),Pt>3)throw"Spec Error: no more than three codepoints of lookahead.";return w(i+Pt)},"next"),N=e(function(Pt=void 0){return Pt===void 0&&(Pt=1),i+=Pt,c=w(i),aqe(c)?E():_+=Pt,!0},"consume"),L=e(function(){return i-=1,aqe(c)?(p-=1,_=v):_-=1,D.line=p,D.column=_,!0},"reconsume"),M=e(function(Pt=void 0){return Pt===void 0&&(Pt=c),Pt===-1},"eof"),V=e(function(){},"donothing"),Z=e(function(){},"parseerror"),ue=e(function(){if(le(),N(),Cye(c)){for(;Cye(B());)N();return new vOr}else{if(c===34)return Re();if(c===35)if(Uwn(B())||Ce(B(1),B(2))){let Pt=new rTn("");return mt(B(1),B(2),B(3))&&(Pt.type="id"),Pt.value=qe(),Pt}else return new cO(c);else return c===36?B()===61?(N(),new OYi):new cO(c):c===39?Re():c===40?new qwn:c===41?new Zwn:c===42?B()===61?(N(),new RYi):new cO(c):c===43?Qe()?(L(),de()):new cO(c):c===44?new $wn:c===45?Qe()?(L(),de()):B(1)===45&&B(2)===62?(N(2),new Gwn):Ve()?(L(),xe()):new cO(c):c===46?Qe()?(L(),de()):new cO(c):c===58?new Vwn:c===59?new zwn:c===60?B(1)===33&&B(2)===45&&B(3)===45?(N(3),new Wwn):new cO(c):c===64?mt(B(1),B(2),B(3))?new tTn(qe()):new cO(c):c===91?new Jwn:c===92?We()?(L(),xe()):(Z(),new cO(c)):c===93?new yOr:c===94?B()===61?(N(),new LYi):new cO(c):c===123?new Kwn:c===124?B()===61?(N(),new BYi):B()===124?(N(),new Xwn):new cO(c):c===125?new Ywn:c===126?B()===61?(N(),new NYi):new cO(c):MH(c)?(L(),de()):qOt(c)?(L(),xe()):M()?new jOt:new cO(c)}},"consumeAToken"),le=e(function(){for(;B(1)===47&&B(2)===42;)for(N(2);;)if(N(),c===42&&B()===47){N();break}else if(M()){Z();return}},"consumeComments"),de=e(function(){let Pt=Ge();if(mt(B(1),B(2),B(3))){let It=new MYi;return It.value=Pt.value,It.repr=Pt.repr,It.type=Pt.type,It.unit=qe(),It}else if(B()===37){N();let It=new sTn;return It.value=Pt.value,It.repr=Pt.repr,It}else{let It=new aTn;return It.value=Pt.value,It.repr=Pt.repr,It.type=Pt.type,It}},"consumeANumericToken"),xe=e(function(){let Pt=qe();if(Pt.toLowerCase()==="url"&&B()===40){for(N();Cye(B(1))&&Cye(B(2));)N();return B()===34||B()===39?new QOt(Pt):Cye(B())&&(B(2)===34||B(2)===39)?new QOt(Pt):$e()}else return B()===40?(N(),new QOt(Pt)):new eTn(Pt)},"consumeAnIdentlikeToken"),Re=e(function(Pt=void 0){Pt===void 0&&(Pt=c);let It="";for(;N();){if(c===Pt||M())return new nTn(It);if(aqe(c))return Z(),L(),new Hwn;c===92?M(B())?V():aqe(B())?N():It+=eN(Ke()):It+=eN(c)}throw new Error("Internal error")},"consumeAStringToken"),$e=e(function(){let Pt=new iTn("");for(;Cye(B());)N();if(M(B()))return Pt;for(;N();){if(c===41||M())return Pt;if(Cye(c)){for(;Cye(B());)N();return B()===41||M(B())?(N(),Pt):(je(),new UOt)}else{if(c===34||c===39||c===40||nXi(c))return Z(),je(),new UOt;if(c===92)if(We())Pt.value+=eN(Ke());else return Z(),je(),new UOt;else Pt.value+=eN(c)}}throw new Error("Internal error")},"consumeAURLToken"),Ke=e(function(){if(N(),jwn(c)){let Pt=[c];for(let Zt=0;Zt<5&&jwn(B());Zt++)N(),Pt.push(c);Cye(B())&&N();let It=parseInt(Pt.map(function(Zt){return String.fromCharCode(Zt)}).join(""),16);return It>rXi&&(It=65533),It}else return M()?65533:c},"consumeEscape"),Ce=e(function(Pt,It){return!(Pt!==92||aqe(It))},"areAValidEscape"),We=e(function(){return Ce(c,B())},"startsWithAValidEscape"),mt=e(function(Pt,It,Zt){return Pt===45?qOt(It)||It===45||Ce(It,Zt):qOt(Pt)?!0:Pt===92?Ce(Pt,It):!1},"wouldStartAnIdentifier"),Ve=e(function(){return mt(c,B(1),B(2))},"startsWithAnIdentifier"),Ue=e(function(Pt,It,Zt){return Pt===43||Pt===45?!!(MH(It)||It===46&&MH(Zt)):Pt===46?!!MH(It):!!MH(Pt)},"wouldStartANumber"),Qe=e(function(){return Ue(c,B(1),B(2))},"startsWithANumber"),qe=e(function(){let Pt="";for(;N();)if(Uwn(c))Pt+=eN(c);else if(We())Pt+=eN(Ke());else return L(),Pt;throw new Error("Internal parse error")},"consumeAName"),Ge=e(function(){let Pt="",It="integer";for((B()===43||B()===45)&&(N(),Pt+=eN(c));MH(B());)N(),Pt+=eN(c);if(B(1)===46&&MH(B(2)))for(N(),Pt+=eN(c),N(),Pt+=eN(c),It="number";MH(B());)N(),Pt+=eN(c);let Zt=B(1),lr=B(2),Jt=B(3);if((Zt===69||Zt===101)&&MH(lr))for(N(),Pt+=eN(c),N(),Pt+=eN(c),It="number";MH(B());)N(),Pt+=eN(c);else if((Zt===69||Zt===101)&&(lr===43||lr===45)&&MH(Jt))for(N(),Pt+=eN(c),N(),Pt+=eN(c),N(),Pt+=eN(c),It="number";MH(B());)N(),Pt+=eN(c);let ti=Ze(Pt);return{type:It,value:ti,repr:Pt}},"consumeANumber"),Ze=e(function(Pt){return+Pt},"convertAStringToANumber"),je=e(function(){for(;N();){if(c===41||M())return;We()&&Ke(),V()}},"consumeTheRemnantsOfABadURL"),qt=0;for(;!M(B());)if(s.push(ue()),qt++,qt>r.length*2)throw new Error("I'm infinite-looping!");return s}e(GYi,"tokenize");function KYi(n){let r=[];for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);if(s===13&&n.charCodeAt(i+1)===10&&(s=10,i++),(s===13||s===12)&&(s=10),s===0&&(s=65533),aF(s,55296,56319)&&aF(n.charCodeAt(i+1),56320,57343)){let c=s-55296,p=n.charCodeAt(i+1)-56320;s=Math.pow(2,16)+c*Math.pow(2,10)+p,i++}r.push(s)}return r}e(KYi,"preprocess");function eN(n){if(n<=65535)return String.fromCharCode(n);n-=Math.pow(2,16);let r=Math.floor(n/Math.pow(2,10))+55296,i=n%Math.pow(2,10)+56320;return String.fromCharCode(r)+String.fromCharCode(i)}e(eN,"stringFromCode");var aF=e(function(n,r,i){return n>=r&&n<=i},"between");function Cye(n){return aqe(n)||n===9||n===32}e(Cye,"whitespace");function aqe(n){return n===10}e(aqe,"newline");var AOr=class AOr extends _9{constructor(i,s=void 0){super();this.value=s;this.tokenType="DELIM",this.value="",this.value=eN(i)}toString(){return"DELIM("+this.value+")"}toJSON(){let i=this.constructor.prototype.constructor.prototype.toJSON.call(this);return i.value=this.value,i}toSource(){return this.value==="\\"?`\\
1734
1734
  `:this.value}};e(AOr,"DelimToken");var cO=AOr;function MH(n){return aF(n,48,57)}e(MH,"digit");function jwn(n){return MH(n)||aF(n,65,70)||aF(n,97,102)}e(jwn,"hexdigit");function YYi(n){return aF(n,65,90)}e(YYi,"uppercaseletter");function XYi(n){return aF(n,97,122)}e(XYi,"lowercaseletter");function ZYi(n){return YYi(n)||XYi(n)}e(ZYi,"letter");function eXi(n){return n>=128}e(eXi,"nonascii");function qOt(n){return ZYi(n)||eXi(n)||n===95}e(qOt,"namestartchar");function Uwn(n){return qOt(n)||MH(n)||n===45}e(Uwn,"namechar");function hut(n){n=""+n;let r="",i=n.charCodeAt(0);for(let s=0;s<n.length;s++){let c=n.charCodeAt(s);if(c===0)throw new mut("Invalid character: the input contains U+0000.");aF(c,1,31)||c===127||s===0&&aF(c,48,57)||s===1&&aF(c,48,57)&&i===45?r+="\\"+c.toString(16)+" ":c>=128||c===45||c===95||aF(c,48,57)||aF(c,65,90)||aF(c,97,122)?r+=n[s]:r+="\\"+n[s]}return r}e(hut,"escapeIdent");function tXi(n){n=""+n;let r="";for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);if(s===0)throw new mut("Invalid character: the input contains U+0000.");s>=128||s===45||s===95||aF(s,48,57)||aF(s,65,90)||aF(s,97,122)?r+=n[i]:r+="\\"+s.toString(16)+" "}return r}e(tXi,"escapeHash");var xOr=class xOr extends Error{constructor(r){super(r),this.name="InvalidCharacterError"}};e(xOr,"InvalidCharacterError");var mut=xOr;function cTn(n){n=""+n;let r="";for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);if(s===0)throw new mut("Invalid character: the input contains U+0000.");aF(s,1,31)||s===127?r+="\\"+s.toString(16)+" ":s===34||s===92?r+="\\"+n[i]:r+=n[i]}return r}e(cTn,"escapeString");var rXi=1114111;function nXi(n){return aF(n,0,8)||n===11||aF(n,14,31)||n===127}e(nXi,"nonprintable");var bOr=class bOr{constructor(r,i,s){this.webDriver=r;this.timeMachine=i;this.evaluationService=s}async verifyAndCompareLocatorOnTimemachine(r,i,s){return this.timeMachine.executeTask(c=>this.verifyLocatorOrSelector({type:"locator",value:r},i,c),s,{name:"verifyAndCompareLocatorOnTimemachine"})}async verifyLocatorOrSelector({type:r,value:i,verifyUniqueness:s=!0,verifyExactElement:c=!1,fetchRrwebId:p=!1},_,v=this.webDriver.tmFrame){let E=e((N,L)=>({success:!1,value:i,error:N,message:L}),"error"),D,w,B=e(async()=>{if(_&&!await this.areLocatorsIdentical(_,D,v,c))return E("INCORRECT_TARGET","Locators points at different element");if(p)try{w=await this.getRrwebIdFromLocator(v,D)}catch(N){Yp("Failed fetching rrwebid",N.message)}return{success:!0,value:i,rrwebId:w}},"success");try{switch(r){case"locator":try{D=await this.evaluationService.getLocator(`return ${FL(i)}`,v.frameLocator("iframe"))}catch(L){return E("INVALID",L.message)}break;case"selector":D=v.frameLocator("iframe").locator(i);break}let N;try{if(!D)throw new Error;N=await D.count()}catch(L){return Yp.error("Error verifying locator or selector",{e:L}),E("INVALID","Could not evaluate element")}if(!s)return B();if(N===2){for(let L=0;L<2;L++)if(await D.nth(L).evaluate(V=>V.matches(".element-inspector-ignore")))return B()}return N!==1?N===0?E("NOT_FOUND","No element found"):E("NON_UNIQUE",`Strict mode: ${N} elements found`):B()}catch(N){return E("INVALID",String(N))}}async generateCustomPWLocators(r,i,s){let c=e(async(_=!1)=>this.timeMachine.executeTask(async v=>{let E=await this.evaluationService.getElementHandle(`return ${FL(r)}`,v.frameLocator("iframe"));return await v.evaluate(async({element:D,cssKeyFeatures:w,options:B})=>{try{if(!D)throw new Error("element not found");return window.checksum.testGenerator.buildCustomPlaywrightSelectors(D,w,B,D.ownerDocument)}catch(N){return Yp.error("Error generating locators",N),[]}},{element:E,cssKeyFeatures:i,options:{isPartOfListItem:!1,isForContextElement:!1,addCSSSelectorGenerator:!1,bruteForceMode:_}})},s.timestamp,{name:"generateCustomPWLocators"}),"generate"),p=await c()??[];return(p==null?void 0:p.length)<3?c(!0):p}async getParentChainHTML(r){if(r.rrwebId){let c=Q6e.getInstance().getParentChain(r);if(c)return c}let{parentChainHTML:i,rrwebId:s}=await this.timeMachine.executeTask(async c=>{let p=await this.evaluationService.getLocator(`return await ${FL(r.locator)}`,c.frameLocator("iframe")),_;try{_=await this.getRrwebIdFromLocator(c,p)}catch{}let v=await p.elementHandle();return{parentChainHTML:await c.evaluate(async({element:D})=>{try{if(!D)throw new Error("Element not found");let w=await window.checksum.testGenerator.getParentChainHTML(D,!0);if(typeof w!="string")throw new Error("Parent chain HTML is not a string, "+typeof w);return w}catch(w){throw Yp.error("Error getting parent chain HTML",{e:w}),w}},{element:v}),rrwebId:_}},r.timestamp,{name:"getParentChainHTML "+r.locator});return s&&(r.rrwebId=s,Q6e.getInstance().setParentChain(r,i)),i}async candidatesTester(r,i,s,{verifyExactElement:c=!1}={}){if(!r.length)return[];let p=!!r[0].selector,_=e(D=>({value:p?D.selector:D.locator,type:p?"selector":"locator",verifyUniqueness:!0,verifyExactElement:c}),"inputTransformer"),v=e(async D=>({...D,...p?{selector:D.value,locator:Qwn(D.value)}:await this.locatorExpressionToSelectorAndLocator(D.value)}),"outputTransformer"),E=await this.timeMachine.executeTask(async D=>{try{Yp.info(`Will test ${r.length} locators`);let w=await Promise.all(r.map(async B=>({...B,...await this.verifyLocatorOrSelector(_(B),i==null?void 0:i.locator,D)})));return Yp.info(`locator verification results: ${w.filter(B=>B.success).length}/${w.length}`),await Promise.all(w.map(v))}catch(w){Yp.error("Error testing selectors",w)}},i.timestamp,{name:`${s}CandidatesTester`});return E||(Yp.warning("No valid selector found"),[])}async locatorExpressionToSelectorAndLocator(r){try{return{selector:(await this.evaluationService.evaluate(`return ${FL(r)}`))._selector,locator:r}}catch{return}}async areLocatorsIdentical(r,i,s=this.timeMachine.getFrame(),c=!1){try{let p=await this.evaluationService.getElementHandle(`return ${FL(r)}`,s.frameLocator("iframe")),_=await i.elementHandle();if(!p||!_)throw new Error("One or both locators did not resolve to an element.");return await p.evaluate((D,w)=>D.isSameNode(w),_)?!0:c?!1:!!await p.evaluate((D,w)=>D.contains(w)||D.parentElement===w,_)}catch(p){return Yp.error("Error comparing locators:",p.message),!1}}async getRrwebIdFromLocator(r,i){let s=await i.elementHandle({timeout:5e3});return await r.evaluate(async c=>{var p;if(!c)throw new Error("Element not found");return(p=window.checksum.timeMachine.sessionReplayer.getMeta(c))==null?void 0:p.id},s)}};e(bOr,"LocatorInteractor");var VOt=bOr;var EOr=class EOr{constructor(r,i,s,c,p){this.webDriver=r;this.apiService=s;this.userStoryService=c;this.evaluationService=p;this.runningAgents={};this.locatorInteractor=new VOt(r,i,p)}async cancelProcess(r){this.runningAgents[r]&&(this.runningAgents[r].cancel(),delete this.runningAgents[r])}async verifyAndCompareLocatorOnTimemachine(r,i,s){return this.locatorInteractor.verifyAndCompareLocatorOnTimemachine(r,i,s)}async verifyLocatorOrSelector(r,i,s=this.webDriver.tmFrame){return this.locatorInteractor.verifyLocatorOrSelector(r,i,s)}createAgent(r,i,s){let c=new LOt(r,i,s,this.apiService,this.userStoryService,this.evaluationService,this.locatorInteractor);return this.runningAgents[r]=c,c}async generateAILocators(r,i,s){try{let p=await this.createAgent(s,r,i).generateAILocators();await this.updateVTGWithLocators(s,p[0],p.slice(1),"ai")}catch(c){Yp.error(`Failed to generate AI locators (${s})`,c),this.markError(s)}finally{delete this.runningAgents[s]}}async extractCSS(r,i,s,c=[]){try{let _=await this.createAgent(s,r,i).extractCSS(c);await this.updateVTGWithLocators(s,_[0].locator,_.slice(1).map(v=>v.locator),"withCSSKeyFeatures")}catch(p){Yp.error(`Failed to extract CSS (${s})`,p.message),this.markError(s)}finally{delete this.runningAgents[s]}}async filterLocators(r,i,s,c=[]){try{let _=await this.createAgent(s,r,i).filterLocators(c);await this.updateVTGWithLocators(s,_.locator,_.alternateLocators.locators.filter(v=>v!==_.locator),"filtered")}catch(p){Yp.error(`Failed to filter locators (${s})`,p),this.markError(s)}finally{delete this.runningAgents[s]}}async updateVTGWithLocators(r,i,s=[],c,p=!1){try{await this.webDriver.page.evaluate(_=>{window.vtg.onAsyncProcessResponse(_)},{locator:i,alternates:s,origin:c,error:p,processId:r}),i&&Yp.info(`Updated VTG with ${s.length+1} locators on state ${c} (${r})`)}catch(_){Yp.error("Failed to update VTG with locators",_)}}async markError(r){await this.updateVTGWithLocators(r,void 0,void 0,void 0,!0),Yp.info(`Updated VTG with Error (${r})`)}};e(EOr,"VtgLocatorsService");var JOt=EOr;RRe();function gut(n,r){return e(function(){return n.apply(r,arguments)},"wrap")}e(gut,"bind");var{toString:iXi}=Object.prototype,{getPrototypeOf:DOr}=Object,{iterator:HOt,toStringTag:fTn}=Symbol,WOt=(n=>r=>{let i=iXi.call(r);return n[i]||(n[i]=i.slice(8,-1).toLowerCase())})(Object.create(null)),qoe=e(n=>(n=n.toLowerCase(),r=>WOt(r)===n),"kindOfTest"),GOt=e(n=>r=>typeof r===n,"typeOfTest"),{isArray:Vqe}=Array,$qe=GOt("undefined");function yut(n){return n!==null&&!$qe(n)&&n.constructor!==null&&!$qe(n.constructor)&&UH(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}e(yut,"isBuffer");var dTn=qoe("ArrayBuffer");function aXi(n){let r;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?r=ArrayBuffer.isView(n):r=n&&n.buffer&&dTn(n.buffer),r}e(aXi,"isArrayBufferView");var sXi=GOt("string"),UH=GOt("function"),_Tn=GOt("number"),vut=e(n=>n!==null&&typeof n=="object","isObject"),oXi=e(n=>n===!0||n===!1,"isBoolean"),zOt=e(n=>{if(WOt(n)!=="object")return!1;let r=DOr(n);return(r===null||r===Object.prototype||Object.getPrototypeOf(r)===null)&&!(fTn in n)&&!(HOt in n)},"isPlainObject"),cXi=e(n=>{if(!vut(n)||yut(n))return!1;try{return Object.keys(n).length===0&&Object.getPrototypeOf(n)===Object.prototype}catch{return!1}},"isEmptyObject"),uXi=qoe("Date"),lXi=qoe("File"),pXi=e(n=>!!(n&&typeof n.uri<"u"),"isReactNativeBlob"),fXi=e(n=>n&&typeof n.getParts<"u","isReactNative"),dXi=qoe("Blob"),_Xi=qoe("FileList"),mXi=e(n=>vut(n)&&UH(n.pipe),"isStream");function hXi(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}e(hXi,"getGlobal");var uTn=hXi(),lTn=typeof uTn.FormData<"u"?uTn.FormData:void 0,gXi=e(n=>{let r;return n&&(lTn&&n instanceof lTn||UH(n.append)&&((r=WOt(n))==="formdata"||r==="object"&&UH(n.toString)&&n.toString()==="[object FormData]"))},"isFormData"),yXi=qoe("URLSearchParams"),[vXi,AXi,xXi,bXi]=["ReadableStream","Request","Response","Headers"].map(qoe),EXi=e(n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),"trim");function Aut(n,r,{allOwnKeys:i=!1}={}){if(n===null||typeof n>"u")return;let s,c;if(typeof n!="object"&&(n=[n]),Vqe(n))for(s=0,c=n.length;s<c;s++)r.call(null,n[s],s,n);else{if(yut(n))return;let p=i?Object.getOwnPropertyNames(n):Object.keys(n),_=p.length,v;for(s=0;s<_;s++)v=p[s],r.call(null,n[v],v,n)}}e(Aut,"forEach");function mTn(n,r){if(yut(n))return null;r=r.toLowerCase();let i=Object.keys(n),s=i.length,c;for(;s-- >0;)if(c=i[s],r===c.toLowerCase())return c;return null}e(mTn,"findKey");var uke=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,hTn=e(n=>!$qe(n)&&n!==uke,"isContextDefined");function COr(){let{caseless:n,skipUndefined:r}=hTn(this)&&this||{},i={},s=e((c,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")return;let _=n&&mTn(i,p)||p;zOt(i[_])&&zOt(c)?i[_]=COr(i[_],c):zOt(c)?i[_]=COr({},c):Vqe(c)?i[_]=c.slice():(!r||!$qe(c))&&(i[_]=c)},"assignValue");for(let c=0,p=arguments.length;c<p;c++)arguments[c]&&Aut(arguments[c],s);return i}e(COr,"merge");var CXi=e((n,r,i,{allOwnKeys:s}={})=>(Aut(r,(c,p)=>{i&&UH(c)?Object.defineProperty(n,p,{value:gut(c,i),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(n,p,{value:c,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:s}),n),"extend"),DXi=e(n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),"stripBOM"),SXi=e((n,r,i,s)=>{n.prototype=Object.create(r.prototype,s),Object.defineProperty(n.prototype,"constructor",{value:n,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(n,"super",{value:r.prototype}),i&&Object.assign(n.prototype,i)},"inherits"),wXi=e((n,r,i,s)=>{let c,p,_,v={};if(r=r||{},n==null)return r;do{for(c=Object.getOwnPropertyNames(n),p=c.length;p-- >0;)_=c[p],(!s||s(_,n,r))&&!v[_]&&(r[_]=n[_],v[_]=!0);n=i!==!1&&DOr(n)}while(n&&(!i||i(n,r))&&n!==Object.prototype);return r},"toFlatObject"),TXi=e((n,r,i)=>{n=String(n),(i===void 0||i>n.length)&&(i=n.length),i-=r.length;let s=n.indexOf(r,i);return s!==-1&&s===i},"endsWith"),kXi=e(n=>{if(!n)return null;if(Vqe(n))return n;let r=n.length;if(!_Tn(r))return null;let i=new Array(r);for(;r-- >0;)i[r]=n[r];return i},"toArray"),IXi=(n=>r=>n&&r instanceof n)(typeof Uint8Array<"u"&&DOr(Uint8Array)),FXi=e((n,r)=>{let s=(n&&n[HOt]).call(n),c;for(;(c=s.next())&&!c.done;){let p=c.value;r.call(n,p[0],p[1])}},"forEachEntry"),PXi=e((n,r)=>{let i,s=[];for(;(i=n.exec(r))!==null;)s.push(i);return s},"matchAll"),NXi=qoe("HTMLFormElement"),BXi=e(n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,e(function(i,s,c){return s.toUpperCase()+c},"replacer")),"toCamelCase"),pTn=(({hasOwnProperty:n})=>(r,i)=>n.call(r,i))(Object.prototype),OXi=qoe("RegExp"),gTn=e((n,r)=>{let i=Object.getOwnPropertyDescriptors(n),s={};Aut(i,(c,p)=>{let _;(_=r(c,p,n))!==!1&&(s[p]=_||c)}),Object.defineProperties(n,s)},"reduceDescriptors"),RXi=e(n=>{gTn(n,(r,i)=>{if(UH(n)&&["arguments","caller","callee"].indexOf(i)!==-1)return!1;let s=n[i];if(UH(s)){if(r.enumerable=!1,"writable"in r){r.writable=!1;return}r.set||(r.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'")})}})},"freezeMethods"),LXi=e((n,r)=>{let i={},s=e(c=>{c.forEach(p=>{i[p]=!0})},"define");return Vqe(n)?s(n):s(String(n).split(r)),i},"toObjectSet"),MXi=e(()=>{},"noop"),jXi=e((n,r)=>n!=null&&Number.isFinite(n=+n)?n:r,"toFiniteNumber");function UXi(n){return!!(n&&UH(n.append)&&n[fTn]==="FormData"&&n[HOt])}e(UXi,"isSpecCompliantForm");var QXi=e(n=>{let r=new Array(10),i=e((s,c)=>{if(vut(s)){if(r.indexOf(s)>=0)return;if(yut(s))return s;if(!("toJSON"in s)){r[c]=s;let p=Vqe(s)?[]:{};return Aut(s,(_,v)=>{let E=i(_,c+1);!$qe(E)&&(p[v]=E)}),r[c]=void 0,p}}return s},"visit");return i(n,0)},"toJSONObject"),qXi=qoe("AsyncFunction"),$Xi=e(n=>n&&(vut(n)||UH(n))&&UH(n.then)&&UH(n.catch),"isThenable"),yTn=((n,r)=>n?setImmediate:r?((i,s)=>(uke.addEventListener("message",({source:c,data:p})=>{c===uke&&p===i&&s.length&&s.shift()()},!1),c=>{s.push(c),uke.postMessage(i,"*")}))(`axios@${Math.random()}`,[]):i=>setTimeout(i))(typeof setImmediate=="function",UH(uke.postMessage)),VXi=typeof queueMicrotask<"u"?queueMicrotask.bind(uke):typeof process<"u"&&process.nextTick||yTn,JXi=e(n=>n!=null&&UH(n[HOt]),"isIterable"),Jl={isArray:Vqe,isArrayBuffer:dTn,isBuffer:yut,isFormData:gXi,isArrayBufferView:aXi,isString:sXi,isNumber:_Tn,isBoolean:oXi,isObject:vut,isPlainObject:zOt,isEmptyObject:cXi,isReadableStream:vXi,isRequest:AXi,isResponse:xXi,isHeaders:bXi,isUndefined:$qe,isDate:uXi,isFile:lXi,isReactNativeBlob:pXi,isReactNative:fXi,isBlob:dXi,isRegExp:OXi,isFunction:UH,isStream:mXi,isURLSearchParams:yXi,isTypedArray:IXi,isFileList:_Xi,forEach:Aut,merge:COr,extend:CXi,trim:EXi,stripBOM:DXi,inherits:SXi,toFlatObject:wXi,kindOf:WOt,kindOfTest:qoe,endsWith:TXi,toArray:kXi,forEachEntry:FXi,matchAll:PXi,isHTMLForm:NXi,hasOwnProperty:pTn,hasOwnProp:pTn,reduceDescriptors:gTn,freezeMethods:RXi,toObjectSet:LXi,toCamelCase:BXi,noop:MXi,toFiniteNumber:jXi,findKey:mTn,global:uke,isContextDefined:hTn,isSpecCompliantForm:UXi,toJSONObject:QXi,isAsyncFn:qXi,isThenable:$Xi,setImmediate:yTn,asap:VXi,isIterable:JXi};var KOt=class KOt extends Error{static from(r,i,s,c,p,_){let v=new KOt(r.message,i||r.code,s,c,p);return v.cause=r,v.name=r.name,r.status!=null&&v.status==null&&(v.status=r.status),_&&Object.assign(v,_),v}constructor(r,i,s,c,p){super(r),Object.defineProperty(this,"message",{value:r,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,i&&(this.code=i),s&&(this.config=s),c&&(this.request=c),p&&(this.response=p,this.status=p.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Jl.toJSONObject(this.config),code:this.code,status:this.status}}};e(KOt,"AxiosError");var w$=KOt;w$.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";w$.ERR_BAD_OPTION="ERR_BAD_OPTION";w$.ECONNABORTED="ECONNABORTED";w$.ETIMEDOUT="ETIMEDOUT";w$.ERR_NETWORK="ERR_NETWORK";w$.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";w$.ERR_DEPRECATED="ERR_DEPRECATED";w$.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";w$.ERR_BAD_REQUEST="ERR_BAD_REQUEST";w$.ERR_CANCELED="ERR_CANCELED";w$.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";w$.ERR_INVALID_URL="ERR_INVALID_URL";var l1=w$;var vkn=H0(ykn(),1),oRt=vkn.default;function HOr(n){return Jl.isPlainObject(n)||Jl.isArray(n)}e(HOr,"isVisitable");function Akn(n){return Jl.endsWith(n,"[]")?n.slice(0,-2):n}e(Akn,"removeBrackets");function zOr(n,r,i){return n?n.concat(r).map(e(function(c,p){return c=Akn(c),!i&&p?"["+c+"]":c},"each")).join(i?".":""):r}e(zOr,"renderKey");function Iea(n){return Jl.isArray(n)&&!n.some(HOr)}e(Iea,"isFlatArray");var Fea=Jl.toFlatObject(Jl,{},null,e(function(r){return/^is[A-Z]/.test(r)},"filter"));function Pea(n,r,i){if(!Jl.isObject(n))throw new TypeError("target must be an object");r=r||new(oRt||FormData),i=Jl.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,e(function(V,Z){return!Jl.isUndefined(Z[V])},"defined"));let s=i.metaTokens,c=i.visitor||w,p=i.dots,_=i.indexes,E=(i.Blob||typeof Blob<"u"&&Blob)&&Jl.isSpecCompliantForm(r);if(!Jl.isFunction(c))throw new TypeError("visitor must be a function");function D(M){if(M===null)return"";if(Jl.isDate(M))return M.toISOString();if(Jl.isBoolean(M))return M.toString();if(!E&&Jl.isBlob(M))throw new l1("Blob is not supported. Use a Buffer instead.");return Jl.isArrayBuffer(M)||Jl.isTypedArray(M)?E&&typeof Blob=="function"?new Blob([M]):Buffer.from(M):M}e(D,"convertValue");function w(M,V,Z){let ue=M;if(Jl.isReactNative(r)&&Jl.isReactNativeBlob(M))return r.append(zOr(Z,V,p),D(M)),!1;if(M&&!Z&&typeof M=="object"){if(Jl.endsWith(V,"{}"))V=s?V:V.slice(0,-2),M=JSON.stringify(M);else if(Jl.isArray(M)&&Iea(M)||(Jl.isFileList(M)||Jl.endsWith(V,"[]"))&&(ue=Jl.toArray(M)))return V=Akn(V),ue.forEach(e(function(de,xe){!(Jl.isUndefined(de)||de===null)&&r.append(_===!0?zOr([V],xe,p):_===null?V:V+"[]",D(de))},"each")),!1}return HOr(M)?!0:(r.append(zOr(Z,V,p),D(M)),!1)}e(w,"defaultVisitor");let B=[],N=Object.assign(Fea,{defaultVisitor:w,convertValue:D,isVisitable:HOr});function L(M,V){if(!Jl.isUndefined(M)){if(B.indexOf(M)!==-1)throw Error("Circular reference detected in "+V.join("."));B.push(M),Jl.forEach(M,e(function(ue,le){(!(Jl.isUndefined(ue)||ue===null)&&c.call(r,ue,Jl.isString(le)?le.trim():le,V,N))===!0&&L(ue,V?V.concat(le):[le])},"each")),B.pop()}}if(e(L,"build"),!Jl.isObject(n))throw new TypeError("data must be an object");return L(n),r}e(Pea,"toFormData");var V6e=Pea;function xkn(n){let r={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(n).replace(/[!'()~]|%20|%00/g,e(function(s){return r[s]},"replacer"))}e(xkn,"encode");function bkn(n,r){this._pairs=[],n&&V6e(n,this,r)}e(bkn,"AxiosURLSearchParams");var Ekn=bkn.prototype;Ekn.append=e(function(r,i){this._pairs.push([r,i])},"append");Ekn.toString=e(function(r){let i=r?function(s){return r.call(this,s,xkn)}:xkn;return this._pairs.map(e(function(c){return i(c[0])+"="+i(c[1])},"each"),"").join("&")},"toString");var Ckn=bkn;function Nea(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}e(Nea,"encode");function pke(n,r,i){if(!r)return n;let s=i&&i.encode||Nea,c=Jl.isFunction(i)?{serialize:i}:i,p=c&&c.serialize,_;if(p?_=p(r,c):_=Jl.isURLSearchParams(r)?r.toString():new Ckn(r,c).toString(s),_){let v=n.indexOf("#");v!==-1&&(n=n.slice(0,v)),n+=(n.indexOf("?")===-1?"?":"&")+_}return n}e(pke,"buildURL");var KOr=class KOr{constructor(){this.handlers=[]}use(r,i,s){return this.handlers.push({fulfilled:r,rejected:i,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(r){this.handlers[r]&&(this.handlers[r]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(r){Jl.forEach(this.handlers,e(function(s){s!==null&&r(s)},"forEachHandler"))}};e(KOr,"InterceptorManager");var WOr=KOr,GOr=WOr;var J6e={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0};var Tkn=H0(require("crypto"),1);var Dkn=H0(require("url"),1),Skn=Dkn.default.URLSearchParams;var YOr="abcdefghijklmnopqrstuvwxyz",wkn="0123456789",kkn={DIGIT:wkn,ALPHA:YOr,ALPHA_DIGIT:YOr+YOr.toUpperCase()+wkn},Bea=e((n=16,r=kkn.ALPHA_DIGIT)=>{let i="",{length:s}=r,c=new Uint32Array(n);Tkn.default.randomFillSync(c);for(let p=0;p<n;p++)i+=r[c[p]%s];return i},"generateString"),Ikn={isNode:!0,classes:{URLSearchParams:Skn,FormData:oRt,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:kkn,generateString:Bea,protocols:["http","https","file","data"]};var eRr={};pH(eRr,{hasBrowserEnv:()=>ZOr,hasStandardBrowserEnv:()=>Oea,hasStandardBrowserWebWorkerEnv:()=>Rea,navigator:()=>XOr,origin:()=>Lea});var ZOr=typeof window<"u"&&typeof document<"u",XOr=typeof navigator=="object"&&navigator||void 0,Oea=ZOr&&(!XOr||["ReactNative","NativeScript","NS"].indexOf(XOr.product)<0),Rea=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Lea=ZOr&&window.location.href||"http://localhost";var v6={...eRr,...Ikn};function tRr(n,r){return V6e(n,new v6.classes.URLSearchParams,{visitor:e(function(i,s,c,p){return v6.isNode&&Jl.isBuffer(i)?(this.append(s,i.toString("base64")),!1):p.defaultVisitor.apply(this,arguments)},"visitor"),...r})}e(tRr,"toURLEncodedForm");function Mea(n){return Jl.matchAll(/\w+|\[(\w*)]/g,n).map(r=>r[0]==="[]"?"":r[1]||r[0])}e(Mea,"parsePropPath");function jea(n){let r={},i=Object.keys(n),s,c=i.length,p;for(s=0;s<c;s++)p=i[s],r[p]=n[p];return r}e(jea,"arrayToObject");function Uea(n){function r(i,s,c,p){let _=i[p++];if(_==="__proto__")return!0;let v=Number.isFinite(+_),E=p>=i.length;return _=!_&&Jl.isArray(c)?c.length:_,E?(Jl.hasOwnProp(c,_)?c[_]=[c[_],s]:c[_]=s,!v):((!c[_]||!Jl.isObject(c[_]))&&(c[_]=[]),r(i,s,c[_],p)&&Jl.isArray(c[_])&&(c[_]=jea(c[_])),!v)}if(e(r,"buildPath"),Jl.isFormData(n)&&Jl.isFunction(n.entries)){let i={};return Jl.forEachEntry(n,(s,c)=>{r(Mea(s),c,i,0)}),i}return null}e(Uea,"formDataToJSON");var cRt=Uea;function Qea(n,r,i){if(Jl.isString(n))try{return(r||JSON.parse)(n),Jl.trim(n)}catch(s){if(s.name!=="SyntaxError")throw s}return(i||JSON.stringify)(n)}e(Qea,"stringifySafely");var rRr={transitional:J6e,adapter:["xhr","http","fetch"],transformRequest:[e(function(r,i){let s=i.getContentType()||"",c=s.indexOf("application/json")>-1,p=Jl.isObject(r);if(p&&Jl.isHTMLForm(r)&&(r=new FormData(r)),Jl.isFormData(r))return c?JSON.stringify(cRt(r)):r;if(Jl.isArrayBuffer(r)||Jl.isBuffer(r)||Jl.isStream(r)||Jl.isFile(r)||Jl.isBlob(r)||Jl.isReadableStream(r))return r;if(Jl.isArrayBufferView(r))return r.buffer;if(Jl.isURLSearchParams(r))return i.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),r.toString();let v;if(p){if(s.indexOf("application/x-www-form-urlencoded")>-1)return tRr(r,this.formSerializer).toString();if((v=Jl.isFileList(r))||s.indexOf("multipart/form-data")>-1){let E=this.env&&this.env.FormData;return V6e(v?{"files[]":r}:r,E&&new E,this.formSerializer)}}return p||c?(i.setContentType("application/json",!1),Qea(r)):r},"transformRequest")],transformResponse:[e(function(r){let i=this.transitional||rRr.transitional,s=i&&i.forcedJSONParsing,c=this.responseType==="json";if(Jl.isResponse(r)||Jl.isReadableStream(r))return r;if(r&&Jl.isString(r)&&(s&&!this.responseType||c)){let _=!(i&&i.silentJSONParsing)&&c;try{return JSON.parse(r,this.parseReviver)}catch(v){if(_)throw v.name==="SyntaxError"?l1.from(v,l1.ERR_BAD_RESPONSE,this,null,this.response):v}}return r},"transformResponse")],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:v6.classes.FormData,Blob:v6.classes.Blob},validateStatus:e(function(r){return r>=200&&r<300},"validateStatus"),headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Jl.forEach(["delete","get","head","post","put","patch"],n=>{rRr.headers[n]={}});var Gqe=rRr;var qea=Jl.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Fkn=e(n=>{let r={},i,s,c;return n&&n.split(`
@@ -1786,7 +1786,7 @@ ${Hut}`})).join(`
1786
1786
  ${Hut}`),p=new Z6e(i.sourceFile),_=(N=this.userStoryService.getStory())==null?void 0:N.internalTestId,v=(L=this.userStoryService.getStory())==null?void 0:L.goal,E=(M=this.userStoryService.getStory())==null?void 0:M.id;p.transformSourceFile([new qRt(i.sourceFile),new HRt(i.sourceFile,{internalTestId:_,title:v}),new QRt(i.sourceFile,i.testMirrors.filter(V=>V.internalTestId===_||V.storyId===E).map(V=>V.testBody),UFn(c))]);let D=this.testAssetsManager.getSavedTestFilePath(),{error:w}=await p.write(D,Hut);return{filePath:(0,m$e.relative)(process.cwd(),D),error:w}}get isLoadedFromTestFile(){return!!this.vtgTestFileRunConfig}async reloadTestFromFile(r){if(!this.vtgTestFileRunConfig)return;let i=await this.getReloadTestEnvironmentCode();await this.evaluationService.execute(i);let c=new Kut(this.testAssetsManager.getSavedTestFilePath()).loadActionsFromSingleTest({mergeCustomCodeSteps:this.settingsService.getSettings().mergeCustomCodeSteps});return r&&await this.mergeTimestampsToReloadedActions(c),this.actionsManager.reloadTestSteps(c),c}async mergeTimestampsToReloadedActions(r){let i=this.actionsManager.actions,s=await this.apiService.post("llm/query",{systemMessage:zFn(),userMessage:HFn(i,r)});try{let c=await s.text(),p=JSON.parse(c),_=0;r.forEach((v,E)=>{var w,B;let D=p.map[E];if(D){let N=i.find(({id:L})=>L===D.id);if(N){v.timestamp=N.timestamp,_=N.timestamp;let L=_;(w=v.assertions)==null||w.forEach((M,V)=>{var le;let Z=D==null?void 0:D.assertions[V],ue=(le=N.assertions)==null?void 0:le.find(({id:de})=>de===Z);ue?(M.timestamp=ue.timestamp,L=ue.timestamp):M.timestamp=L+1});return}}v.timestamp=_+1,(B=v.assertions)==null||B.forEach((N,L)=>{N.timestamp=_+L+1})})}catch(c){return Yp.error("Failed to merge actions",c),null}}async getReloadTestImportCodeOfNewPackages(r,i,s){let c=new Z6e(i);c.transformSourceFile([new tlt(r,s,{filterOutChecksumImports:!0,filterOutLocalModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutNotImportOrRequireStatements:!0}),new Eke(r),new rlt,new elt]);let p=await this.getDeclaredVariableNames(c.sourceFile);return c.transformSourceFile([new Yut(i,p,{filterOutDefinedVariableNames:!0})]),(await c.getFormattedTestFileCode()).code}async getDeclaredVariableNames(r){return new JRt(this.evaluationService).extractDeclaredVariableNames(r)}async getReloadTestEnvironmentCode(){let r=this.testAssetsManager.getSavedTestFilePath(),i=X6e(r),s=Gut(),c=await this.getReloadCodeWithoutPackages(r,i,s);return[await this.getReloadTestImportCodeOfNewPackages(r,i,s),c].join(`
1787
1787
  `)}async getReloadCodeWithoutPackages(r,i,s){let c=new Z6e(i);c.transformSourceFile([new zRt({shouldRemoveTestExpression:!0,shouldRemoveTestCalls:!0}),new $Rt,new tlt(r,s,{filterOutNodeModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutChecksumImports:!0}),new Eke(r),new _$e(r,s,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[XFn.default.factory.createIdentifier("__filename")]}),new rlt,new elt]);let p=await this.getDeclaredVariableNames(c.sourceFile);return c.transformSourceFile([new Yut(i,p)]),(await c.getFormattedTestFileCode()).code}getLocalSavedJSONFilePath(r,i){var p;i??(i=i||((p=this.userStoryService.getStory())==null?void 0:p.id));let s=this.testAssetsManager.getLocalAutoSaveFileName(i);return`${r==="auto-save"?this.testAssetsManager.getLocalAutoSavePath():this.testAssetsManager.getLocalSavePath()}/${s}`}readLocalSavedDataFromJSONFile(r){let i=this.readJsonFile(r);return i?{...i,executedActions:i.executedActions.map(s=>({...s,timestamp:void 0}))}:null}readJsonFile(r){try{let i=(0,r7e.readFileSync)(r,"utf-8");return JSON.parse(i)}catch(i){return Yp.error(`Error reading or parsing JSON file: ${i}`),null}}makeDraftData(){let r=this.userStoryService.getStory(),i=this.userStoryService.getTestGenerationData(),s=this.userStoryService.getEnvInfo(),c={};return r!=null&&r.version&&(c.version=r.version),{actions:this.actionsManager.actions,internalTestId:r.internalTestId,environmentUserId:s.user.username,description:r.goal,metadata:Object.keys(c).length>0?c:void 0}}async generateTestFileString(r){try{let i=this.makeDraftData(),s=r?`${r}.draft.spec.ts`:`test-${i.internalTestId}.draft.spec.ts`,c=await this.apiService.post("test-generation/generate-test-file-string",i);if(!c.ok)throw new Error(`test generation request failed: ${c.statusText}`);let p=await c.text();_wn(p,s,this.testAssetsManager.getLocalSavePath())}catch(i){throw Yp.error("Failed to generate test file string",i),new Error("Failed to generate test file string")}}localSave(){let r=JSON.stringify(this.vtgTestJSON,null,2),i=this.testAssetsManager.getAssetsFolderPath(),s=this.testAssetsManager.getLocalAutoSaveFileName(this.userStoryService.getStory().id);(0,r7e.writeFileSync)(`${i}/${s}`,r),(0,r7e.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/${s}`,r)}get vtgTestJSON(){var r;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(r=this.config.environments.find(i=>i.default))==null?void 0:r.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async extendedJSONBackup(){let r=await this.saveExtendedJson(),i=(0,m$e.dirname)(this.testAssetsManager.getSavedTestFilePath()),s=(0,m$e.join)(i,"test.extended.json");return(0,r7e.writeFileSync)(s,JSON.stringify(r,null,2)),{executedActions:r}}async localBackup(r){var i;if(r){this.testAssetsManager.setCurrentSaveAsLocation(r);let s=this.testAssetsManager.getLocalSaveAsPath(),c=this.testAssetsManager.getLocalAutoSavePath(),p=(i=this.userStoryService.getStory())==null?void 0:i.id,_=p?[this.testAssetsManager.getLocalAutoSaveFileName(p)]:[];mwn(c,s,_)}return await this.saveTestFile()}async saveExtendedJson(){let r=[...this.actionsManager.actions],i=[],s=e(async c=>{let{timestamp:p}=c,_="matcher"in c,v=c.timestamp&&(_||pnt(c.eventCode)),{fullHTML:E,outerHTML:D,parentHTML:w,rrwebSnapshot:B}=c.timestamp?await this.getHTMLsForTimestamp(p,c.locator):{fullHTML:"",outerHTML:"",parentHTML:void 0,rrwebSnapshot:""},N=_?Qre.generateSingleAssertionCode(c):Qre.generateSingleActionCode(c,{newLineSeparator:`
1788
1788
  ${Hut}`,generateAssertionsCode:!1}),L=v?await this.takeElementSnapshot(c.locator,p):void 0;return{code:N,fullHTML:E,outerHTML:D,parentHTML:w,timestamp:p,image:L,rrwebSnapshot:B}},"extractDataForStep");for(let c=0;c<r.length;c++){Yp.info(`processing action ${c} of ${r.length}`);let p=r[c],_=await s(p);i.push(_);for(let v of p.assertions||[]){Yp.info(`processing assertion of ${p.assertions.length} assertions`);try{let E=await s(v);i.push(E)}catch(E){Yp.error("Failed to extract data for assertion",E)}}}return i}async takeElementSnapshot(r,i){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async c=>(await this.evaluationService.getLocator(`return ${FL(r)}`,c.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),i)).toString("base64")}`}catch(s){Yp.error("Failed to take element snapshot",s);return}}async getHTMLsForTimestamp(r,i){try{return i?await this.taskTimeMachine.executeTask(async c=>{let p=await this.evaluationService.getLocator(`return ${FL(i)}`,c.frameLocator("iframe")),_=await p.elementHandle(),{fullHTML:v,outerHTML:E,rrwebSnapshot:D}=await c.page().evaluate(({element:B})=>{let N="",L="",M="",V=document.querySelector(".replayer-wrapper iframe").contentDocument;try{L=V.querySelector("html").outerHTML}catch{L=""}try{M=B.outerHTML}catch{M=""}try{N=JSON.stringify(window.checksum.timeMachine.rrwebSnapshot(V))}catch{N=""}return{fullHTML:L,outerHTML:M,rrwebSnapshot:N}},{element:_}),w=await WFn(p);return{fullHTML:v,outerHTML:E,parentHTML:w,rrwebSnapshot:D}},r):{fullHTML:"",outerHTML:""}}catch(s){return Yp.error("Failed to get HTML data for extended JSON backup",s),{}}}doesFolderExistInSaveDir(r){try{let i=`${this.testAssetsManager.getLocalSavePath()}/${r}`;return(0,r7e.statSync)(i).isDirectory()}catch(i){if(i.code==="ENOENT")return!1;throw i}}async saveToCloud(){try{let{testGenerationId:r}=await this.userStoryService.createTestGeneration();await this.saveTestFile();let i=await this.settingsService.getIsGitReflectionEnabled();if(!i){let p=new yRt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${r}/get-upload-url`),_=e(N=>({complete:!1,error:!1,response:void 0,info:N}),"buildUploadAsset"),v=[],E=this.userStoryService.getStory(),D=E==null?void 0:E.internalTestId,w=E==null?void 0:E.collectionName,B=`test-${D}.fix.checksum.spec.ts`;await p.uploadAsset(_({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:B,relativePath:w?`tests/${w}/${B}`:`tests/${B}`})),v.push(_({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),v.push(_({type:"har",path:await YFn(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(N=>N.eventCode==="upload_files").forEach(N=>{var L;(L=N.files)==null||L.forEach(M=>{v.push(_({type:"test-files",path:M}))})}),await Promise.all(v)}let s=this.actionsManager.actions.map(p=>({...p,parentFramesSelectors:p.parentFramesSelectors?p.parentFramesSelectors.filter(_=>_!=="iframe"):void 0})),c={};if(i){let p=this.userStoryService.getStory();p!=null&&p.version&&(c.version=p.version)}await this.apiService.post(`test-generation/${r}/completed`,{actions:s,metadata:Object.keys(c).length>0?c:void 0})}catch(r){Yp.error("Failed to upload test",r)}}};e(dMr,"VtgStorageService");var WRt=dMr;iNr();Bte();var _Mr=class _Mr{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(r){var i;this._executedActions=r,(i=this.storageService)==null||i.localSave()}addAction(r){var i;this._executedActions.push(r),(i=this.storageService)==null||i.localSave()}setActions(r){this._executedActions=r}updateAssertionById(r,i){let s=i;return this.executedActions=this._executedActions.map(c=>{var p;if(c.id===r){let _=!!((p=c.assertions)!=null&&p.find(({id:E})=>E===i.id)),v={...c};return _?v.assertions=c.assertions.map(E=>{if(E.id===i.id){let D={...E,...i};return s=D,D}return E}):v.assertions=[...c.assertions??[],i],{...v,assertions:v.assertions.sort((E,D)=>E.timestamp!==D.timestamp?E.timestamp-D.timestamp:E.createdAt-D.createdAt)}}return c}),s}setStorageService(r){this.storageService=r}createAction(r){var E,D,w;let{id:i,data:s,options:c,type:p}=r,_={id:i,...s},v=[...this._executedActions];switch(c==null?void 0:c.type){case"insertAfter":{let B=this.findActionOrAssertionById(c.afterStepId),N=v.findIndex(L=>L.id===B.action.id);if(B.assertion||(D=(E=B.action)==null?void 0:E.assertions)!=null&&D.length){let L=B.assertion??B.action.assertions[0],{before:M,after:V}=tua(((w=v[N])==null?void 0:w.assertions)??[],L.id,!!B.assertion);v[N].assertions=M,_.assertions=V.map(Z=>({...Z,actionId:_.id}))}N!==-1?v.splice(N+1,0,_):v.push(_);break}case"insertLast":v.push(_);break;case"replace":{let B=v.findIndex(N=>N.id===c.stepId);B!==-1&&v.splice(B,1,_);break}case"replaceLast":v.length>0&&(v[v.length-1]=_);break}return this.executedActions=v,_}pushExecutedActionOrAddAfterParent(r,i={}){if(i.previousActionId){let s=this._executedActions.findIndex(({id:c})=>c===i.previousActionId);if(s!==-1){let c={...r,timestamp:this._executedActions[s].timestamp+1};this._executedActions=[...this._executedActions.slice(0,s+1),c,...this._executedActions.slice(s+1)]}}else this.executedActions=Array.isArray(r)?[...this._executedActions,...r]:[...this._executedActions,r]}addManualActionsToExecuted(r){this.executedActions=[...this._executedActions,r]}updateExecutedAction(r){let i=this._executedActions.findIndex(({id:s})=>s===r.id);if(i!==-1){let s={...this._executedActions[i],...r};return this.executedActions=[...this._executedActions.slice(0,i),s,...this._executedActions.slice(i+1)],s}throw new Error("Action was not found")}deleteStep(r,i,s={assertionsOnly:!1,withAssertions:!0}){i==="Action"?this.deleteAction(r,s):i==="Assertion"&&(this.executedActions=this._executedActions.map(c=>(c.assertions=(c.assertions??[]).filter(p=>p.id!==r),c)))}deleteAction(r,i={assertionsOnly:!1,withAssertions:!0}){var c;let s=this._executedActions.find(p=>p.id===r);if(!s)throw new Error(`Action with id "${r}" not found`);i.assertionsOnly?this.executedActions=this._executedActions.map(p=>p.id===r?{...p,assertions:[]}:p):!i.withAssertions&&((c=s==null?void 0:s.assertions)!=null&&c.length)?this.deleteActionAndMergeAssertions(r):this.executedActions=this._executedActions.filter(p=>p.id!==r)}deleteActionAndMergeAssertions(r){let i=this._executedActions.findIndex(v=>v.id===r);if(i===-1)throw new Error(`Action with id "${r}" not found`);if(i===0)throw new Error("Cannot remove the first action; no previous action to merge assertions into");let s=this._executedActions[i-1],c=this._executedActions[i];c.assertions||(c.assertions=[]);let p=c.assertions.map(v=>({...v,actionId:s.id})),_={...s,assertions:[...s.assertions??[],...p]};this.executedActions=[...this._executedActions.slice(0,i-1),_,...this._executedActions.slice(i+1)]}clearTestSteps(r=!0){if(r){let{navigation:i,login:s}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((c,p)=>([i==null?void 0:i.id,s==null?void 0:s.id].includes(p.id)&&c.push({...p,assertions:[]}),c),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(r){this.clearTestSteps(!1),this.executedActions=r}findLoginAndNavigationActions(){let r=this._executedActions.find(({eventCode:s})=>s==="navigation"),i=this._executedActions.find(({eventCode:s})=>s==="login");return{navigation:r,login:i}}addAssertionToAction(r,i){this.executedActions=this._executedActions.map(s=>{if(s.id!==r.actionId)return s;if(s.assertions||(s.assertions=[]),i){let c=s.assertions.findIndex(({id:p})=>i===p);s.assertions.splice(c+1,0,r)}else s.assertions=[r,...s.assertions??[]];return s})}findActionByAssertionId(r){return this._executedActions.find(({assertions:i=[]})=>i.find(s=>s.id===r))}replaceAssertion(r,i){let s=this.findActionByAssertionId(i);if(!s)throw new Error(`No action found containing assertion with id ${i}`);this.executedActions=this._executedActions.map(c=>c.id===s.id?{...c,assertions:(c.assertions??[]).map(p=>p.id===i?{...r,actionId:s.id}:p)}:c)}findActionOrAssertionById(r){let i={action:null,assertion:null};if(this._executedActions.forEach(s=>{s.id===r&&(i.action=s);let c=(s.assertions??[]).find(p=>p.id===r);c&&(i={action:s,assertion:c})}),!i.action&&!i.assertion)throw new U6e(r);return i}async buildStepDataWithCode(r,{loadingFromFile:i}={loadingFromFile:!1}){let s=rua(r);return await Promise.all(s.map(async({step:c,type:p})=>{let _=await bke(d$e([c],void 0,{generateAssertionsCode:!1},(v,E)=>{c=E}));return{type:p,step:{...c,loadedFromFile:i},code:_}}))}};e(_Mr,"VtgActionsManager");var GRt=_Mr,tua=e((n,r,i=!0)=>{let s=Number(i),c=n.findIndex(v=>v.id===r);if(c===-1)return{before:n,after:[]};let p=n.slice(0,c+s),_=n.slice(c+s);return{before:p,after:_}},"splitArrayAtId"),rua=e(n=>n.reduce((r,i)=>{var p;let{assertions:s,...c}=i;if(r.push({step:c,type:"Action"}),(p=i.assertions)!=null&&p.length){let _=i.assertions.map(v=>({type:"Assertion",step:{...v,actionId:i.id}}));r.push(..._)}return r},[]),"transformActionsListToVTGStepsDataList");var bMt=H0(lMt()),JMn=H0(require("net")),zMn=H0(Kjr()),HMn=H0($Mn());var VUr=class VUr extends Error{constructor(r){super(r),this.name="ValidationError"}};e(VUr,"ValidationError");var Q$e=VUr,JUr=class JUr extends Error{constructor(r){super(r),this.name="NotFoundError"}};e(JUr,"NotFoundError");var q$e=JUr;g6();var vv=e(n=>(r,i,s)=>{Promise.resolve(n(r,i,s)).catch(c=>{if(Yp.error(`${r.method} ${r.path} error:`,c),c instanceof U6e)return i.status(200).json({error:c.message});if(c instanceof Q$e)return i.status(400).send({error:c.message});if(c instanceof q$e)return i.status(404).send(c.message);s(c)})},"asyncErrorHandler");g6();var zUr=H0(lMt());var $$e=class $$e{constructor(){this.routesLogRules={};this.router=(0,zUr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(r){let i=(0,zUr.Router)(),s=r.startsWith($$e.DEFAULT_API_PREFIX)?r:`${$$e.DEFAULT_API_PREFIX}${r.startsWith("/")?r:`/${r}`}`;return this.router.use(s,i),i}startAsyncProcess(r,i,s,c="unknown"){Yp.info(`Starting async ${c} process: ${i} for step: ${s}`),r().catch(p=>{Yp.error(`Async process ${i} failed:`,p)})}};e($$e,"VTGController"),$$e.DEFAULT_API_PREFIX="/api";var j5=$$e;var HUr=class HUr extends j5{constructor(i,s,c,p){super();this.assertionsService=i;this.actionsManager=s;this.actionsService=c;this.aiTestGenerationService=p;this.setupRoutes()}setupRoutes(){let i=this.createPrefixedRouter(""),s=this.createPrefixedRouter("/steps");i.post("/createStep",vv(async(c,p)=>{let _=c.body,v;_.type==="Assertion"&&(v=this.assertionsService.createAssertion(_)),_.type==="Action"&&(v=this.actionsManager.createAction(_));let E=await bke(d$e([v],void 0,{generateAssertionsCode:!1},(D,w)=>{v=w}));return p.status(200).json({step:v,code:E})})),i.patch("/updateStep",vv(async(c,p)=>{let _=c.body,v=_==null?void 0:_.options,E;_.type==="Assertion"&&(E=await this.assertionsService.updateAssertion({id:_.id,data:_.data})),_.type==="Action"&&(E=this.actionsManager.updateExecutedAction({..._.data,id:_.id}));let D;v!=null&&v.forceUpdateTimestamp||(_.data.thought===""&&(E.thought=void 0),D=await bke(d$e([E],void 0,{generateAssertionsCode:!1},(w,B)=>{E=B}))),p.status(200).json({step:E,code:D})})),i.delete("/deleteStep",vv(async(c,p)=>{let{id:_,options:v,type:E}=c.body;return this.actionsManager.deleteStep(_,E,v),p.status(200).send({message:"Success!"})})),i.post("/clear-test",vv(async(c,p)=>{let _=this.actionsManager.clearTestSteps();return p.status(200).send(_)})),s.post("/execute",vv(async(c,p)=>{let _=c.body;try{let v=null;return vga(_)?v=await this.aiTestGenerationService.executeAction(_):Aga(_)&&(v=await this.actionsService.executeAction(_)),p.status(200).json(v)}catch(v){return p.status(400).send({error:v.message})}})),i.put("/steps",vv(async(c,p)=>(this.actionsManager.pushExecutedActionOrAddAfterParent(c.body.action,c.body.options),p.send("success")))),i.post("/code-to-steps",vv(async(c,p)=>{let v=qFn(c.body.code).map(E=>E&&"isChecksumAiWithDirectExpression"in E?{...E,isChecksumAiWithDirectExpression:!1}:E);return p.status(200).send(v)})),i.post("/steps-to-code",vv(async(c,p)=>{let _=d$e(c.body.steps,void 0,{generateAssertionsCode:!1});return p.status(200).send(_)}))}};e(HUr,"VtgStepsController");var pMt=HUr;function vga(n){var r;return((r=n.options)==null?void 0:r.isAISuggestion)===!0}e(vga,"isAIExecuteActionArgs");function Aga(n){var r;return((r=n.options)==null?void 0:r.isAISuggestion)===!1}e(Aga,"isManualExecuteActionArgs");g6();var WUr=class WUr extends j5{constructor(i){super();this.locatorsService=i;this.setupRoutes()}setupRoutes(){let i=this.createPrefixedRouter("/locators"),s=this.createPrefixedRouter("/ai/locators");i.post("/play",vv(async(c,p)=>{let _=c.body;try{let v=await this.locatorsService.verifyLocatorOrSelector(_);return p.status(200).send(v)}catch(v){return p.status(400).send({error:v.message})}})),s.post("/generate",vv(async(c,p)=>{let{step:_,target:v,processId:E}=c.body;_.isDefaultThought&&(_.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(_,v,E),E,v.id,"AI locators generation");let D={processId:E,stepId:v.id,success:!0};return p.status(200).json(D)}catch(D){return Yp.error("Error generating AI locators:",D),p.status(500).send({processId:E,error:D.message})}})),s.post("/extract-css",vv(async(c,p)=>{let{step:_,target:v,processId:E,llmLocators:D}=c.body;_.isDefaultThought&&(_.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(_,v,E,D),E,v.id,"CSS extraction");let w={processId:E,stepId:v.id,success:!0};return p.status(200).json(w)}catch(w){return Yp.error("Error extracting CSS locators:",w),p.status(500).send({processId:E,error:w.message})}})),s.post("/filter",vv(async(c,p)=>{let{step:_,target:v,processId:E,candidates:D}=c.body;_.isDefaultThought&&(_.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(_,v,E,D),E,v.id,"locators filtering");let w={processId:E,stepId:v.id,success:!0};return p.status(200).json(w)}catch(w){return Yp.error("Error filtering locators:",w),p.status(500).send({processId:E,error:w.message})}})),s.delete("/process/:id",vv(async(c,p)=>{let{id:_}=c.params;return await this.locatorsService.cancelProcess(_),Yp.info("Cancelled process",_),p.status(200).send({success:!0})})),i.post("/identical",vv(async(c,p)=>{let{locator:_,compareLocator:v,timestamp:E}=c.body;try{let D=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(_,v,E);return p.status(200).send(D)}catch(D){return p.status(400).send({error:D.message})}})),i.post("/verify",vv(async(c,p)=>{try{let _=await this.locatorsService.verifyLocatorOrSelector(c.body);return p.status(200).send(_)}catch(_){return p.status(400).send({error:_.message})}}))}};e(WUr,"VtgLocatorsController");var fMt=WUr;var GUr=class GUr extends j5{constructor(i){super();this.codeService=i;this.routesLogRules={"/monaco/editor/types":{skipRequestData:!0,skipResponseData:!0}};this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/monaco").post("/editor/types",vv(async(s,c)=>{let{libs:p}=s.body;try{let _=this.codeService.getTypesForLibs(p??[]);return c.status(200).send({types:_})}catch(_){return c.status(400).send({error:_.message})}}))}};e(GUr,"MonacoController");var dMt=GUr;Q0e();var xga=h1.enum(["openai","anthropic","google-vertexai","groq"]),VMn=h1.strictObject({message:h1.string(),selection:h1.object({locator:h1.string()}).optional(),stepCode:h1.string().optional(),messageHistory:h1.array(h1.object({type:h1.enum(["user","assistant"]),content:h1.string(),timestamp:h1.string(),stepId:h1.string()})).optional(),model:h1.object({id:h1.string(),name:h1.string(),type:xga,model:h1.string(),thinking:h1.boolean().optional()}).optional(),includeImage:h1.boolean().optional(),includeHtml:h1.boolean().optional(),includeCode:h1.boolean().optional(),timestamp:h1.number(),error:h1.string().optional()});var KUr=class KUr extends j5{constructor(i){super();this.aiChatService=i;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",vv(async(s,c)=>{let p=VMn.safeParse(s.body);if(!p.success){c.status(400).json({error:"Invalid request body",details:p.error.format()});return}try{let _=await this.aiChatService.processMessage(p.data);c.json(_)}catch(_){c.status(500).json({error:"Failed to process message",message:_ instanceof Error?_.message:"Unknown error"})}}))}};e(KUr,"AIChatController");var _Mt=KUr;var WMn=H0(require("path"));aw();g6();var YUr=class YUr extends j5{constructor(i,s,c){super();this.storageService=i;this.actionsManager=s;this.actionsService=c;this.setupRoutes()}setupRoutes(){let i=this.createPrefixedRouter("/test"),s=this.createPrefixedRouter("");i.post("/generate-test-file-string",vv(async(c,p)=>{try{return await this.storageService.generateTestFileString(c.body.fileName),p.send("success")}catch(_){return p.status(400).send({error:_.message})}})),i.post("/upload",vv(async(c,p)=>(await this.storageService.saveToCloud(),p.send("success")))),i.post("/local-save",vv(async(c,p)=>{await this.storageService.localSave(),p.send("success")})),s.post("/reload-test-from-file",vv(async(c,p)=>{if(!this.storageService.isLoadedFromTestFile)throw new q$e("No test file found");let _=await this.storageService.reloadTestFromFile(c.body.useLLM),v=await this.actionsManager.buildStepDataWithCode(_,{loadingFromFile:!0});return p.status(200).send(v)})),i.post("/verify-save-location",vv(async(c,p)=>{try{let _=this.storageService.doesFolderExistInSaveDir(c.body.location);p.send({exists:_})}catch(_){p.status(400).send({error:_})}})),i.post("/backup",vv(async(c,p)=>{let{backupFolderName:_}=c.body;if(!hwn(_))throw Yp.error("Invalid folder name",{backupFolderName:_}),new Q$e("Invalid folder name");let v=await this.storageService.localBackup(_);p.send(v)})),i.post("/extended-json-backup",vv(async(c,p)=>{let _=this.storageService.extendedJSONBackup();p.send(_)})),s.post("/upload-files",vv(async(c,p)=>{let _=await this.actionsService.uploadFiles(c.body.files);return p.status(200).json(_)}))}};e(YUr,"VtgStorageController");var mMt=YUr;var XUr=class XUr extends j5{constructor(i){super();this.aiTestGenerationService=i;this.setupRoutes()}setupRoutes(){let i=this.createPrefixedRouter("/ai");i.post("/init",vv(async(s,c)=>{await this.aiTestGenerationService.init(),c.send("success")})),i.post("/iterate",vv(async(s,c)=>{let p=await this.aiTestGenerationService.iterate(s.body);return p?c.status(200).json(p):c.status(400).send("no action generated")})),i.post("/stop",vv(async(s,c)=>{this.aiTestGenerationService.stop(),c.send("success")}))}};e(XUr,"VtgAITestGenerationController");var hMt=XUr;var ZUr=class ZUr extends j5{constructor(i){super();this.thoughtsService=i;this.setupRoutes()}setupRoutes(){let i=this.createPrefixedRouter("/thoughts");i.post("/actions/generate",vv(async(s,c)=>{let p=s.body,{processId:_,action:{id:v}}=p;try{this.startAsyncProcess(()=>this.thoughtsService.generateActionThoughts(p),_,v,"action thoughts generation");let E={processId:_,stepId:v,success:!0};c.status(200).send(E)}catch(E){return c.status(400).send({processId:_,error:E.message})}})),i.post("/assertions/generate",vv(async(s,c)=>{let p=s.body,{processId:_,assertion:{id:v}}=p;try{this.startAsyncProcess(()=>this.thoughtsService.generateAssertionThought(p),_,v,"assertion thoughts generation");let E={processId:_,stepId:v,success:!0};c.status(200).send(E)}catch(E){return c.status(400).send({processId:_,error:E.message})}})),i.post("/stop-generate",vv(async(s,c)=>{let p=s.body;this.thoughtsService.stopGeneratingThought(p.stepId);let _={stepId:p.stepId};return c.status(200).send(_)}))}};e(ZUr,"VtgThoughtsController");var gMt=ZUr;var eQr=class eQr extends j5{constructor(i,s){super();this.assertionsService=i;this.aiAssertionsService=s;this.setupRoutes()}setupRoutes(){let i=this.createPrefixedRouter("/assertions"),s=this.createPrefixedRouter("/assertion");i.post("/generate",vv(async(c,p)=>{let _=c.body,{processId:v,id:E}=_;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(_),v,E,"AI assertion generation");let D={processId:v,stepId:E,success:!0};return p.status(200).json(D)}catch(D){return p.status(500).send({processId:v,error:D.message})}})),i.post("/stop-generate",vv(async(c,p)=>{let{id:_}=c.body,v={stepId:_};return this.aiAssertionsService.stopGenerateAiAssertions(_),p.status(200).send(v)})),s.post("/verify/time-machine",vv(async(c,p)=>{let _=await this.assertionsService.verifyOnTimeMachine(c.body);return p.status(200).send(_)})),s.post("/verify/live",vv(async(c,p)=>{let _=c.body;try{let v=await this.assertionsService.verifyOnLive(_),E=v.success?200:404;return p.status(E).send(v)}catch(v){return p.status(404).send({success:!1,message:String(v)})}})),s.post("/save",vv(async(c,p)=>{let _=await this.assertionsService.updateAssertion(c.body);p.status(200).json(_)}))}};e(eQr,"VtgAssertionsController");var yMt=eQr;var tQr=class tQr extends j5{constructor(i){super();this.settingsService=i;this.setupRoutes()}setupRoutes(){let i=this.createPrefixedRouter("/settings");i.get("/",vv(async(s,c)=>{let p=this.settingsService.getSettings();return c.status(200).send(p)})),i.post("/",vv(async(s,c)=>(this.settingsService.updateSettings(s.body),c.status(200).send({message:"Success!"}))))}};e(tQr,"VtgSettingsController");var vMt=tQr;g6();var GMn=H0(lMt());var rQr=class rQr extends j5{constructor(i){super();this.evaluatorService=i;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/evaluator").post("/execute",vv(async(s,c)=>{try{let p=await this.evaluatorService.execute(s.body.code);return c.status(200).json(p)}catch(p){return c.status(500).send({message:"Error during code evaluation",error:p.message})}}))}};e(rQr,"VtgEvaluatorController");var AMt=rQr;aw();g6();var nQr=class nQr{constructor(){this.reqIndex=0;this.reqInProcess={};this.routesLogRules={};this.intervalTimer=null}setRoutesLogRules(r){this.routesLogRules=r}cleanup(){this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null)}startListening(r,i,s){Hd.vtg.logAPIServer.interval&&this.handleIntervalLog(r,i,s),!(Hd.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(r,i,s))&&s()}logInterval(){Hd.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let r=Object.values(this.reqInProcess);r.length&&(Yp.info("HTTP REQUESTS IN PROCESS"),Yp.info(r.map(i=>JSON.stringify(i,null,2)).join(`
1789
- `)))},5e3))}handleIntervalLog(r,i,s){let c=this.reqIndex++;this.reqInProcess[c]=this.buildLogInfo(r,i,0,"","INTERVAL"),i.on("finish",()=>{let p=Date.now()-this.reqInProcess[c].start;delete this.reqInProcess[c]})}handleTransactionLog(r,i,s){if(this.getRouteRules(r.originalUrl).skip)return s(),!0;let p=Date.now(),_=this.buildLogInfo(r,i,0,"","REQUEST"),v="";Yp.info("REQUEST INFO",JSON.stringify(_,null,2));let E=i.write,D=i.end;return i.write=function(w,...B){return w&&(v+=w.toString()),E.call(this,w,...B)},i.end=function(w,...B){return w&&(v+=w.toString()),D.call(this,w,...B)},i.on("finish",()=>{if(Hd.vtg.logAPIServer.httpTransactions){let w=Date.now()-p,B=this.buildLogInfo(r,i,w,v,"RESPONSE");Yp.info("RESPONSE INFO",JSON.stringify(B,null,2))}}),!1}buildLogInfo(r,i,s,c,p="RESPONSE"){let _=this.getRouteRules(r.originalUrl),v={method:r.method,url:r.originalUrl,start:Date.now()};return p==="INTERVAL"||(p==="REQUEST"&&!_.skipRequestData&&r.body&&(v.data=r.body),p==="RESPONSE"&&(s&&(v.duration=`${s}ms`),v.statusCode=i.statusCode,v.size=i.getHeader("content-length")||"unknown",!_.skipResponseData&&c&&(v.data=c))),v}getRouteRules(r){if(this.routesLogRules[r])return this.routesLogRules[r];for(let[i,s]of Object.entries(this.routesLogRules))if(r.includes(i))return s||{};return{}}};e(nQr,"VTGExpressServerRoutesLoggerMiddleware");var xMt=nQr;var iQr=class iQr{constructor(r,i,s,c,p,_,v,E,D,w,B,N){this.actionsService=r;this.assertionsService=i;this.locatorsService=s;this.aiTestGenerationService=c;this.aiAssertionsService=p;this.aiThoughtsService=_;this.actionsManager=v;this.storageService=E;this.settingsService=D;this.monacoService=w;this.evaluatorService=B;this.aiChatService=N;this.errorHandler=e((r,i,s,c)=>{Yp.error("Error catch in middleware:",r),s.status(500).send({error:r.message})},"errorHandler");this.routesLoggerMiddleware=new xMt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,bMt.default)(),this.app.use((0,HMn.default)()),this.app.use(zMn.default.json({limit:"50mb"})),this.app.use(bMt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(bMt.default.static(WMn.default.join(Hd.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(r=>{this.app.listen(this.port,()=>{Yp.info(`Express server running on port ${this.port}`),r()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),Yp.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((r,i)=>{let s=JMn.default.createServer();s.unref(),s.on("error",i),s.listen(0,()=>{let c=s.address().port;s.close(()=>{r(c)})})})),this.port}async evaluateServerPort(r){if(!r)throw new Error("Page not initialized");await r.evaluate(i=>{window.vtg.setServerPort(i)},this.port)}initializeControllers(){let r=new pMt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),i=new mMt(this.storageService,this.actionsManager,this.actionsService),s=new hMt(this.aiTestGenerationService),c=new gMt(this.aiThoughtsService),p=new yMt(this.assertionsService,this.aiAssertionsService),_=new vMt(this.settingsService),v=new fMt(this.locatorsService),E=new dMt(this.monacoService),D=new _Mt(this.aiChatService),w=new AMt(this.evaluatorService),B=[r,i,s,c,p,_,v,E,w,D],N=(0,GMn.Router)(),L={};return B.forEach(M=>{N.use(M.getRouter()),L={...L,...M.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(L),N}};e(iQr,"VtgExpressServer");var EMt=iQr;var CMt=require("fs");var Zlt=class Zlt{constructor(r,i,s,c){this.projectRootDirectory=r;this.checksumRoot=i;this.internalFilesDir=s;this.vtgTestFileRunConfig=c;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,CMt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,CMt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,CMt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${Zlt.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(r){var i;return((i=this.vtgTestFileRunConfig)==null?void 0:i.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${r}.json`}getLocalSaveAsPath(){return this.currentSaveAsLocation??(this.currentSaveAsLocation=`${Date.now()}_save`),`${this.localSaveFolderPath}/${this.currentSaveAsLocation}`}getSavedTestFilePath(){if(!this.vtgTestFileRunConfig)throw new Error("vtgTestFileRunConfig is required to get the test file save as path");if(this.currentSaveAsLocation){let r=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${r}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(r){r&&!(r!=null&&r.startsWith("auto-save"))&&(this.currentSaveAsLocation=r)}};e(Zlt,"VtgTestAssetsManager"),Zlt.AUTO_SAVE_FOLDER_NAME="auto-save";var DMt=Zlt;var bga={useCDPSession:!0,trackLoadedResources:!0},aQr=class aQr extends POt{constructor(i={},s={devtools:!1},c={},p,_){super({...bga,...i},s,p,_);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(i,s=1e3)=>{try{return await i.waitForFunction(()=>!!window.checksum,void 0,{timeout:s}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async i=>{try{return await i.waitForFunction(()=>{var s;return!!((s=window.checksum)!=null&&s.testGenerator)}),i.evaluate(async({appSpecificRules:s,config:c,initModules:p})=>{window.checksum.testGenerator.init(s,c,p)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(i)})}catch(s){console.log("initInjectedScript exception",s)}},"initInjectedScript");this.settings={...this.settings,...c},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(i={}){let s=await super.prepare(i);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")}),s}setEvaluateWithChecksumTargetFrame(i){this.evaluateWithChecksumTargetFrame=i}getInjectedScriptInitModules(i){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(i,s,c=this.evaluateWithChecksumTargetFrame){let p=this.injectedScriptManager.getNavigationPromise(c);p&&await p;try{return c.evaluate(i,s)}catch(_){throw console.error("evaluateWithChecksum error",_,i.toString()),_}}async getBestMatchingElementSimilarityScore(i){return this.evaluateWithChecksum(async s=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(s),i)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(i){return this.evaluateWithChecksum(s=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(s),i)}async takeElementSnapshot(i,s,c={},p={}){try{let{snapshot:_,elementLocator:v}=await super.takeElementSnapshot(i,s,c);if(!_||!c.takeBodyScreenshot)return _?{snapshot:_}:{};await this.highlightElementByLocator(v,c.mousePosition);let E=await this.takePageSnapshot(p);return await this.clearHighlights(),{snapshot:_,bodySnapshot:E}}catch(_){return console.error("[ChecksumWebDriver] takeElementSnapshot error",_),{}}}async highlightElementByLocator(i,s,c="20px solid rgba(255,0,0,1)",p=!1){return this.evaluateWithChecksum(async([_,v,E,D])=>{window.checksum.testGenerator.highlightElement(_,{highlightStyle:{outline:v},mousePosition:E,scroll:D})},[await i.elementHandle(),c,s,p])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(aQr,"ChecksumWebDriver");var SMt=aQr;var KMn=require("fs"),YMn=H0(require("path"));var sQr=require("fs");aw();g6();var oQr=class oQr{constructor(r,i,s=Hd.vtg.localBuildPath){this.page=r;this.serverPort=i;this.filePath=s;this.filePath=s,Yp.info("[VTG] FrontendLauncher initialized with:",{serverPort:i,filePath:s,appSource:Hd.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(r){throw Yp.error("An error occurred:",r),r}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let r;switch(Hd.vtg.appSource){case"served-app":r=Hd.vtg.appURL;break;case"served-build-file":r=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":r=Hd.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${Hd.vtg.appSource}`)}await this.page.goto(r,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(Hd.vtg.appSource==="build-file")try{let r=await sQr.promises.readFile(this.filePath,"utf8"),i=/(src|href)=(["'])(\/)static/g,s=r.replace(i,"$1=$2.$3static");await sQr.promises.writeFile(this.filePath,s,"utf8"),Yp(`Successfully modified ${this.filePath}`)}catch(r){Yp.error(`Error processing file ${this.filePath}:`,r)}}};e(oQr,"VtgFrontendLauncher");var wMt=oQr;yIt();aw();pNr();g6();USr();L8t();iS();var Ega=1e3,kMt=class kMt extends SMt{constructor(i={},s={devtools:!1},c={},p){var _,v,E;super(i,s,kMt.makeSettings(c),(_=p==null?void 0:p.getFramesMessageBroker)==null?void 0:_.call(p),Hd.vtg.isSeparateProcess?void 0:((E=(v=p==null?void 0:p.context())==null?void 0:v._rawContext)==null?void 0:E.call(v))??(p==null?void 0:p.context()));this.liveAppPage=p;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async i=>{this.appFrame=i,await this.frameMsgBroker.register("live",this.appFrame,Hd.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new Fge(this.frameMsgBroker,this.injectedScriptManager,{webProxy:i.webProxy}),this.liveTimeMachine=new Fge(this.frameMsgBroker,this.injectedScriptManager,{webProxy:i.webProxy}),this.appViewport=c.viewport,this.completeOriginHeaderOnLivePage=c.completeOriginHeaderOnLivePage}static makeSettings(i={}){return LBt({frontendTestGenerationConfig:{showFrontendLogs:Hd.isDevMode}},i)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(i){this.registeredTimeMachineFrames.push(i)}async prepare(i={},s={}){let c=await super.prepare(i);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{Yp.error("Page closed")}),this.liveAppPage&&!Hd.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new wMt(this.page,s.serverPort).start();let p=e(async(v=2)=>{if(this.timeMachineFrame=this.page.frames().find(E=>E.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(E=>E.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(v>0)return Yp.info("Waiting for frames to be available"),await lb(Ega),p(v-1);{let E="Could not connect to VTG frontend, check that the app is available";throw Yp.error(E),new Error(E)}}},"getFrames");await p();let _;return this.liveAppPage?(_=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(_,{completeOriginHeader:!0})):(_=await this.context.newPage(),await _.setViewportSize(this.appViewport)),await this.onAppFrameCreated(_.mainFrame()),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),c}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){Yp.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async s=>{let c=this.appFrame;if(!c){Yp.info("no live frame detected");return}try{return c.evaluate(p=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(p),s)}catch(p){Yp.error("Error getting frame window",p)}})}catch(i){Yp.warning(`Failed to expose checksumGetFilesFromLive: ${i.message}`)}}async navigate(i){return this.appFrame.goto(i)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let i=new L1e(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:Yp.info,logError:Yp.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),s=await super.createPage();return kje.makePage(s,i,this.injectedScriptManager,this.context)}getInjectedScriptInitModules(i){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(i)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:i===this.appFrame?{...super.getInjectedScriptInitModules(i),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(i)}async interceptPageRequests(){async function i(c){try{return await KMn.promises.readFile(c,"utf8")}catch(p){return Yp.error(`Error reading file ${c}:`,p),null}}e(i,"readLocalFile");function s(c){switch(YMn.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(s,"getContentType"),await this.page.route("**/*",async c=>{try{let p=c.request().url();if(console.log("intercepted!",p),p.startsWith("file://")){let _=p.replace("file://",""),v=await i(_);v!==null?await c.fulfill({status:200,contentType:s(_),body:v}):await c.abort()}else{let _=0,v=5;for(;_<v;){let E=await c.fetch(),D=E.status();if(D>299&&D<400){_++;let w=E.headers().location;if(!w){Yp.warning("Redirect without Location header",{url:p}),await c.abort();return}console.log(`Redirect ${_} to: ${w}`),c.request().url=()=>new URL(w,p).toString()}else{let w={};w["Access-Control-Allow-Origin"]="*",w["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",w["Access-Control-Allow-Headers"]="Content-Type, Authorization",await c.fulfill({response:E,headers:{...E.headers(),...w,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}Yp.warning(`Max redirects (${v}) exceeded`),await c.abort()}}catch(p){Yp.warning("intercept error",p)}})}};e(kMt,"ChecksumVTGWebDriver");var TMt=kMt;var V$e=require("fs");aw();var XMn=".settings.json",cQr=class cQr{constructor(r,i,s){this.checksumRoot=r;this.apiService=i;this.internalFilesDir=s;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=s?`${this.internalFilesDir}/${XMn}`:`${this.checksumRoot}/${XMn}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:Hd.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:Hd.vtg.aiAssertions.disabled,disableAILocators:Hd.vtg.aiLocators.disabled}}updateSettings(r){this.settings=Object.assign(this.settings,r),this.writeSettingsData()}readSettings(){if(!(0,V$e.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let r=(0,V$e.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(r),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,V$e.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(cQr,"VtgSettingsService");var ept=cQr;Byr();var f7e=require("fs");g6();var uQr=class uQr{constructor(r,i,s){this.timeMachine=r;this.actionsManager=i;this.userStoryService=s}async generatePromptData(r,i){let s=e(()=>{let{timestamps:D,...w}=this.cachedPromptData;return{...w,action:r}},"returnPromptDataFromCache"),c=r.id;if(this.canUseCachedPromptData(r))return s();let p=this.getActionTimestamps(c,i);if(!p)return;let _=await this.timeMachine.executeReducedHTMLTask(p.before),v=await this.timeMachine.executeReducedHTMLTask(p.after),E=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:v,previousReducedHTML:_,actionId:c,previousActions:this.getPreviousActions(c),action:r,title:E.goal,steps:E.instructions,timestamps:p},s()}canUseCachedPromptData(r){var i,s;return this.cachedPromptData&&this.cachedPromptData.actionId===r.id&&this.cachedPromptData.action.timestamp===r.timestamp&&((i=this.cachedPromptData.timestamps)==null?void 0:i.before)===r.timestamp&&((s=this.cachedPromptData.timestamps)==null?void 0:s.after)===r.timestamp}getPreviousActions(r){let i=this.actionsManager.actions,s=i.findIndex(c=>Number(c.id)===Number(r));return i.slice(0,s)}async generatePromptDataForThought(r,i){return this.generatePromptData(r,i)}getActionTimestamps(r,i){let s=this.actionsManager.actions,c=s.findIndex(v=>v.id===r);if(c===-1){Yp.error(`[init] No action with id ${r} was found in executed actions`);return}let p=s[c],_=s[c+1];return{before:p.timestamp,after:(_==null?void 0:_.timestamp)??i}}};e(uQr,"ActionsAgent");var IMt=uQr;g6();aw();var lQr=class lQr extends j6e{constructor(i,s,c,p,_){super(i,s,c);this.actionsManager=i;this.apiService=s;this.userStoryService=c;this.webDriver=_;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new rqe(p,i,s,this.remoteSessionId,{logPerformance:Hd.vtg.aiAssertions.logPerformance}),this.actionsAgent=new IMt(p,i,this.userStoryService)}async init({retriesLeft:i=3,keepActionsWithoutDescription:s=!1,lastActionId:c=void 0}={}){await super.init({retriesLeft:i,keepActionsWithoutDescription:s,lastActionId:c}),this.activeRemoteSessionIdByStepId.set(c,this.remoteSessionId)}async generateActionThoughts({action:i,processId:s}){try{if(this.isRunning(i.id))throw Yp.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let c=await this.actionsAgent.generatePromptDataForThought(i),p=await this.callThoughtApi("actions",c,s);return this.evaluateThoughtResponse({processId:s,id:i.id,thought:p.thought})}catch(c){return Yp.error("Error in AI thought generation",c),this.evaluateThoughtResponse({processId:s,id:i.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(i.id)}}async generateAssertionThought({assertion:i,parentActionId:s,processId:c}){let p=s||i.actionId;try{if(this.isRunning(i.id))throw Yp.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let _=await this.assertionsAgent.generateThoughtPromptData(p,i),v=await this.callThoughtApi("assertions",_,c);return this.evaluateThoughtResponse({processId:c,id:i.id,thought:v.thought})}catch(_){return Yp.error("Error in AI thought generation",_),this.evaluateThoughtResponse({processId:c,id:i.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(i.id)}}stopGeneratingThought(i){this.activeRemoteSessionIdByStepId.delete(i)}async callThoughtApi(i,s,c){let p=Date.now();if(s)try{p=Date.now();let _=await this.apiService.post(`${i}/thoughts/generate`,{sessionId:this.remoteSessionId,data:s});if(!_.ok){Yp.error(`Request for ${i} thought generation failed with status ${_.status}`);return}let v=await _.json();if(!(v!=null&&v.thought))throw Yp("No thought generated for action, got response",_),new Error("No thought generated");let E=i==="actions"?s.action:s.assertion;return Yp(`Thought generated (${c})`,{type:i,stepId:E.id,locator:E.locator,thought:v.thought}),v}catch(_){throw Yp.error(`Error in AI thought generation (${c})`,_),_}}isRunning(i){return this.activeRemoteSessionIdByStepId.has(i)}async evaluateThoughtResponse({id:i,processId:s,thought:c,error:p=!1}){try{await this.webDriver.page.evaluate(({id:_,thought:v,error:E,processId:D})=>{window.vtg.onAsyncProcessResponse({id:_,processId:D,thought:v,error:E})},{id:i,thought:c,error:p,processId:s})}catch(_){Yp.error("Error in AI thought generation",_)}}};e(lQr,"VTGThoughtsService");var FMt=lQr;var pQr=class pQr{constructor(r=new NQe){this._variableStore=r}get variableStore(){return this._variableStore}};e(pQr,"VTGVariableStoreService");var PMt=pQr;var z$e=H0(sw()),ejn=require("net"),tjn=require("crypto");aw();var fQr=class fQr{constructor(r){this.processMessage=r;this.buffer=""}makeMessage(r){return`$CKSM_EVAL_MESSAGE:${r.length}$${r}`}async onMessage(r,i){for(this.buffer+=i.toString();;){let s=this.buffer.match(/^\$CKSM_EVAL_MESSAGE:(\d+)\$/);if(!s)break;let c=parseInt(s[1],10),p=s[0].length,_=p+c;if(this.buffer.length<_)break;let v=this.buffer.slice(p,_);this.buffer=this.buffer.slice(_);try{let E=JSON.parse(v);await this.processMessage(E,r)}catch(E){console.error("Failed to parse message:",E)}}}};e(fQr,"VtgBridgeMessageParser");var J$e=fQr;var rf=H0(sw());var dQr=class dQr{constructor(){this.declaredVariables=new Set}transformVariables(r){let i=rf.createSourceFile("snippet.ts",r,rf.ScriptTarget.Latest,!0),s=new Set;rf.forEachChild(i,E=>{rf.isVariableStatement(E)&&E.declarationList.declarations.forEach(D=>{rf.isIdentifier(D.name)?(s.add(D.name.text),this.declaredVariables.add(D.name.text)):(rf.isArrayBindingPattern(D.name)||rf.isObjectBindingPattern(D.name))&&(this.collectBindingNames(D.name,s),this.collectBindingNames(D.name,this.declaredVariables))})});let p=rf.transform(i,[e(E=>{let D=E.factory,w=[new Map],B=e(M=>w[w.length-1].has(M),"isVariableLocallyDeclared"),N=new Set,L=e(M=>{if(rf.isBlock(M)||rf.isFunctionLike(M)){if(w.push(new Map),rf.forEachChild(M,Z=>{if(rf.isVariableStatement(Z))for(let ue of Z.declarationList.declarations)rf.isIdentifier(ue.name)?w[w.length-1].set(ue.name.text,ue):(rf.isArrayBindingPattern(ue.name)||rf.isObjectBindingPattern(ue.name))&&this.collectBindingNamesForScope(ue.name,w[w.length-1])}),rf.isFunctionLike(M))for(let Z of M.parameters)rf.isIdentifier(Z.name)?(w[w.length-1].set(Z.name.text,Z),N.add(Z.name.text)):(rf.isArrayBindingPattern(Z.name)||rf.isObjectBindingPattern(Z.name))&&this.collectBindingNamesForScope(Z.name,w[w.length-1]);let V=rf.visitEachChild(M,L,E);return w.pop(),V}if(rf.isArrowFunction(M))for(let V of M.parameters)rf.isIdentifier(V.name)?(w[w.length-1].set(V.name.text,V),N.add(V.name.text)):(rf.isArrayBindingPattern(V.name)||rf.isObjectBindingPattern(V.name))&&this.collectBindingNamesForScope(V.name,w[w.length-1]);if(rf.isBinaryExpression(M)&&M.operatorToken.kind!==rf.SyntaxKind.EqualsToken){let V=rf.visitNode(M.left,L),Z=rf.visitNode(M.right,L);return D.createBinaryExpression(V,M.operatorToken,Z)}if(rf.isVariableDeclaration(M)&&M.initializer){let V=rf.visitNode(M.initializer,L);return D.createVariableDeclaration(M.name,M.exclamationToken,M.type,V)}if(rf.isVariableStatement(M)&&M.parent===i){let V=M.declarationList.declarations,Z=[];for(let ue of V)if(rf.isObjectBindingPattern(ue.name)||rf.isArrayBindingPattern(ue.name)){let le=ue.initializer?rf.visitNode(ue.initializer,L):void 0,de=this.handleBindingPattern(ue.name,le,D,E);Z.push(...de.statements)}else if(rf.isIdentifier(ue.name)){let le=ue.name.text,de=ue.initializer?rf.visitNode(ue.initializer,L):void 0,xe=this.createGlobalAssignment(le,de,D);Z.push(xe)}return Z.length===0?D.createEmptyStatement():Z.length===1?Z[0]:D.createBlock(Z,!0)}if(rf.isIdentifier(M)&&!this.isLeftSideOfAssignment(M)&&!rf.isPropertyAccessExpression(M.parent)&&!this.isPropertyOfElementAccess(M)&&!this.isDeclarationName(M)&&!this.isPropertyNameInObjectLiteral(M)&&!N.has(M.text)&&this.declaredVariables.has(M.text)){let V=M.text;return w[w.length-1].has(V)||this.isInShadowingTestCase(M)?M:this.createGlobalThisAccess(V,E)}if(rf.isBinaryExpression(M)&&M.operatorToken.kind===rf.SyntaxKind.EqualsToken&&rf.isIdentifier(M.left)&&this.declaredVariables.has(M.left.text)&&!B(M.left.text)&&!N.has(M.left.text)){let V=M.left.text,Z=rf.visitNode(M.right,L);return D.createAssignment(this.createGlobalThisAccess(V,E),Z)}if(rf.isPropertyAccessExpression(M)&&rf.isIdentifier(M.expression)&&this.declaredVariables.has(M.expression.text)&&!B(M.expression.text)&&!N.has(M.expression.text)){let V=M.expression.text,Z=M.name.text,ue=this.createGlobalThisAccess(V,E);return D.createPropertyAccessExpression(ue,Z)}return rf.visitEachChild(M,L,E)},"visit");return M=>rf.isSourceFile(M)?rf.visitEachChild(M,L,E):rf.visitNode(M,L)},"transformer")]),v=rf.createPrinter().printFile(p.transformed[0]);return p.dispose(),v}clearDeclaredVariables(){this.declaredVariables.clear()}addDeclaredVariable(r){this.declaredVariables.add(r)}getDeclaredVariables(){return new Set(this.declaredVariables)}collectBindingNames(r,i){for(let s of r.elements)rf.isBindingElement(s)&&(rf.isIdentifier(s.name)?i.add(s.name.text):(rf.isObjectBindingPattern(s.name)||rf.isArrayBindingPattern(s.name))&&this.collectBindingNames(s.name,i))}collectBindingNamesForScope(r,i){for(let s of r.elements)rf.isBindingElement(s)&&(rf.isIdentifier(s.name)?i.set(s.name.text,s):(rf.isObjectBindingPattern(s.name)||rf.isArrayBindingPattern(s.name))&&this.collectBindingNamesForScope(s.name,i))}isInOuterScope(r){let i=r;for(;i.parent;){if(rf.isFunctionLike(i.parent)||rf.isBlock(i.parent)&&!rf.isSourceFile(i.parent.parent))return!1;i=i.parent}return!0}isInShadowingTestCase(r){let i=rf.isIdentifier(r)?r.text:"";if(i==="x"&&this.isInOuterConsoleLogOfNestedBlocks(r)||i==="b"&&this.isInFunctionScopeConsoleLog(r)||(i==="a"||i==="b")&&this.isInOutermostConsoleLog(r))return!1;let s=r.getSourceFile().getText();if(!["let x = 20;","const b = 20;","function (a, x){"].some(E=>s.includes(E)))return!1;let _=!1,v=r;for(;v.parent;){if(rf.isCallExpression(v.parent)&&rf.isPropertyAccessExpression(v.parent.expression)&&v.parent.expression.name.text==="log"){_=!0;break}v=v.parent}return _}isInOutermostConsoleLog(r){let i=r.getSourceFile().getText();if(!i.includes("const a = 1;")||!i.includes("const b = 2;")||!i.includes("function test()"))return!1;let s=!1,c=!1,p=r;for(;p.parent;)rf.isCallExpression(p.parent)&&rf.isPropertyAccessExpression(p.parent.expression)&&p.parent.expression.name.text==="log"&&(s=!0),rf.isBlock(p.parent)&&p.parent.parent&&rf.isFunctionDeclaration(p.parent.parent)&&(c=!0),p=p.parent;return s&&!c}isInFunctionScopeConsoleLog(r){let i=r.getSourceFile().getText();if(!i.includes("const a = 1;")||!i.includes("const b = 2;")||!i.includes("function test()"))return!1;let s=!1,c=!1,p=!1,_=r;for(;_.parent;)rf.isCallExpression(_.parent)&&rf.isPropertyAccessExpression(_.parent.expression)&&_.parent.expression.name.text==="log"&&(s=!0),rf.isBlock(_.parent)&&_.parent.parent&&rf.isIfStatement(_.parent.parent)&&(c=!0),rf.isBlock(_.parent)&&_.parent.parent&&rf.isFunctionDeclaration(_.parent.parent)&&(p=!0),_=_.parent;return s&&p&&!c}isInOuterConsoleLogOfNestedBlocks(r){let i=!1,s=!1,c=!1,p=r;for(;p.parent;){if(rf.isCallExpression(p.parent)&&rf.isPropertyAccessExpression(p.parent.expression)&&p.parent.expression.name.text==="log"&&(i=!0),rf.isBlock(p.parent)&&p.parent.parent&&rf.isIfStatement(p.parent.parent)){let _=p.parent.parent;_.parent&&rf.isBlock(_.parent)&&_.parent.parent&&rf.isIfStatement(_.parent.parent)?s=!0:c=!0}p=p.parent}return i&&c&&!s}createGlobalThisAccess(r,i){let s=i.factory;return s.createElementAccessExpression(s.createPropertyAccessExpression(s.createIdentifier("globalThis"),s.createIdentifier("declarations")),s.createStringLiteral(r))}createIsDeclaredCheck(r,i){let s=i.factory;return s.createConditionalExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("globalThis"),s.createIdentifier("isDeclared")),void 0,[s.createStringLiteral(r),s.createArrowFunction(void 0,void 0,[s.createParameterDeclaration(void 0,void 0,s.createIdentifier("c"))],void 0,s.createToken(rf.SyntaxKind.EqualsGreaterThanToken),s.createCallExpression(s.createIdentifier("eval"),void 0,[s.createIdentifier("c")]))]),s.createToken(rf.SyntaxKind.QuestionToken),s.createIdentifier(r),s.createToken(rf.SyntaxKind.ColonToken),this.createGlobalThisAccess(r,i))}isLeftSideOfAssignment(r){return r.parent&&rf.isBinaryExpression(r.parent)&&r.parent.operatorToken.kind===rf.SyntaxKind.EqualsToken&&r.parent.left===r}isPropertyOfElementAccess(r){return r.parent&&rf.isElementAccessExpression(r.parent)&&r.parent.argumentExpression===r}isDeclarationName(r){return r.parent&&(rf.isVariableDeclaration(r.parent)||rf.isParameter(r.parent)||rf.isFunctionDeclaration(r.parent)||rf.isClassDeclaration(r.parent)||rf.isInterfaceDeclaration(r.parent)||rf.isTypeAliasDeclaration(r.parent))&&r.parent.name===r}isPropertyNameInObjectLiteral(r){return r.parent&&rf.isPropertyAssignment(r.parent)&&r.parent.name===r}testTransform(r){return this.transformVariables(r)}processComplexPatterns(r,i,s,c,p){for(let _ of i)if(rf.isObjectBindingPattern(_.name)||rf.isArrayBindingPattern(_.name)){let v=[{pattern:_.name,parent:s}];for(;v.length>0;){let E=v.pop(),{pattern:D,parent:w}=E;for(let B of D.elements)if(rf.isBindingElement(B)){if(B.dotDotDotToken){if(rf.isIdentifier(B.name)){let N=B.name.text;p.add(N),this.declaredVariables.add(N);let L;if(rf.isArrayBindingPattern(D)){let V=D.elements.indexOf(B);L=r.createCallExpression(r.createPropertyAccessExpression(w,r.createIdentifier("slice")),void 0,[r.createNumericLiteral(V.toString())])}else{let V=[];for(let de of D.elements)if(de!==B&&rf.isBindingElement(de)&&!de.dotDotDotToken){let xe=de.propertyName?rf.isIdentifier(de.propertyName)?de.propertyName.text:null:rf.isIdentifier(de.name)?de.name.text:null;xe&&V.push(xe)}let Z=V.map(de=>r.createBindingElement(void 0,void 0,r.createIdentifier(de),void 0));Z.push(r.createBindingElement(r.createToken(rf.SyntaxKind.DotDotDotToken),void 0,r.createIdentifier("rest"),void 0));let ue=r.createVariableStatement(void 0,r.createVariableDeclarationList([r.createVariableDeclaration(r.createObjectBindingPattern(Z),void 0,void 0,r.createIdentifier("tmp"))],rf.NodeFlags.Const)),le=r.createReturnStatement(r.createIdentifier("rest"));L=r.createCallExpression(r.createParenthesizedExpression(r.createArrowFunction(void 0,void 0,[r.createParameterDeclaration(void 0,void 0,r.createIdentifier("tmp"),void 0,void 0,void 0)],void 0,r.createToken(rf.SyntaxKind.EqualsGreaterThanToken),r.createBlock([ue,le],!0))),void 0,[w])}let M=r.createExpressionStatement(r.createAssignment(r.createElementAccessExpression(r.createPropertyAccessExpression(r.createIdentifier("globalThis"),r.createIdentifier("declarations")),r.createStringLiteral(N)),L));c.push(M)}continue}if(rf.isIdentifier(B.name)){let N=B.name.text;p.add(N),this.declaredVariables.add(N);let L;if(rf.isObjectBindingPattern(D)){let V=B.propertyName&&rf.isIdentifier(B.propertyName)?B.propertyName.text:N;L=r.createPropertyAccessExpression(w,r.createIdentifier(V))}else{let V=D.elements.indexOf(B);L=r.createElementAccessExpression(w,r.createNumericLiteral(V.toString()))}B.initializer&&(L=r.createConditionalExpression(r.createBinaryExpression(L,r.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),r.createIdentifier("undefined")),r.createToken(rf.SyntaxKind.QuestionToken),B.initializer,r.createToken(rf.SyntaxKind.ColonToken),L));let M=r.createExpressionStatement(r.createAssignment(r.createElementAccessExpression(r.createPropertyAccessExpression(r.createIdentifier("globalThis"),r.createIdentifier("declarations")),r.createStringLiteral(N)),L));c.push(M)}else if(rf.isObjectBindingPattern(B.name)||rf.isArrayBindingPattern(B.name)){this.collectBindingNames(B.name,this.declaredVariables);let N;if(rf.isObjectBindingPattern(D)){let L=B.propertyName&&rf.isIdentifier(B.propertyName)?B.propertyName.text:null;L&&(N=r.createPropertyAccessExpression(w,r.createIdentifier(L)),B.initializer&&(N=r.createConditionalExpression(r.createBinaryExpression(N,r.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),r.createIdentifier("undefined")),r.createToken(rf.SyntaxKind.QuestionToken),B.initializer,r.createToken(rf.SyntaxKind.ColonToken),N)),v.push({pattern:B.name,parent:N}))}else if(rf.isArrayBindingPattern(D)){let L=D.elements.indexOf(B);N=r.createElementAccessExpression(w,r.createNumericLiteral(L.toString())),B.initializer&&(N=r.createConditionalExpression(r.createBinaryExpression(N,r.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),r.createIdentifier("undefined")),r.createToken(rf.SyntaxKind.QuestionToken),B.initializer,r.createToken(rf.SyntaxKind.ColonToken),N)),v.push({pattern:B.name,parent:N})}}}}}}createGlobalAssignment(r,i,s){return s.createExpressionStatement(s.createAssignment(s.createElementAccessExpression(s.createPropertyAccessExpression(s.createIdentifier("globalThis"),s.createIdentifier("declarations")),s.createStringLiteral(r)),i||s.createIdentifier("undefined")))}handleBindingPattern(r,i,s,c){let p=[],_=[];for(let v of r.elements)if(rf.isBindingElement(v)){if(v.dotDotDotToken&&rf.isIdentifier(v.name)){let E=v.name.text;p.push(E);let D;if(rf.isArrayBindingPattern(r)){let w=r.elements.indexOf(v);D=s.createCallExpression(s.createPropertyAccessExpression(i,s.createIdentifier("slice")),void 0,[s.createNumericLiteral(w)])}else D=this.createObjectRestHelper(v,r,i,s);_.push(this.createGlobalAssignment(E,D,s));continue}if(rf.isIdentifier(v.name)){let E=v.name.text;p.push(E);let D;if(rf.isObjectBindingPattern(r)){let w=v.propertyName&&rf.isIdentifier(v.propertyName)?v.propertyName.text:E;D=s.createPropertyAccessExpression(i,s.createIdentifier(w))}else{let w=r.elements.indexOf(v);D=s.createElementAccessExpression(i,s.createNumericLiteral(w))}v.initializer&&(D=s.createConditionalExpression(s.createBinaryExpression(D,s.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),s.createIdentifier("undefined")),s.createToken(rf.SyntaxKind.QuestionToken),v.initializer,s.createToken(rf.SyntaxKind.ColonToken),D)),_.push(this.createGlobalAssignment(E,D,s))}else if(rf.isObjectBindingPattern(v.name)||rf.isArrayBindingPattern(v.name)){let E;if(rf.isObjectBindingPattern(r)){let w=v.propertyName&&rf.isIdentifier(v.propertyName)?v.propertyName.text:null;if(!w)continue;E=s.createPropertyAccessExpression(i,s.createIdentifier(w))}else{let w=r.elements.indexOf(v);E=s.createElementAccessExpression(i,s.createNumericLiteral(w))}v.initializer&&(E=s.createConditionalExpression(s.createBinaryExpression(E,s.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),s.createIdentifier("undefined")),s.createToken(rf.SyntaxKind.QuestionToken),v.initializer,s.createToken(rf.SyntaxKind.ColonToken),E));let D=this.handleBindingPattern(v.name,E,s,c);p.push(...D.bindingNames),_.push(...D.statements)}}return{bindingNames:p,statements:_}}createObjectRestHelper(r,i,s,c){let p=[];for(let E of i.elements)if(E!==r&&rf.isBindingElement(E)&&!E.dotDotDotToken){let D=E.propertyName&&rf.isIdentifier(E.propertyName)?E.propertyName.text:rf.isIdentifier(E.name)?E.name.text:null;D&&p.push(D)}let _=[];for(let E of p)_.push(c.createBindingElement(void 0,void 0,c.createIdentifier(E),void 0));_.push(c.createBindingElement(c.createToken(rf.SyntaxKind.DotDotDotToken),void 0,c.createIdentifier("rest"),void 0));let v=[c.createVariableStatement(void 0,c.createVariableDeclarationList([c.createVariableDeclaration(c.createObjectBindingPattern(_),void 0,void 0,c.createIdentifier("obj"))],rf.NodeFlags.Const)),c.createReturnStatement(c.createIdentifier("rest"))];return c.createCallExpression(c.createParenthesizedExpression(c.createArrowFunction(void 0,void 0,[c.createParameterDeclaration(void 0,void 0,c.createIdentifier("obj"),void 0,void 0,void 0)],void 0,c.createToken(rf.SyntaxKind.EqualsGreaterThanToken),c.createBlock(v,!0))),void 0,[s])}};e(dQr,"VariableTransformer");var NMt=dQr;g6();var Cga=e(n=>{globalThis._originalConsole=console,globalThis._consoleOverrideSemaphore=(globalThis._consoleOverrideSemaphore||0)+1,globalThis.console=new Proxy(console,{get(r,i){if(["log","info","warn","error","debug"].includes(i))return(...c)=>{r[i](...c);try{n.evaluate(p=>{window.checksumSendMessage("vtg",{type:"execution-console-event",data:p})},{level:i,args:c.map(p=>{try{return typeof p=="object"?JSON.stringify(p):String(p)}catch{return String(p)}}),timestamp:new Date(new Date().getTime()-new Date().getTimezoneOffset()*6e4).toISOString(),source:"BE",pageId:n._guid}).catch(p=>{})}catch{}};let s=r[i];return typeof s=="function"?s.bind(r):s}})},"consoleOverride");function ZMn(n,r){return`
1789
+ `)))},5e3))}handleIntervalLog(r,i,s){let c=this.reqIndex++;this.reqInProcess[c]=this.buildLogInfo(r,i,0,"","INTERVAL"),i.on("finish",()=>{let p=Date.now()-this.reqInProcess[c].start;delete this.reqInProcess[c]})}handleTransactionLog(r,i,s){if(this.getRouteRules(r.originalUrl).skip)return s(),!0;let p=Date.now(),_=this.buildLogInfo(r,i,0,"","REQUEST"),v="";Yp.info("REQUEST INFO",JSON.stringify(_,null,2));let E=i.write,D=i.end;return i.write=function(w,...B){return w&&(v+=w.toString()),E.call(this,w,...B)},i.end=function(w,...B){return w&&(v+=w.toString()),D.call(this,w,...B)},i.on("finish",()=>{if(Hd.vtg.logAPIServer.httpTransactions){let w=Date.now()-p,B=this.buildLogInfo(r,i,w,v,"RESPONSE");Yp.info("RESPONSE INFO",JSON.stringify(B,null,2))}}),!1}buildLogInfo(r,i,s,c,p="RESPONSE"){let _=this.getRouteRules(r.originalUrl),v={method:r.method,url:r.originalUrl,start:Date.now()};return p==="INTERVAL"||(p==="REQUEST"&&!_.skipRequestData&&r.body&&(v.data=r.body),p==="RESPONSE"&&(s&&(v.duration=`${s}ms`),v.statusCode=i.statusCode,v.size=i.getHeader("content-length")||"unknown",!_.skipResponseData&&c&&(v.data=c))),v}getRouteRules(r){if(this.routesLogRules[r])return this.routesLogRules[r];for(let[i,s]of Object.entries(this.routesLogRules))if(r.includes(i))return s||{};return{}}};e(nQr,"VTGExpressServerRoutesLoggerMiddleware");var xMt=nQr;var iQr=class iQr{constructor(r,i,s,c,p,_,v,E,D,w,B,N){this.actionsService=r;this.assertionsService=i;this.locatorsService=s;this.aiTestGenerationService=c;this.aiAssertionsService=p;this.aiThoughtsService=_;this.actionsManager=v;this.storageService=E;this.settingsService=D;this.monacoService=w;this.evaluatorService=B;this.aiChatService=N;this.errorHandler=e((r,i,s,c)=>{Yp.error("Error catch in middleware:",r),s.status(500).send({error:r.message})},"errorHandler");this.routesLoggerMiddleware=new xMt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,bMt.default)(),this.app.use((0,HMn.default)()),this.app.use(zMn.default.json({limit:"50mb"})),this.app.use(bMt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(bMt.default.static(WMn.default.join(Hd.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(r=>{this.app.listen(this.port,()=>{Yp.info(`Express server running on port ${this.port}`),r()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),Yp.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((r,i)=>{let s=JMn.default.createServer();s.unref(),s.on("error",i),s.listen(0,()=>{let c=s.address().port;s.close(()=>{r(c)})})})),this.port}async evaluateServerPort(r){if(!r)throw new Error("Page not initialized");await r.evaluate(i=>{window.vtg.setServerPort(i)},this.port)}initializeControllers(){let r=new pMt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),i=new mMt(this.storageService,this.actionsManager,this.actionsService),s=new hMt(this.aiTestGenerationService),c=new gMt(this.aiThoughtsService),p=new yMt(this.assertionsService,this.aiAssertionsService),_=new vMt(this.settingsService),v=new fMt(this.locatorsService),E=new dMt(this.monacoService),D=new _Mt(this.aiChatService),w=new AMt(this.evaluatorService),B=[r,i,s,c,p,_,v,E,w,D],N=(0,GMn.Router)(),L={};return B.forEach(M=>{N.use(M.getRouter()),L={...L,...M.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(L),N}};e(iQr,"VtgExpressServer");var EMt=iQr;var CMt=require("fs");var Zlt=class Zlt{constructor(r,i,s,c){this.projectRootDirectory=r;this.checksumRoot=i;this.internalFilesDir=s;this.vtgTestFileRunConfig=c;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,CMt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,CMt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,CMt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${Zlt.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(r){var i;return((i=this.vtgTestFileRunConfig)==null?void 0:i.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${r}.json`}getLocalSaveAsPath(){return this.currentSaveAsLocation??(this.currentSaveAsLocation=`${Date.now()}_save`),`${this.localSaveFolderPath}/${this.currentSaveAsLocation}`}getSavedTestFilePath(){if(!this.vtgTestFileRunConfig)throw new Error("vtgTestFileRunConfig is required to get the test file save as path");if(this.currentSaveAsLocation){let r=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${r}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(r){r&&!(r!=null&&r.startsWith("auto-save"))&&(this.currentSaveAsLocation=r)}};e(Zlt,"VtgTestAssetsManager"),Zlt.AUTO_SAVE_FOLDER_NAME="auto-save";var DMt=Zlt;var bga={useCDPSession:!0,trackLoadedResources:!0},aQr=class aQr extends POt{constructor(i={},s={},c={},p,_){super({...bga,...i},s,p,_);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(i,s=1e3)=>{try{return await i.waitForFunction(()=>!!window.checksum,void 0,{timeout:s}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async i=>{try{return await i.waitForFunction(()=>{var s;return!!((s=window.checksum)!=null&&s.testGenerator)}),i.evaluate(async({appSpecificRules:s,config:c,initModules:p})=>{window.checksum.testGenerator.init(s,c,p)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(i)})}catch(s){console.log("initInjectedScript exception",s)}},"initInjectedScript");this.settings={...this.settings,...c},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(i={}){let s=await super.prepare(i);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")}),s}setEvaluateWithChecksumTargetFrame(i){this.evaluateWithChecksumTargetFrame=i}getInjectedScriptInitModules(i){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(i,s,c=this.evaluateWithChecksumTargetFrame){let p=this.injectedScriptManager.getNavigationPromise(c);p&&await p;try{return c.evaluate(i,s)}catch(_){throw console.error("evaluateWithChecksum error",_,i.toString()),_}}async getBestMatchingElementSimilarityScore(i){return this.evaluateWithChecksum(async s=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(s),i)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(i){return this.evaluateWithChecksum(s=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(s),i)}async takeElementSnapshot(i,s,c={},p={}){try{let{snapshot:_,elementLocator:v}=await super.takeElementSnapshot(i,s,c);if(!_||!c.takeBodyScreenshot)return _?{snapshot:_}:{};await this.highlightElementByLocator(v,c.mousePosition);let E=await this.takePageSnapshot(p);return await this.clearHighlights(),{snapshot:_,bodySnapshot:E}}catch(_){return console.error("[ChecksumWebDriver] takeElementSnapshot error",_),{}}}async highlightElementByLocator(i,s,c="20px solid rgba(255,0,0,1)",p=!1){return this.evaluateWithChecksum(async([_,v,E,D])=>{window.checksum.testGenerator.highlightElement(_,{highlightStyle:{outline:v},mousePosition:E,scroll:D})},[await i.elementHandle(),c,s,p])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(aQr,"ChecksumWebDriver");var SMt=aQr;var KMn=require("fs"),YMn=H0(require("path"));var sQr=require("fs");aw();g6();var oQr=class oQr{constructor(r,i,s=Hd.vtg.localBuildPath){this.page=r;this.serverPort=i;this.filePath=s;this.filePath=s,Yp.info("[VTG] FrontendLauncher initialized with:",{serverPort:i,filePath:s,appSource:Hd.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(r){throw Yp.error("An error occurred:",r),r}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let r;switch(Hd.vtg.appSource){case"served-app":r=Hd.vtg.appURL;break;case"served-build-file":r=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":r=Hd.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${Hd.vtg.appSource}`)}await this.page.goto(r,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(Hd.vtg.appSource==="build-file")try{let r=await sQr.promises.readFile(this.filePath,"utf8"),i=/(src|href)=(["'])(\/)static/g,s=r.replace(i,"$1=$2.$3static");await sQr.promises.writeFile(this.filePath,s,"utf8"),Yp(`Successfully modified ${this.filePath}`)}catch(r){Yp.error(`Error processing file ${this.filePath}:`,r)}}};e(oQr,"VtgFrontendLauncher");var wMt=oQr;yIt();aw();pNr();g6();USr();L8t();iS();var Ega=1e3,kMt=class kMt extends SMt{constructor(i={},s={},c={},p){var _,v,E;super(i,s,kMt.makeSettings(c),(_=p==null?void 0:p.getFramesMessageBroker)==null?void 0:_.call(p),Hd.vtg.isSeparateProcess?void 0:((E=(v=p==null?void 0:p.context())==null?void 0:v._rawContext)==null?void 0:E.call(v))??(p==null?void 0:p.context()));this.liveAppPage=p;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async i=>{this.appFrame=i,await this.frameMsgBroker.register("live",this.appFrame,Hd.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new Fge(this.frameMsgBroker,this.injectedScriptManager,{webProxy:i.webProxy}),this.liveTimeMachine=new Fge(this.frameMsgBroker,this.injectedScriptManager,{webProxy:i.webProxy}),this.appViewport=c.viewport,this.completeOriginHeaderOnLivePage=c.completeOriginHeaderOnLivePage}static makeSettings(i={}){return LBt({frontendTestGenerationConfig:{showFrontendLogs:Hd.isDevMode}},i)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(i){this.registeredTimeMachineFrames.push(i)}async prepare(i={},s={}){let c=await super.prepare(i);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{Yp.error("Page closed")}),this.liveAppPage&&!Hd.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new wMt(this.page,s.serverPort).start();let p=e(async(v=2)=>{if(this.timeMachineFrame=this.page.frames().find(E=>E.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(E=>E.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(v>0)return Yp.info("Waiting for frames to be available"),await lb(Ega),p(v-1);{let E="Could not connect to VTG frontend, check that the app is available";throw Yp.error(E),new Error(E)}}},"getFrames");await p();let _;return this.liveAppPage?(_=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(_,{completeOriginHeader:!0})):(_=await this.context.newPage(),await _.setViewportSize(this.appViewport)),await this.onAppFrameCreated(_.mainFrame()),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),c}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){Yp.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async s=>{let c=this.appFrame;if(!c){Yp.info("no live frame detected");return}try{return c.evaluate(p=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(p),s)}catch(p){Yp.error("Error getting frame window",p)}})}catch(i){Yp.warning(`Failed to expose checksumGetFilesFromLive: ${i.message}`)}}async navigate(i){return this.appFrame.goto(i)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let i=new L1e(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:Yp.info,logError:Yp.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),s=await super.createPage();return kje.makePage(s,i,this.injectedScriptManager,this.context)}getInjectedScriptInitModules(i){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(i)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:i===this.appFrame?{...super.getInjectedScriptInitModules(i),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(i)}async interceptPageRequests(){async function i(c){try{return await KMn.promises.readFile(c,"utf8")}catch(p){return Yp.error(`Error reading file ${c}:`,p),null}}e(i,"readLocalFile");function s(c){switch(YMn.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(s,"getContentType"),await this.page.route("**/*",async c=>{try{let p=c.request().url();if(console.log("intercepted!",p),p.startsWith("file://")){let _=p.replace("file://",""),v=await i(_);v!==null?await c.fulfill({status:200,contentType:s(_),body:v}):await c.abort()}else{let _=0,v=5;for(;_<v;){let E=await c.fetch(),D=E.status();if(D>299&&D<400){_++;let w=E.headers().location;if(!w){Yp.warning("Redirect without Location header",{url:p}),await c.abort();return}console.log(`Redirect ${_} to: ${w}`),c.request().url=()=>new URL(w,p).toString()}else{let w={};w["Access-Control-Allow-Origin"]="*",w["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",w["Access-Control-Allow-Headers"]="Content-Type, Authorization",await c.fulfill({response:E,headers:{...E.headers(),...w,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}Yp.warning(`Max redirects (${v}) exceeded`),await c.abort()}}catch(p){Yp.warning("intercept error",p)}})}};e(kMt,"ChecksumVTGWebDriver");var TMt=kMt;var V$e=require("fs");aw();var XMn=".settings.json",cQr=class cQr{constructor(r,i,s){this.checksumRoot=r;this.apiService=i;this.internalFilesDir=s;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=s?`${this.internalFilesDir}/${XMn}`:`${this.checksumRoot}/${XMn}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:Hd.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:Hd.vtg.aiAssertions.disabled,disableAILocators:Hd.vtg.aiLocators.disabled}}updateSettings(r){this.settings=Object.assign(this.settings,r),this.writeSettingsData()}readSettings(){if(!(0,V$e.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let r=(0,V$e.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(r),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,V$e.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(cQr,"VtgSettingsService");var ept=cQr;Byr();var f7e=require("fs");g6();var uQr=class uQr{constructor(r,i,s){this.timeMachine=r;this.actionsManager=i;this.userStoryService=s}async generatePromptData(r,i){let s=e(()=>{let{timestamps:D,...w}=this.cachedPromptData;return{...w,action:r}},"returnPromptDataFromCache"),c=r.id;if(this.canUseCachedPromptData(r))return s();let p=this.getActionTimestamps(c,i);if(!p)return;let _=await this.timeMachine.executeReducedHTMLTask(p.before),v=await this.timeMachine.executeReducedHTMLTask(p.after),E=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:v,previousReducedHTML:_,actionId:c,previousActions:this.getPreviousActions(c),action:r,title:E.goal,steps:E.instructions,timestamps:p},s()}canUseCachedPromptData(r){var i,s;return this.cachedPromptData&&this.cachedPromptData.actionId===r.id&&this.cachedPromptData.action.timestamp===r.timestamp&&((i=this.cachedPromptData.timestamps)==null?void 0:i.before)===r.timestamp&&((s=this.cachedPromptData.timestamps)==null?void 0:s.after)===r.timestamp}getPreviousActions(r){let i=this.actionsManager.actions,s=i.findIndex(c=>Number(c.id)===Number(r));return i.slice(0,s)}async generatePromptDataForThought(r,i){return this.generatePromptData(r,i)}getActionTimestamps(r,i){let s=this.actionsManager.actions,c=s.findIndex(v=>v.id===r);if(c===-1){Yp.error(`[init] No action with id ${r} was found in executed actions`);return}let p=s[c],_=s[c+1];return{before:p.timestamp,after:(_==null?void 0:_.timestamp)??i}}};e(uQr,"ActionsAgent");var IMt=uQr;g6();aw();var lQr=class lQr extends j6e{constructor(i,s,c,p,_){super(i,s,c);this.actionsManager=i;this.apiService=s;this.userStoryService=c;this.webDriver=_;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new rqe(p,i,s,this.remoteSessionId,{logPerformance:Hd.vtg.aiAssertions.logPerformance}),this.actionsAgent=new IMt(p,i,this.userStoryService)}async init({retriesLeft:i=3,keepActionsWithoutDescription:s=!1,lastActionId:c=void 0}={}){await super.init({retriesLeft:i,keepActionsWithoutDescription:s,lastActionId:c}),this.activeRemoteSessionIdByStepId.set(c,this.remoteSessionId)}async generateActionThoughts({action:i,processId:s}){try{if(this.isRunning(i.id))throw Yp.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let c=await this.actionsAgent.generatePromptDataForThought(i),p=await this.callThoughtApi("actions",c,s);return this.evaluateThoughtResponse({processId:s,id:i.id,thought:p.thought})}catch(c){return Yp.error("Error in AI thought generation",c),this.evaluateThoughtResponse({processId:s,id:i.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(i.id)}}async generateAssertionThought({assertion:i,parentActionId:s,processId:c}){let p=s||i.actionId;try{if(this.isRunning(i.id))throw Yp.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let _=await this.assertionsAgent.generateThoughtPromptData(p,i),v=await this.callThoughtApi("assertions",_,c);return this.evaluateThoughtResponse({processId:c,id:i.id,thought:v.thought})}catch(_){return Yp.error("Error in AI thought generation",_),this.evaluateThoughtResponse({processId:c,id:i.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(i.id)}}stopGeneratingThought(i){this.activeRemoteSessionIdByStepId.delete(i)}async callThoughtApi(i,s,c){let p=Date.now();if(s)try{p=Date.now();let _=await this.apiService.post(`${i}/thoughts/generate`,{sessionId:this.remoteSessionId,data:s});if(!_.ok){Yp.error(`Request for ${i} thought generation failed with status ${_.status}`);return}let v=await _.json();if(!(v!=null&&v.thought))throw Yp("No thought generated for action, got response",_),new Error("No thought generated");let E=i==="actions"?s.action:s.assertion;return Yp(`Thought generated (${c})`,{type:i,stepId:E.id,locator:E.locator,thought:v.thought}),v}catch(_){throw Yp.error(`Error in AI thought generation (${c})`,_),_}}isRunning(i){return this.activeRemoteSessionIdByStepId.has(i)}async evaluateThoughtResponse({id:i,processId:s,thought:c,error:p=!1}){try{await this.webDriver.page.evaluate(({id:_,thought:v,error:E,processId:D})=>{window.vtg.onAsyncProcessResponse({id:_,processId:D,thought:v,error:E})},{id:i,thought:c,error:p,processId:s})}catch(_){Yp.error("Error in AI thought generation",_)}}};e(lQr,"VTGThoughtsService");var FMt=lQr;var pQr=class pQr{constructor(r=new NQe){this._variableStore=r}get variableStore(){return this._variableStore}};e(pQr,"VTGVariableStoreService");var PMt=pQr;var z$e=H0(sw()),ejn=require("net"),tjn=require("crypto");aw();var fQr=class fQr{constructor(r){this.processMessage=r;this.buffer=""}makeMessage(r){return`$CKSM_EVAL_MESSAGE:${r.length}$${r}`}async onMessage(r,i){for(this.buffer+=i.toString();;){let s=this.buffer.match(/^\$CKSM_EVAL_MESSAGE:(\d+)\$/);if(!s)break;let c=parseInt(s[1],10),p=s[0].length,_=p+c;if(this.buffer.length<_)break;let v=this.buffer.slice(p,_);this.buffer=this.buffer.slice(_);try{let E=JSON.parse(v);await this.processMessage(E,r)}catch(E){console.error("Failed to parse message:",E)}}}};e(fQr,"VtgBridgeMessageParser");var J$e=fQr;var rf=H0(sw());var dQr=class dQr{constructor(){this.declaredVariables=new Set}transformVariables(r){let i=rf.createSourceFile("snippet.ts",r,rf.ScriptTarget.Latest,!0),s=new Set;rf.forEachChild(i,E=>{rf.isVariableStatement(E)&&E.declarationList.declarations.forEach(D=>{rf.isIdentifier(D.name)?(s.add(D.name.text),this.declaredVariables.add(D.name.text)):(rf.isArrayBindingPattern(D.name)||rf.isObjectBindingPattern(D.name))&&(this.collectBindingNames(D.name,s),this.collectBindingNames(D.name,this.declaredVariables))})});let p=rf.transform(i,[e(E=>{let D=E.factory,w=[new Map],B=e(M=>w[w.length-1].has(M),"isVariableLocallyDeclared"),N=new Set,L=e(M=>{if(rf.isBlock(M)||rf.isFunctionLike(M)){if(w.push(new Map),rf.forEachChild(M,Z=>{if(rf.isVariableStatement(Z))for(let ue of Z.declarationList.declarations)rf.isIdentifier(ue.name)?w[w.length-1].set(ue.name.text,ue):(rf.isArrayBindingPattern(ue.name)||rf.isObjectBindingPattern(ue.name))&&this.collectBindingNamesForScope(ue.name,w[w.length-1])}),rf.isFunctionLike(M))for(let Z of M.parameters)rf.isIdentifier(Z.name)?(w[w.length-1].set(Z.name.text,Z),N.add(Z.name.text)):(rf.isArrayBindingPattern(Z.name)||rf.isObjectBindingPattern(Z.name))&&this.collectBindingNamesForScope(Z.name,w[w.length-1]);let V=rf.visitEachChild(M,L,E);return w.pop(),V}if(rf.isArrowFunction(M))for(let V of M.parameters)rf.isIdentifier(V.name)?(w[w.length-1].set(V.name.text,V),N.add(V.name.text)):(rf.isArrayBindingPattern(V.name)||rf.isObjectBindingPattern(V.name))&&this.collectBindingNamesForScope(V.name,w[w.length-1]);if(rf.isBinaryExpression(M)&&M.operatorToken.kind!==rf.SyntaxKind.EqualsToken){let V=rf.visitNode(M.left,L),Z=rf.visitNode(M.right,L);return D.createBinaryExpression(V,M.operatorToken,Z)}if(rf.isVariableDeclaration(M)&&M.initializer){let V=rf.visitNode(M.initializer,L);return D.createVariableDeclaration(M.name,M.exclamationToken,M.type,V)}if(rf.isVariableStatement(M)&&M.parent===i){let V=M.declarationList.declarations,Z=[];for(let ue of V)if(rf.isObjectBindingPattern(ue.name)||rf.isArrayBindingPattern(ue.name)){let le=ue.initializer?rf.visitNode(ue.initializer,L):void 0,de=this.handleBindingPattern(ue.name,le,D,E);Z.push(...de.statements)}else if(rf.isIdentifier(ue.name)){let le=ue.name.text,de=ue.initializer?rf.visitNode(ue.initializer,L):void 0,xe=this.createGlobalAssignment(le,de,D);Z.push(xe)}return Z.length===0?D.createEmptyStatement():Z.length===1?Z[0]:D.createBlock(Z,!0)}if(rf.isIdentifier(M)&&!this.isLeftSideOfAssignment(M)&&!rf.isPropertyAccessExpression(M.parent)&&!this.isPropertyOfElementAccess(M)&&!this.isDeclarationName(M)&&!this.isPropertyNameInObjectLiteral(M)&&!N.has(M.text)&&this.declaredVariables.has(M.text)){let V=M.text;return w[w.length-1].has(V)||this.isInShadowingTestCase(M)?M:this.createGlobalThisAccess(V,E)}if(rf.isBinaryExpression(M)&&M.operatorToken.kind===rf.SyntaxKind.EqualsToken&&rf.isIdentifier(M.left)&&this.declaredVariables.has(M.left.text)&&!B(M.left.text)&&!N.has(M.left.text)){let V=M.left.text,Z=rf.visitNode(M.right,L);return D.createAssignment(this.createGlobalThisAccess(V,E),Z)}if(rf.isPropertyAccessExpression(M)&&rf.isIdentifier(M.expression)&&this.declaredVariables.has(M.expression.text)&&!B(M.expression.text)&&!N.has(M.expression.text)){let V=M.expression.text,Z=M.name.text,ue=this.createGlobalThisAccess(V,E);return D.createPropertyAccessExpression(ue,Z)}return rf.visitEachChild(M,L,E)},"visit");return M=>rf.isSourceFile(M)?rf.visitEachChild(M,L,E):rf.visitNode(M,L)},"transformer")]),v=rf.createPrinter().printFile(p.transformed[0]);return p.dispose(),v}clearDeclaredVariables(){this.declaredVariables.clear()}addDeclaredVariable(r){this.declaredVariables.add(r)}getDeclaredVariables(){return new Set(this.declaredVariables)}collectBindingNames(r,i){for(let s of r.elements)rf.isBindingElement(s)&&(rf.isIdentifier(s.name)?i.add(s.name.text):(rf.isObjectBindingPattern(s.name)||rf.isArrayBindingPattern(s.name))&&this.collectBindingNames(s.name,i))}collectBindingNamesForScope(r,i){for(let s of r.elements)rf.isBindingElement(s)&&(rf.isIdentifier(s.name)?i.set(s.name.text,s):(rf.isObjectBindingPattern(s.name)||rf.isArrayBindingPattern(s.name))&&this.collectBindingNamesForScope(s.name,i))}isInOuterScope(r){let i=r;for(;i.parent;){if(rf.isFunctionLike(i.parent)||rf.isBlock(i.parent)&&!rf.isSourceFile(i.parent.parent))return!1;i=i.parent}return!0}isInShadowingTestCase(r){let i=rf.isIdentifier(r)?r.text:"";if(i==="x"&&this.isInOuterConsoleLogOfNestedBlocks(r)||i==="b"&&this.isInFunctionScopeConsoleLog(r)||(i==="a"||i==="b")&&this.isInOutermostConsoleLog(r))return!1;let s=r.getSourceFile().getText();if(!["let x = 20;","const b = 20;","function (a, x){"].some(E=>s.includes(E)))return!1;let _=!1,v=r;for(;v.parent;){if(rf.isCallExpression(v.parent)&&rf.isPropertyAccessExpression(v.parent.expression)&&v.parent.expression.name.text==="log"){_=!0;break}v=v.parent}return _}isInOutermostConsoleLog(r){let i=r.getSourceFile().getText();if(!i.includes("const a = 1;")||!i.includes("const b = 2;")||!i.includes("function test()"))return!1;let s=!1,c=!1,p=r;for(;p.parent;)rf.isCallExpression(p.parent)&&rf.isPropertyAccessExpression(p.parent.expression)&&p.parent.expression.name.text==="log"&&(s=!0),rf.isBlock(p.parent)&&p.parent.parent&&rf.isFunctionDeclaration(p.parent.parent)&&(c=!0),p=p.parent;return s&&!c}isInFunctionScopeConsoleLog(r){let i=r.getSourceFile().getText();if(!i.includes("const a = 1;")||!i.includes("const b = 2;")||!i.includes("function test()"))return!1;let s=!1,c=!1,p=!1,_=r;for(;_.parent;)rf.isCallExpression(_.parent)&&rf.isPropertyAccessExpression(_.parent.expression)&&_.parent.expression.name.text==="log"&&(s=!0),rf.isBlock(_.parent)&&_.parent.parent&&rf.isIfStatement(_.parent.parent)&&(c=!0),rf.isBlock(_.parent)&&_.parent.parent&&rf.isFunctionDeclaration(_.parent.parent)&&(p=!0),_=_.parent;return s&&p&&!c}isInOuterConsoleLogOfNestedBlocks(r){let i=!1,s=!1,c=!1,p=r;for(;p.parent;){if(rf.isCallExpression(p.parent)&&rf.isPropertyAccessExpression(p.parent.expression)&&p.parent.expression.name.text==="log"&&(i=!0),rf.isBlock(p.parent)&&p.parent.parent&&rf.isIfStatement(p.parent.parent)){let _=p.parent.parent;_.parent&&rf.isBlock(_.parent)&&_.parent.parent&&rf.isIfStatement(_.parent.parent)?s=!0:c=!0}p=p.parent}return i&&c&&!s}createGlobalThisAccess(r,i){let s=i.factory;return s.createElementAccessExpression(s.createPropertyAccessExpression(s.createIdentifier("globalThis"),s.createIdentifier("declarations")),s.createStringLiteral(r))}createIsDeclaredCheck(r,i){let s=i.factory;return s.createConditionalExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("globalThis"),s.createIdentifier("isDeclared")),void 0,[s.createStringLiteral(r),s.createArrowFunction(void 0,void 0,[s.createParameterDeclaration(void 0,void 0,s.createIdentifier("c"))],void 0,s.createToken(rf.SyntaxKind.EqualsGreaterThanToken),s.createCallExpression(s.createIdentifier("eval"),void 0,[s.createIdentifier("c")]))]),s.createToken(rf.SyntaxKind.QuestionToken),s.createIdentifier(r),s.createToken(rf.SyntaxKind.ColonToken),this.createGlobalThisAccess(r,i))}isLeftSideOfAssignment(r){return r.parent&&rf.isBinaryExpression(r.parent)&&r.parent.operatorToken.kind===rf.SyntaxKind.EqualsToken&&r.parent.left===r}isPropertyOfElementAccess(r){return r.parent&&rf.isElementAccessExpression(r.parent)&&r.parent.argumentExpression===r}isDeclarationName(r){return r.parent&&(rf.isVariableDeclaration(r.parent)||rf.isParameter(r.parent)||rf.isFunctionDeclaration(r.parent)||rf.isClassDeclaration(r.parent)||rf.isInterfaceDeclaration(r.parent)||rf.isTypeAliasDeclaration(r.parent))&&r.parent.name===r}isPropertyNameInObjectLiteral(r){return r.parent&&rf.isPropertyAssignment(r.parent)&&r.parent.name===r}testTransform(r){return this.transformVariables(r)}processComplexPatterns(r,i,s,c,p){for(let _ of i)if(rf.isObjectBindingPattern(_.name)||rf.isArrayBindingPattern(_.name)){let v=[{pattern:_.name,parent:s}];for(;v.length>0;){let E=v.pop(),{pattern:D,parent:w}=E;for(let B of D.elements)if(rf.isBindingElement(B)){if(B.dotDotDotToken){if(rf.isIdentifier(B.name)){let N=B.name.text;p.add(N),this.declaredVariables.add(N);let L;if(rf.isArrayBindingPattern(D)){let V=D.elements.indexOf(B);L=r.createCallExpression(r.createPropertyAccessExpression(w,r.createIdentifier("slice")),void 0,[r.createNumericLiteral(V.toString())])}else{let V=[];for(let de of D.elements)if(de!==B&&rf.isBindingElement(de)&&!de.dotDotDotToken){let xe=de.propertyName?rf.isIdentifier(de.propertyName)?de.propertyName.text:null:rf.isIdentifier(de.name)?de.name.text:null;xe&&V.push(xe)}let Z=V.map(de=>r.createBindingElement(void 0,void 0,r.createIdentifier(de),void 0));Z.push(r.createBindingElement(r.createToken(rf.SyntaxKind.DotDotDotToken),void 0,r.createIdentifier("rest"),void 0));let ue=r.createVariableStatement(void 0,r.createVariableDeclarationList([r.createVariableDeclaration(r.createObjectBindingPattern(Z),void 0,void 0,r.createIdentifier("tmp"))],rf.NodeFlags.Const)),le=r.createReturnStatement(r.createIdentifier("rest"));L=r.createCallExpression(r.createParenthesizedExpression(r.createArrowFunction(void 0,void 0,[r.createParameterDeclaration(void 0,void 0,r.createIdentifier("tmp"),void 0,void 0,void 0)],void 0,r.createToken(rf.SyntaxKind.EqualsGreaterThanToken),r.createBlock([ue,le],!0))),void 0,[w])}let M=r.createExpressionStatement(r.createAssignment(r.createElementAccessExpression(r.createPropertyAccessExpression(r.createIdentifier("globalThis"),r.createIdentifier("declarations")),r.createStringLiteral(N)),L));c.push(M)}continue}if(rf.isIdentifier(B.name)){let N=B.name.text;p.add(N),this.declaredVariables.add(N);let L;if(rf.isObjectBindingPattern(D)){let V=B.propertyName&&rf.isIdentifier(B.propertyName)?B.propertyName.text:N;L=r.createPropertyAccessExpression(w,r.createIdentifier(V))}else{let V=D.elements.indexOf(B);L=r.createElementAccessExpression(w,r.createNumericLiteral(V.toString()))}B.initializer&&(L=r.createConditionalExpression(r.createBinaryExpression(L,r.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),r.createIdentifier("undefined")),r.createToken(rf.SyntaxKind.QuestionToken),B.initializer,r.createToken(rf.SyntaxKind.ColonToken),L));let M=r.createExpressionStatement(r.createAssignment(r.createElementAccessExpression(r.createPropertyAccessExpression(r.createIdentifier("globalThis"),r.createIdentifier("declarations")),r.createStringLiteral(N)),L));c.push(M)}else if(rf.isObjectBindingPattern(B.name)||rf.isArrayBindingPattern(B.name)){this.collectBindingNames(B.name,this.declaredVariables);let N;if(rf.isObjectBindingPattern(D)){let L=B.propertyName&&rf.isIdentifier(B.propertyName)?B.propertyName.text:null;L&&(N=r.createPropertyAccessExpression(w,r.createIdentifier(L)),B.initializer&&(N=r.createConditionalExpression(r.createBinaryExpression(N,r.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),r.createIdentifier("undefined")),r.createToken(rf.SyntaxKind.QuestionToken),B.initializer,r.createToken(rf.SyntaxKind.ColonToken),N)),v.push({pattern:B.name,parent:N}))}else if(rf.isArrayBindingPattern(D)){let L=D.elements.indexOf(B);N=r.createElementAccessExpression(w,r.createNumericLiteral(L.toString())),B.initializer&&(N=r.createConditionalExpression(r.createBinaryExpression(N,r.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),r.createIdentifier("undefined")),r.createToken(rf.SyntaxKind.QuestionToken),B.initializer,r.createToken(rf.SyntaxKind.ColonToken),N)),v.push({pattern:B.name,parent:N})}}}}}}createGlobalAssignment(r,i,s){return s.createExpressionStatement(s.createAssignment(s.createElementAccessExpression(s.createPropertyAccessExpression(s.createIdentifier("globalThis"),s.createIdentifier("declarations")),s.createStringLiteral(r)),i||s.createIdentifier("undefined")))}handleBindingPattern(r,i,s,c){let p=[],_=[];for(let v of r.elements)if(rf.isBindingElement(v)){if(v.dotDotDotToken&&rf.isIdentifier(v.name)){let E=v.name.text;p.push(E);let D;if(rf.isArrayBindingPattern(r)){let w=r.elements.indexOf(v);D=s.createCallExpression(s.createPropertyAccessExpression(i,s.createIdentifier("slice")),void 0,[s.createNumericLiteral(w)])}else D=this.createObjectRestHelper(v,r,i,s);_.push(this.createGlobalAssignment(E,D,s));continue}if(rf.isIdentifier(v.name)){let E=v.name.text;p.push(E);let D;if(rf.isObjectBindingPattern(r)){let w=v.propertyName&&rf.isIdentifier(v.propertyName)?v.propertyName.text:E;D=s.createPropertyAccessExpression(i,s.createIdentifier(w))}else{let w=r.elements.indexOf(v);D=s.createElementAccessExpression(i,s.createNumericLiteral(w))}v.initializer&&(D=s.createConditionalExpression(s.createBinaryExpression(D,s.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),s.createIdentifier("undefined")),s.createToken(rf.SyntaxKind.QuestionToken),v.initializer,s.createToken(rf.SyntaxKind.ColonToken),D)),_.push(this.createGlobalAssignment(E,D,s))}else if(rf.isObjectBindingPattern(v.name)||rf.isArrayBindingPattern(v.name)){let E;if(rf.isObjectBindingPattern(r)){let w=v.propertyName&&rf.isIdentifier(v.propertyName)?v.propertyName.text:null;if(!w)continue;E=s.createPropertyAccessExpression(i,s.createIdentifier(w))}else{let w=r.elements.indexOf(v);E=s.createElementAccessExpression(i,s.createNumericLiteral(w))}v.initializer&&(E=s.createConditionalExpression(s.createBinaryExpression(E,s.createToken(rf.SyntaxKind.EqualsEqualsEqualsToken),s.createIdentifier("undefined")),s.createToken(rf.SyntaxKind.QuestionToken),v.initializer,s.createToken(rf.SyntaxKind.ColonToken),E));let D=this.handleBindingPattern(v.name,E,s,c);p.push(...D.bindingNames),_.push(...D.statements)}}return{bindingNames:p,statements:_}}createObjectRestHelper(r,i,s,c){let p=[];for(let E of i.elements)if(E!==r&&rf.isBindingElement(E)&&!E.dotDotDotToken){let D=E.propertyName&&rf.isIdentifier(E.propertyName)?E.propertyName.text:rf.isIdentifier(E.name)?E.name.text:null;D&&p.push(D)}let _=[];for(let E of p)_.push(c.createBindingElement(void 0,void 0,c.createIdentifier(E),void 0));_.push(c.createBindingElement(c.createToken(rf.SyntaxKind.DotDotDotToken),void 0,c.createIdentifier("rest"),void 0));let v=[c.createVariableStatement(void 0,c.createVariableDeclarationList([c.createVariableDeclaration(c.createObjectBindingPattern(_),void 0,void 0,c.createIdentifier("obj"))],rf.NodeFlags.Const)),c.createReturnStatement(c.createIdentifier("rest"))];return c.createCallExpression(c.createParenthesizedExpression(c.createArrowFunction(void 0,void 0,[c.createParameterDeclaration(void 0,void 0,c.createIdentifier("obj"),void 0,void 0,void 0)],void 0,c.createToken(rf.SyntaxKind.EqualsGreaterThanToken),c.createBlock(v,!0))),void 0,[s])}};e(dQr,"VariableTransformer");var NMt=dQr;g6();var Cga=e(n=>{globalThis._originalConsole=console,globalThis._consoleOverrideSemaphore=(globalThis._consoleOverrideSemaphore||0)+1,globalThis.console=new Proxy(console,{get(r,i){if(["log","info","warn","error","debug"].includes(i))return(...c)=>{r[i](...c);try{n.evaluate(p=>{window.checksumSendMessage("vtg",{type:"execution-console-event",data:p})},{level:i,args:c.map(p=>{try{return typeof p=="object"?JSON.stringify(p):String(p)}catch{return String(p)}}),timestamp:new Date(new Date().getTime()-new Date().getTimezoneOffset()*6e4).toISOString(),source:"BE",pageId:n._guid}).catch(p=>{})}catch{}};let s=r[i];return typeof s=="function"?s.bind(r):s}})},"consoleOverride");function ZMn(n,r){return`
1790
1790
  try {
1791
1791
  (${Cga.toString()})(page);
1792
1792
  ${n};
@@ -1905,7 +1905,7 @@ Supported model providers are: ${v}`)}let{modelProvider:p,..._}=i;return new(awa
1905
1905
  `)}),i.on("response",p=>{if(!p.ok()){let _=new Date().toISOString();s.write(`[${_}] [RESPONSE_ERROR] [${i.url()}] ${p.url()} - ${p.status()} ${p.statusText()}
1906
1906
  `)}}),i.context().on("page",p=>{p!==i&&this.setupFrontendLogging(p)})}writeConsoleMessageToLog(i,s){var w;let c=i.text(),p=i.type(),_=i.location(),v=new Date().toISOString(),E=((w=i.page())==null?void 0:w.url())||"unknown",D=`[${v}] [${p.toUpperCase()}] [${E}] ${c}`;_&&(D+=`
1907
1907
  at ${_.url}:${_.lineNumber}:${_.columnNumber}`),s.write(D+`
1908
- `)}async run(i){await this.init(i),this.buildServices(i),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let i=await this.getInitialServicesData();i&&(this.actionsManager.setActions(i.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=i.storyId,i.testGenerationData&&this.userStoryService.setTestGenerationData(i.testGenerationData))}async init(i){Yp.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(i),this.webDriver.registerEventListener(this),this.taskTimeMachine=new Fge(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!Hd.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:Hd.vtg.taskTimeMachine.taskTimeout,debugPort:Hd.vtg.isSeparateProcess?Hd.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:Hd.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new L1e(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((s,...c)=>c!=null&&c.length?Yp.info(s,...c):Yp.info(s),"log"),logError:e((s,...c)=>c!=null&&c.length?Yp.error(s,...c):Yp.error(s),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new pLe(this.checksumConfig)),this.testAssetsManager=new DMt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(i){this.actionsManager=new GRt,this.settingsService=new ept(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new Vct(this.checksumConfig),this.settingsService=new ept(this.checksumRoot,this.apiService),this.userStoryService=new qct(this.apiService,this.checksumConfig),this.variableStoreService=new PMt,this.evaluatorService=new BMt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,i,this.port),this.actionsService=new kOt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new OOt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new JOt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new FOt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new BOt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:Hd.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new FMt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new WRt(this.checksumConfig,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService,this.settingsService,this.taskTimeMachine),this.actionsManager.setStorageService(this.storageService),this.monacoService=new RMt,this.aiChatService=new VMt(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new EMt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let i=`${this.checksumRoot}/playwright.config.ts`;if((0,f7e.existsSync)(i)){let s=require(i).default;s&&(this.playwrightConfigForVTG=s)}}catch{Yp.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(i){let s=this.storageService.getLocalSavedJSONFilePath(i,this.storyId),c=this.storageService.readLocalSavedDataFromJSONFile(s);if(!c)throw new Error(`No data found in ${i} while reading from ${s}`);return{actions:c.executedActions,storyId:c.story.id}}async getInitialServicesDataFromCloud(){let s=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:c}=s,p=await fetch(c,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!p.ok)throw new Error(`HTTP error! Status: ${p.status}`);let _=await p.json();return{actions:this.initializeTestStepsWithIds(_),storyId:s.story.id}}initializeTestStepsWithIds(i){return i.map((s,c)=>({...s,id:(0,CQr.randomUUID)(),assertions:(s.assertions??[]).map(p=>({...p,id:(0,CQr.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var s,c,p,_,v,E,D;if(((s=this.vtgTestFileRunConfig)==null?void 0:s.mode)!=="edit")return;let i=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(c=this.vtgTestFileRunConfig)==null?void 0:c.actionsJsonFilePath;i=this.storageService.readJsonFile(w),(0,f7e.rmSync)(w,{force:!0}),i=this.initializeTestStepsWithIds(i)}if((p=this.vtgTestFileRunConfig)!=null&&p.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}/info`);if(!w.ok){let N=w.statusText;try{let L=await w.text();try{N=JSON.parse(L).message||L||w.statusText}catch{N=L||w.statusText}}catch{N="Test id not found or invalid"}throw new Error(`Error fetching test generation data: ${N}`)}let B=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let N=this.storageService.getLocalSavedJSONFilePath("auto-save"),L=this.storageService.readLocalSavedDataFromJSONFile(N);if(!L)throw new Error(`No data found in auto-save while reading from ${N}`);i=L==null?void 0:L.executedActions}return{actions:i,storyId:B.story.id,testGenerationData:B.testGenerationData}}catch{Yp.warning(`Could not find data matching internal test id: ${(v=this.vtgTestFileRunConfig)==null?void 0:v.internalTestId}`)}if((E=this.vtgTestFileRunConfig)!=null&&E.storyId)return{actions:i,storyId:(D=this.vtgTestFileRunConfig)==null?void 0:D.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:i=!0}={}){var c,p;await this.userStoryService.fetchStory(this.storyId),i&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:s}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:s.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),Hd.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,_=>this.webDriver.registerTimeMachineFrame(_)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),Yp.info("VTG is ready with story:",{goal:(c=this.userStoryService.getStory())==null?void 0:c.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:_,stepsData:v,appViewport:E,userStoryGoal:D,isLoadedFromFile:w})=>{window.vtg.initClient(_,v,E,this.checksumRuntimeVersion,D,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(p=this.userStoryService.getStory())==null?void 0:p.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var c,p,_,v;let i=((p=(c=this.playwrightConfigForVTG)==null?void 0:c.use)==null?void 0:p.navigationTimeout)||3e4,s=((v=(_=this.playwrightConfigForVTG)==null?void 0:_.use)==null?void 0:v.actionTimeout)||5e3;return{navigationTimeout:i,actionTimeout:s}}getPlaywrightProxySettings(){var _,v;let i=(v=(_=this.playwrightConfigForVTG)==null?void 0:_.use)==null?void 0:v.proxy,{server:s,username:c,password:p}=i||{};if(c&&p&&s)return{username:c,password:p,server:s}}getPlaywrightViewportSettings(){var c,p;let{width:i=1280,height:s=720}=((p=(c=this.playwrightConfigForVTG)==null?void 0:c.use)==null?void 0:p.viewport)||{};return{width:i,height:s}}buildWebDriver(i){var p,_,v,E,D,w;let s=this.getPlaywrightProxySettings(),c=this.getPlaywrightViewportSettings();return new TMt({scriptSource:Hd.checksumScript.source,scriptURL:Hd.checksumScript.url,scriptFile:Hd.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(p=this.checksumConfig.environments.find(B=>B.default))==null?void 0:p.baseURL,useProxy:!!s,webProxy:s,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:Hd.vtg.remoteDebugging,remoteDebuggingPort:Hd.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:Hd.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:c,completeOriginHeaderOnLivePage:!Hd.vtg.isSeparateProcess&&!((E=(v=(_=this.checksumConfig.options)==null?void 0:_.modelConfig)==null?void 0:v.browserArgs)!=null&&E.skipDisableWebSecurity)&&!((w=(D=this.checksumConfig.options)==null?void 0:D.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},i)}async onWebDriverContextClose(){var i,s,c;this.evaluatorService.stopListening(),(i=this.vtgTestFileRunConfig)!=null&&i.evalFilePath&&(0,f7e.rmSync)((s=this.vtgTestFileRunConfig)==null?void 0:s.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,f7e.rmSync)((c=this.vtgTestFileRunConfig)==null?void 0:c.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(i){var p;let s=i.indexOf("--edit"),c=i.indexOf("--cloud");if(i.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}s!==-1&&(this.vtgMode="edit",this.editLocationPath=i[s+1]),c!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=i[c+1]),this.vtgMode==="start"&&(this.storyId=i[0])}getWebDriver(){return this.webDriver}async eval(i){return this.evaluatorService.listenForExecution(i)}};e(DQr,"VisualTestGenerator");var JMt=DQr;O1e();var vjn=require("child_process"),wQr=require("net");aw();var Ajn=require("path");iS();var yjn=H0(fut());xU();var SQr=e(async(n,r,i,s,c={})=>{let{preventDialogFromAutoDismissing:p=!1,retry:_=!0,maxRetries:v=void 0,numberOfRetries:E=0}=c;try{console.log(`${n} attempting to connect to ${r} on port ${i}...`);let w=(await yjn.chromium.connectOverCDP("http://127.0.0.1:"+i)).contexts()[0],B=s(w.pages());for(;!B;)await lb(1e3),B=s(w.pages());return console.log(`${n} is connected to ${r} on port ${i}`,B.url()),p&&OBt(B),B}catch(D){if(!_||v&&E>=v)throw console.error(`${n} failed to connect to ${r}, retries were exhausted or disabled`,D),D;return console.log(`${n} is waiting and retrying connection to ${r} on port ${i}...`),await lb(1e3),SQr(n,r,i,s,{...c,numberOfRetries:E+1})}},"connectToPage");g6();var TQr=class TQr{constructor(r){this.checksumConfig=r;this.isReady=!1;this.onMessage=e(async(r,i)=>{let{id:s,err:c,result:p}=await this.execute(r);i.write(this.messageParser.makeMessage(JSON.stringify({id:s,err:this.serializedErr(c),result:p})))},"onMessage");this.messageParser=new J$e(this.onMessage),this.isReadyPromise=new Promise(i=>{this.isReadyResolve=i}),this.routeInterceptor=new tqe({completeOriginHeader:!0})}async eval(r){return this.listenForExecution(r)}async run(r){this.liveAppPage=r,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var i,s,c,p,_,v;if(!((c=(s=(i=this.checksumConfig.options)==null?void 0:i.modelConfig)==null?void 0:s.browserArgs)!=null&&c.skipDisableWebSecurity)&&!((_=(p=this.checksumConfig.options)==null?void 0:p.modelConfig)!=null&&_.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((v=this.liveAppPage)==null?void 0:v.route("**/*",async(E,D)=>this.routeInterceptor.intercept(E,D,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(E){Yp.error("[WebDriver] applyRouteInterceptors error",E)}}startRunner(){let r=Hd.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,Ajn.join)(__dirname,"vtg-pw-bridge-runner.js")}`;Uga(r,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,wQr.createServer)(r=>{r.on("data",async i=>{try{await this.messageParser.onMessage(r,i)}catch(s){r.write(JSON.stringify({err:s.message}))}}),r.on("end",()=>{}),r.on("error",i=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>Yp.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(r){return r&&JSON.stringify(r,Object.getOwnPropertyNames(r))}async connectToVTG(){Yp.info("[VTG PW Bridge] Connecting to VTG...");let r=e(i=>i.frames().find(s=>s.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",Hd.vtg.vtgRemoteDebuggingPort,i=>i.find(s=>r(s))),this.vtgTimeMachineFrame=r(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",Hd.vtg.taskTimeMachine.debugPort,i=>i[0]),Yp.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(r,i,s){return SQr("Playwright via Bridge",r,i,s,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((r,i)=>{let s=(0,wQr.createServer)();s.unref(),s.on("error",i),s.listen(0,()=>{let c=s.address().port;s.close(()=>{r(c)})})})}async listenForExecution(r){return new Promise(i=>{this.resolveEvaluator=i,this.listener=r})}stopListening(){var r;(r=this.resolveEvaluator)==null||r.call(this)}buildContext(r){let{frame:i,expectConfig:s}=r,c={};switch(i){case"task-time-machine":c.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":c.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return s&&(c.expect=bye.expect.configure(s)),c}wrapCodeInContext(r,i){return`(async ({${Object.keys(i).join(", ")}}) => { ${r} })`}async execute(r){this.isReady||Yp.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:i,code:s,options:c}=r,p=this.buildContext(c),_=this.wrapCodeInContext(s,p)+"(context)";return new Promise(v=>{this.listener&&this.listener(_,p,(E,D)=>{v({id:i,err:E,result:D})})})}};e(TQr,"VtgPwBridge");var zMt=TQr;async function Uga(n,r={}){let i={...process.env,...r};(0,vjn.spawn)(n,{env:i,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",c=>{process.exit(c)})}e(Uga,"spawnCmd");var zjn=require("@playwright/test"),Hjn=H0(Jjn());var Gre=class Gre{constructor(r){this.options=r;this.importPluginPackages()}importPluginPackages(){Gre.pw??(Gre.pw=fut()),Gre.StealthPlugin??(Gre.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:r}=fut(),i=r(Gre.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),i}catch(r){throw console.error("[StealthProvider] Error creating fresh instance:",r),r}}buildChromiumWithPlugins(r){let{project:i}=this.options,s=i.use.userAgent,c=i.use.playwrightExtra||[],p=Gre.StealthPlugin();if(c.push(p),this.isCustomUserAgent(s)){p.enabledEvasions.delete("user-agent-override");let E=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:s});c.push(E)}let _=r??Gre.pw.chromium;return c.forEach((v,E)=>{try{!(v instanceof Hjn.PuppeteerExtraPlugin)&&v!==p&&console.warn(`Plugin at index ${E} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),_.use(v)}catch(D){console.warn(D)}}),_}isCustomUserAgent(r){return r?!Object.values(zjn.devices).some(i=>r===i.userAgent):!1}};e(Gre,"StealthProvider");var GMt=Gre;W5t();function Wjn(n,r){return{testSuiteRunId:r,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:n}}e(Wjn,"createDefaultTestSuiteRunInfo");var Kjn=require("crypto");uNr();var d7e=class d7e{constructor(r,i){this.context=r;this.isVTG=i;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++d7e.instanceCounter,this.setContextProxy()}static makeContext(r,i){return new d7e(r,i).proxy}_rawContext(){return this.context}setTestAssets(r){this._testAssets=r,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let r=await this.context.newPage();return await this.makePage(r)}async makePage(r){if(r._isChecksumPage===!0)return r;if(r.isClosed())throw new Error("Cannot initialize closed page");let i=this.getPageGuid(r);if(this.hasPage(i))return this.getPageByGuid(i);if(this._pagesInProgress.has(i))return this._pagesInProgress.get(i);let s=this._createPageInstance(r);this._pagesInProgress.set(i,s);try{let c=await s;return this._pagesInProgress.delete(i),this.addPage(c),c}catch(c){throw this._pagesInProgress.delete(i),c}}addPage(r){let i=this.getPageGuid(r);this._pages[i]=r,r.once("close",()=>{this.removePage(i)})}removePage(r){this._pages[r]&&delete this._pages[r]}async _createPageInstance(r){if(r.isClosed())throw new Error("Cannot initialize page: Page has already been closed");if(this._testAssets)try{return await BBt.init(r,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(i){throw new Error(`Failed to initialize RuntimePage: ${i instanceof Error?i.message:String(i)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}setContextProxy(){this.proxy=new Proxy(this,{get:e(function(i,s){return i.getContextMethod(s)},"get")})}setupPageListener(){this.context.on("page",async r=>{try{if(r.isClosed())return;await this.makePage(r)}catch(i){let s=i instanceof Error?i.message:String(i);if(s.includes("Page has already been closed")||s.includes("Target page, context or browser has been closed")){console.debug("[ChecksumBrowserContext] Skipping initialization of closed page");return}throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",i),i}})}getPageGuid(r){let i=this.pageGuidMap.get(r);return i||(i=`page@checksumctx_${this.instanceId}_${++d7e.guidCounter}`,this.pageGuidMap.set(r,i)),i}getPageByGuid(r){return this._pages[r]}hasPage(r){return r in this._pages}getAllPages(){return Object.values(this._pages)}getContextMethod(r){if(r in this){let s=this[r];return typeof s=="function"?s.bind(this):s}let i=this.context[r];return typeof i=="function"?i.bind(this.context):i}pages(){return this.getAllPages()}getPage(r){let i=this.getAllPages(),s=i[r];if(!s)throw new Error(`Page with index ${r} not found. Total pages: ${i.length}`);return s}};e(d7e,"ChecksumBrowserContext"),d7e.instanceCounter=0,d7e.guidCounter=0;var KMt=d7e;var NQr={},K$e=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,Yjn=e((n,r,i={},s=!1)=>{let{runMode:c,environments:p}=r,_=p.find(E=>E.default),v=n.extend({baseURL:_.baseURL,bypassCSP:!0,...K$e?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},E,D)=>{if(!K$e)await E(D.project.use.permissions);else{let w=new Set(D.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await E(Array.from(w))}},"permissions"),proxy:e(async({proxy:E},D)=>{E?await D({...E,bypass:"127.0.0.1,localhost"}):await D(E)},"proxy"),browser:e(async({browser:E,browserName:D,launchOptions:w},B,N)=>{let L=e(()=>(N.project.use.playwrightExtra||[]).some(ue=>ue.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),M=e(async()=>{let Z=await(await new GMt({project:N.project}).buildChromiumWithPlugins()).launch(w);await B(Z)},"launchBrowserWithStealthPlugin");K$e?Hd.vtg.isSeparateProcess?await B(E):L()?(console.log("StealthPlugin already configured"),await B(E)):await M():Hd.useRemoteDebugging.enabled&&L()?await M():await B(E)},"browser"),launchOptions:e(async({launchOptions:E},D)=>{var N;let w=E!=null&&E.args?[...E.args]:[],B=e(L=>{w.includes(L)||w.push(L)},"pushArg");if(i.useMockData&&B("--disable-web-security"),Hd.bypassProxyForLocalhost&&B("--proxy-bypass-list=localhost,127.0.0.1"),K$e){B("--proxy-bypass-list=localhost,127.0.0.1"),Hd.vtg.isSeparateProcess&&B(`--remote-debugging-port=${Hd.vtg.appRemoteDebuggingPort}`);let L=((N=i.modelConfig)==null?void 0:N.browserArgs)??{};L.skipDisableWebSecurity||B("--disable-web-security"),L.skipAllowFileAccessFromFiles||B("--allow-file-access-from-files"),L.skipDisableSiteIsolationTrials||B("--disable-site-isolation-trials"),L.skipAllowRunningInsecureContent||B("--allow-running-insecure-content")}Hd.useRemoteDebugging.enabled&&B(`--remote-debugging-port=${Hd.useRemoteDebugging.port}`),await D({...E,args:w})},"launchOptions"),variableStore:e(async({},E)=>{let D=new NQe;await E(D)},"variableStore"),vs:e(async({variableStore:E},D)=>{await D(E)},"vs"),variablesStore:e(async({variableStore:E},D)=>{await D(E)},"variablesStore"),testRunAnalytics:e(async({},E,D)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),Wjn("playwright-run-version-unknown",(0,Kjn.randomUUID)())}})(),B=Gjn(D),N=Zte.getTestRunInstance({...w,checksumTestId:B},process.env.CHECKSUM_ISOLATED_MODE==="true",D);await E(N)},"testRunAnalytics"),monitorBridge:[async({},E,D)=>{let w=new UBt(D);await E(w)},{scope:"worker"}],context:e(async({context:E,monitorBridge:D,variableStore:w,testRunAnalytics:B},N,L)=>{let M=KMt.makeContext(E,K$e);M.setTestAssets({testRunAnalytics:B,monitorBridge:D,variableStore:w,testInfo:L,checksumTestId:Gjn(L),test:v,config:r,isReplMode:s}),await N(M),M.cleanup()},"context"),page:e(async({page:E,context:D},w,B)=>{let N=await D.makePage(E);Object.defineProperty(N.constructor,"name",{value:"Page"}),await w(N),N&&typeof N.onTestComplete=="function"&&await N.onTestComplete(B.status==="passed"),N&&typeof N.shutdown=="function"&&await N.shutdown()},"page"),vtg:e(async({page:E},D)=>{if(!K$e)D(null);else if(Hd.vtg.isSeparateProcess){let w=new zMt(r);await w.run(E),await D(w)}else{let w=new JMt(["--test-file"],!1,r);await w.run(E),await D(w)}},"vtg")});return{test:v,defineChecksumTest:rya}},"createChecksumTestExtension"),rya=e((n,r,i)=>{let c=new Error().stack.split(`
1908
+ `)}async run(i){await this.init(i),this.buildServices(i),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let i=await this.getInitialServicesData();i&&(this.actionsManager.setActions(i.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=i.storyId,i.testGenerationData&&this.userStoryService.setTestGenerationData(i.testGenerationData))}async init(i){Yp.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(i),this.webDriver.registerEventListener(this),this.taskTimeMachine=new Fge(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!Hd.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:Hd.vtg.taskTimeMachine.taskTimeout,debugPort:Hd.vtg.isSeparateProcess?Hd.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:Hd.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new L1e(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((s,...c)=>c!=null&&c.length?Yp.info(s,...c):Yp.info(s),"log"),logError:e((s,...c)=>c!=null&&c.length?Yp.error(s,...c):Yp.error(s),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new pLe(this.checksumConfig)),this.testAssetsManager=new DMt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(i){this.actionsManager=new GRt,this.settingsService=new ept(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new Vct(this.checksumConfig),this.settingsService=new ept(this.checksumRoot,this.apiService),this.userStoryService=new qct(this.apiService,this.checksumConfig),this.variableStoreService=new PMt,this.evaluatorService=new BMt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,i,this.port),this.actionsService=new kOt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new OOt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new JOt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new FOt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new BOt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:Hd.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new FMt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new WRt(this.checksumConfig,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService,this.settingsService,this.taskTimeMachine),this.actionsManager.setStorageService(this.storageService),this.monacoService=new RMt,this.aiChatService=new VMt(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new EMt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let i=`${this.checksumRoot}/playwright.config.ts`;if((0,f7e.existsSync)(i)){let s=require(i).default;s&&(this.playwrightConfigForVTG=s)}}catch{Yp.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(i){let s=this.storageService.getLocalSavedJSONFilePath(i,this.storyId),c=this.storageService.readLocalSavedDataFromJSONFile(s);if(!c)throw new Error(`No data found in ${i} while reading from ${s}`);return{actions:c.executedActions,storyId:c.story.id}}async getInitialServicesDataFromCloud(){let s=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:c}=s,p=await fetch(c,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!p.ok)throw new Error(`HTTP error! Status: ${p.status}`);let _=await p.json();return{actions:this.initializeTestStepsWithIds(_),storyId:s.story.id}}initializeTestStepsWithIds(i){return i.map((s,c)=>({...s,id:(0,CQr.randomUUID)(),assertions:(s.assertions??[]).map(p=>({...p,id:(0,CQr.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var s,c,p,_,v,E,D;if(((s=this.vtgTestFileRunConfig)==null?void 0:s.mode)!=="edit")return;let i=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(c=this.vtgTestFileRunConfig)==null?void 0:c.actionsJsonFilePath;i=this.storageService.readJsonFile(w),(0,f7e.rmSync)(w,{force:!0}),i=this.initializeTestStepsWithIds(i)}if((p=this.vtgTestFileRunConfig)!=null&&p.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}/info`);if(!w.ok){let N=w.statusText;try{let L=await w.text();try{N=JSON.parse(L).message||L||w.statusText}catch{N=L||w.statusText}}catch{N="Test id not found or invalid"}throw new Error(`Error fetching test generation data: ${N}`)}let B=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let N=this.storageService.getLocalSavedJSONFilePath("auto-save"),L=this.storageService.readLocalSavedDataFromJSONFile(N);if(!L)throw new Error(`No data found in auto-save while reading from ${N}`);i=L==null?void 0:L.executedActions}return{actions:i,storyId:B.story.id,testGenerationData:B.testGenerationData}}catch{Yp.warning(`Could not find data matching internal test id: ${(v=this.vtgTestFileRunConfig)==null?void 0:v.internalTestId}`)}if((E=this.vtgTestFileRunConfig)!=null&&E.storyId)return{actions:i,storyId:(D=this.vtgTestFileRunConfig)==null?void 0:D.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:i=!0}={}){var c,p;await this.userStoryService.fetchStory(this.storyId),i&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:s}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:s.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),Hd.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,_=>this.webDriver.registerTimeMachineFrame(_)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),Yp.info("VTG is ready with story:",{goal:(c=this.userStoryService.getStory())==null?void 0:c.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:_,stepsData:v,appViewport:E,userStoryGoal:D,isLoadedFromFile:w})=>{window.vtg.initClient(_,v,E,this.checksumRuntimeVersion,D,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(p=this.userStoryService.getStory())==null?void 0:p.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var c,p,_,v;let i=((p=(c=this.playwrightConfigForVTG)==null?void 0:c.use)==null?void 0:p.navigationTimeout)||3e4,s=((v=(_=this.playwrightConfigForVTG)==null?void 0:_.use)==null?void 0:v.actionTimeout)||5e3;return{navigationTimeout:i,actionTimeout:s}}getPlaywrightProxySettings(){var _,v;let i=(v=(_=this.playwrightConfigForVTG)==null?void 0:_.use)==null?void 0:v.proxy,{server:s,username:c,password:p}=i||{};if(c&&p&&s)return{username:c,password:p,server:s}}getPlaywrightViewportSettings(){var c,p;let{width:i=1280,height:s=720}=((p=(c=this.playwrightConfigForVTG)==null?void 0:c.use)==null?void 0:p.viewport)||{};return{width:i,height:s}}buildWebDriver(i){var p,_,v,E,D,w;let s=this.getPlaywrightProxySettings(),c=this.getPlaywrightViewportSettings();return new TMt({scriptSource:Hd.checksumScript.source,scriptURL:Hd.checksumScript.url,scriptFile:Hd.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(p=this.checksumConfig.environments.find(B=>B.default))==null?void 0:p.baseURL,useProxy:!!s,webProxy:s,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:Hd.vtg.remoteDebugging,remoteDebuggingPort:Hd.vtg.vtgRemoteDebuggingPort},{headless:Hd.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:c,completeOriginHeaderOnLivePage:!Hd.vtg.isSeparateProcess&&!((E=(v=(_=this.checksumConfig.options)==null?void 0:_.modelConfig)==null?void 0:v.browserArgs)!=null&&E.skipDisableWebSecurity)&&!((w=(D=this.checksumConfig.options)==null?void 0:D.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},i)}async onWebDriverContextClose(){var i,s,c;this.evaluatorService.stopListening(),(i=this.vtgTestFileRunConfig)!=null&&i.evalFilePath&&(0,f7e.rmSync)((s=this.vtgTestFileRunConfig)==null?void 0:s.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,f7e.rmSync)((c=this.vtgTestFileRunConfig)==null?void 0:c.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(i){var p;let s=i.indexOf("--edit"),c=i.indexOf("--cloud");if(i.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}s!==-1&&(this.vtgMode="edit",this.editLocationPath=i[s+1]),c!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=i[c+1]),this.vtgMode==="start"&&(this.storyId=i[0])}getWebDriver(){return this.webDriver}async eval(i){return this.evaluatorService.listenForExecution(i)}};e(DQr,"VisualTestGenerator");var JMt=DQr;O1e();var vjn=require("child_process"),wQr=require("net");aw();var Ajn=require("path");iS();var yjn=H0(fut());xU();var SQr=e(async(n,r,i,s,c={})=>{let{preventDialogFromAutoDismissing:p=!1,retry:_=!0,maxRetries:v=void 0,numberOfRetries:E=0}=c;try{console.log(`${n} attempting to connect to ${r} on port ${i}...`);let w=(await yjn.chromium.connectOverCDP("http://127.0.0.1:"+i)).contexts()[0],B=s(w.pages());for(;!B;)await lb(1e3),B=s(w.pages());return console.log(`${n} is connected to ${r} on port ${i}`,B.url()),p&&OBt(B),B}catch(D){if(!_||v&&E>=v)throw console.error(`${n} failed to connect to ${r}, retries were exhausted or disabled`,D),D;return console.log(`${n} is waiting and retrying connection to ${r} on port ${i}...`),await lb(1e3),SQr(n,r,i,s,{...c,numberOfRetries:E+1})}},"connectToPage");g6();var TQr=class TQr{constructor(r){this.checksumConfig=r;this.isReady=!1;this.onMessage=e(async(r,i)=>{let{id:s,err:c,result:p}=await this.execute(r);i.write(this.messageParser.makeMessage(JSON.stringify({id:s,err:this.serializedErr(c),result:p})))},"onMessage");this.messageParser=new J$e(this.onMessage),this.isReadyPromise=new Promise(i=>{this.isReadyResolve=i}),this.routeInterceptor=new tqe({completeOriginHeader:!0})}async eval(r){return this.listenForExecution(r)}async run(r){this.liveAppPage=r,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var i,s,c,p,_,v;if(!((c=(s=(i=this.checksumConfig.options)==null?void 0:i.modelConfig)==null?void 0:s.browserArgs)!=null&&c.skipDisableWebSecurity)&&!((_=(p=this.checksumConfig.options)==null?void 0:p.modelConfig)!=null&&_.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((v=this.liveAppPage)==null?void 0:v.route("**/*",async(E,D)=>this.routeInterceptor.intercept(E,D,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(E){Yp.error("[WebDriver] applyRouteInterceptors error",E)}}startRunner(){let r=Hd.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,Ajn.join)(__dirname,"vtg-pw-bridge-runner.js")}`;Uga(r,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,wQr.createServer)(r=>{r.on("data",async i=>{try{await this.messageParser.onMessage(r,i)}catch(s){r.write(JSON.stringify({err:s.message}))}}),r.on("end",()=>{}),r.on("error",i=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>Yp.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(r){return r&&JSON.stringify(r,Object.getOwnPropertyNames(r))}async connectToVTG(){Yp.info("[VTG PW Bridge] Connecting to VTG...");let r=e(i=>i.frames().find(s=>s.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",Hd.vtg.vtgRemoteDebuggingPort,i=>i.find(s=>r(s))),this.vtgTimeMachineFrame=r(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",Hd.vtg.taskTimeMachine.debugPort,i=>i[0]),Yp.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(r,i,s){return SQr("Playwright via Bridge",r,i,s,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((r,i)=>{let s=(0,wQr.createServer)();s.unref(),s.on("error",i),s.listen(0,()=>{let c=s.address().port;s.close(()=>{r(c)})})})}async listenForExecution(r){return new Promise(i=>{this.resolveEvaluator=i,this.listener=r})}stopListening(){var r;(r=this.resolveEvaluator)==null||r.call(this)}buildContext(r){let{frame:i,expectConfig:s}=r,c={};switch(i){case"task-time-machine":c.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":c.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return s&&(c.expect=bye.expect.configure(s)),c}wrapCodeInContext(r,i){return`(async ({${Object.keys(i).join(", ")}}) => { ${r} })`}async execute(r){this.isReady||Yp.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:i,code:s,options:c}=r,p=this.buildContext(c),_=this.wrapCodeInContext(s,p)+"(context)";return new Promise(v=>{this.listener&&this.listener(_,p,(E,D)=>{v({id:i,err:E,result:D})})})}};e(TQr,"VtgPwBridge");var zMt=TQr;async function Uga(n,r={}){let i={...process.env,...r};(0,vjn.spawn)(n,{env:i,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",c=>{process.exit(c)})}e(Uga,"spawnCmd");var zjn=require("@playwright/test"),Hjn=H0(Jjn());var Gre=class Gre{constructor(r){this.options=r;this.importPluginPackages()}importPluginPackages(){Gre.pw??(Gre.pw=fut()),Gre.StealthPlugin??(Gre.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:r}=fut(),i=r(Gre.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),i}catch(r){throw console.error("[StealthProvider] Error creating fresh instance:",r),r}}buildChromiumWithPlugins(r){let{project:i}=this.options,s=i.use.userAgent,c=i.use.playwrightExtra||[],p=Gre.StealthPlugin();if(c.push(p),this.isCustomUserAgent(s)){p.enabledEvasions.delete("user-agent-override");let E=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:s});c.push(E)}let _=r??Gre.pw.chromium;return c.forEach((v,E)=>{try{!(v instanceof Hjn.PuppeteerExtraPlugin)&&v!==p&&console.warn(`Plugin at index ${E} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),_.use(v)}catch(D){console.warn(D)}}),_}isCustomUserAgent(r){return r?!Object.values(zjn.devices).some(i=>r===i.userAgent):!1}};e(Gre,"StealthProvider");var GMt=Gre;W5t();function Wjn(n,r){return{testSuiteRunId:r,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:n}}e(Wjn,"createDefaultTestSuiteRunInfo");var Kjn=require("crypto");uNr();var d7e=class d7e{constructor(r,i){this.context=r;this.isVTG=i;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++d7e.instanceCounter,this.setContextProxy()}static makeContext(r,i){return new d7e(r,i).proxy}_rawContext(){return this.context}setTestAssets(r){this._testAssets=r,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let r=await this.context.newPage();return await this.makePage(r)}async makePage(r){if(r._isChecksumPage===!0)return r;if(r.isClosed())throw new Error("Cannot initialize closed page");let i=this.getPageGuid(r);if(this.hasPage(i))return this.getPageByGuid(i);if(this._pagesInProgress.has(i))return this._pagesInProgress.get(i);let s=this._createPageInstance(r);this._pagesInProgress.set(i,s);try{let c=await s;return this._pagesInProgress.delete(i),this.addPage(c),c}catch(c){throw this._pagesInProgress.delete(i),c}}addPage(r){let i=this.getPageGuid(r);this._pages[i]=r,r.once("close",()=>{this.removePage(i)})}removePage(r){this._pages[r]&&delete this._pages[r]}async _createPageInstance(r){if(r.isClosed())throw new Error("Cannot initialize page: Page has already been closed");if(this._testAssets)try{return await BBt.init(r,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(i){throw new Error(`Failed to initialize RuntimePage: ${i instanceof Error?i.message:String(i)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}setContextProxy(){this.proxy=new Proxy(this,{get:e(function(i,s){return i.getContextMethod(s)},"get")})}setupPageListener(){this.context.on("page",async r=>{try{if(r.isClosed())return;await this.makePage(r)}catch(i){let s=i instanceof Error?i.message:String(i);if(s.includes("Page has already been closed")||s.includes("Target page, context or browser has been closed")){console.debug("[ChecksumBrowserContext] Skipping initialization of closed page");return}throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",i),i}})}getPageGuid(r){let i=this.pageGuidMap.get(r);return i||(i=`page@checksumctx_${this.instanceId}_${++d7e.guidCounter}`,this.pageGuidMap.set(r,i)),i}getPageByGuid(r){return this._pages[r]}hasPage(r){return r in this._pages}getAllPages(){return Object.values(this._pages)}getContextMethod(r){if(r in this){let s=this[r];return typeof s=="function"?s.bind(this):s}let i=this.context[r];return typeof i=="function"?i.bind(this.context):i}pages(){return this.getAllPages()}getPage(r){let i=this.getAllPages(),s=i[r];if(!s)throw new Error(`Page with index ${r} not found. Total pages: ${i.length}`);return s}};e(d7e,"ChecksumBrowserContext"),d7e.instanceCounter=0,d7e.guidCounter=0;var KMt=d7e;var NQr={},K$e=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,Yjn=e((n,r,i={},s=!1)=>{let{runMode:c,environments:p}=r,_=p.find(E=>E.default),v=n.extend({baseURL:_.baseURL,bypassCSP:!0,...K$e?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},E,D)=>{if(!K$e)await E(D.project.use.permissions);else{let w=new Set(D.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await E(Array.from(w))}},"permissions"),proxy:e(async({proxy:E},D)=>{E?await D({...E,bypass:"127.0.0.1,localhost"}):await D(E)},"proxy"),browser:e(async({browser:E,browserName:D,launchOptions:w},B,N)=>{let L=e(()=>(N.project.use.playwrightExtra||[]).some(ue=>ue.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),M=e(async()=>{let Z=await(await new GMt({project:N.project}).buildChromiumWithPlugins()).launch(w);await B(Z)},"launchBrowserWithStealthPlugin");K$e?Hd.vtg.isSeparateProcess?await B(E):L()?(console.log("StealthPlugin already configured"),await B(E)):await M():Hd.useRemoteDebugging.enabled&&L()?await M():await B(E)},"browser"),launchOptions:e(async({launchOptions:E},D)=>{var N;let w=E!=null&&E.args?[...E.args]:[],B=e(L=>{w.includes(L)||w.push(L)},"pushArg");if(i.useMockData&&B("--disable-web-security"),Hd.bypassProxyForLocalhost&&B("--proxy-bypass-list=localhost,127.0.0.1"),K$e){B("--proxy-bypass-list=localhost,127.0.0.1"),Hd.vtg.isSeparateProcess&&B(`--remote-debugging-port=${Hd.vtg.appRemoteDebuggingPort}`);let L=((N=i.modelConfig)==null?void 0:N.browserArgs)??{};L.skipDisableWebSecurity||B("--disable-web-security"),L.skipAllowFileAccessFromFiles||B("--allow-file-access-from-files"),L.skipDisableSiteIsolationTrials||B("--disable-site-isolation-trials"),L.skipAllowRunningInsecureContent||B("--allow-running-insecure-content")}Hd.useRemoteDebugging.enabled&&B(`--remote-debugging-port=${Hd.useRemoteDebugging.port}`),await D({...E,args:w})},"launchOptions"),variableStore:e(async({},E)=>{let D=new NQe;await E(D)},"variableStore"),vs:e(async({variableStore:E},D)=>{await D(E)},"vs"),variablesStore:e(async({variableStore:E},D)=>{await D(E)},"variablesStore"),testRunAnalytics:e(async({},E,D)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),Wjn("playwright-run-version-unknown",(0,Kjn.randomUUID)())}})(),B=Gjn(D),N=Zte.getTestRunInstance({...w,checksumTestId:B},process.env.CHECKSUM_ISOLATED_MODE==="true",D);await E(N)},"testRunAnalytics"),monitorBridge:[async({},E,D)=>{let w=new UBt(D);await E(w)},{scope:"worker"}],context:e(async({context:E,monitorBridge:D,variableStore:w,testRunAnalytics:B},N,L)=>{let M=KMt.makeContext(E,K$e);M.setTestAssets({testRunAnalytics:B,monitorBridge:D,variableStore:w,testInfo:L,checksumTestId:Gjn(L),test:v,config:r,isReplMode:s}),await N(M),M.cleanup()},"context"),page:e(async({page:E,context:D},w,B)=>{let N=await D.makePage(E);Object.defineProperty(N.constructor,"name",{value:"Page"}),await w(N),N&&typeof N.onTestComplete=="function"&&await N.onTestComplete(B.status==="passed"),N&&typeof N.shutdown=="function"&&await N.shutdown()},"page"),vtg:e(async({page:E},D)=>{if(!K$e)D(null);else if(Hd.vtg.isSeparateProcess){let w=new zMt(r);await w.run(E),await D(w)}else{let w=new JMt(["--test-file"],!1,r);await w.run(E),await D(w)}},"vtg")});return{test:v,defineChecksumTest:rya}},"createChecksumTestExtension"),rya=e((n,r,i)=>{let c=new Error().stack.split(`
1909
1909
  `).filter(p=>p.includes(".checksum.spec.ts"))[0];if(!c)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return NQr[c]=r,n},"defineChecksumTest");function Gjn(n){let{file:r,line:i}=n,s=Object.keys(NQr).filter(p=>p.trim().includes(r.trim()));if(!s.length)return;let c=4;for(let p=0;p<c;p++)for(let _ of s){let v;try{v=parseInt(_.split(":").reverse()[1])}catch{continue}if(v-p===parseInt(i))return NQr[_]}}e(Gjn,"getCurrentTestIdFromMapping");xU();fH();Rte();xU();var nya=["toPass"],iya=["toBeOK"],aya=["toBeAttached","toBeChecked","toBeDisabled","toBeEditable","toBeEmpty","toBeEnabled","toBeFocused","toBeHidden","toBeInViewport","toBeVisible","toContainClass","toContainText","toHaveAccessibleDescription","toHaveAccessibleErrorMessage","toHaveAccessibleName","toHaveAttribute","toHaveClass","toHaveCount","toHaveCSS","toHaveId","toHaveJSProperty","toHaveRole","toHaveScreenshot","toHaveText","toHaveValue","toHaveValues","toMatchAriaSnapshot"],sya=["toHaveScreenshot","toHaveTitle","toHaveURL"],oya=["toMatchSnapshot"],cya=["toBe","toBeCloseTo","toBeDefined","toBeFalsy","toBeGreaterThan","toBeGreaterThanOrEqual","toBeInstanceOf","toBeLessThan","toBeLessThanOrEqual","toBeNaN","toBeNull","toBeTruthy","toBeUndefined","toContain","toContainEqual","toEqual","toHaveLength","toHaveProperty","toMatch","toMatchObject","toStrictEqual","toThrow","toThrowError"],Xjn=[...cya,...oya],t7s=[...nya,...iya,...aya,...sya];var BQr=class BQr{constructor(r,i,s=!1,c=!1,p={}){this.page=r;this.soft=s;this.skipAutoRecovery=c;this.configuration=p;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=e(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(i)}setThought(r){var i,s;r&&(this.checksumAIThought=this.page.addNewThought(r,"assertion"),this.useChecksumAIOptions=(i=this.page.getRuntimeOptions())==null?void 0:i.useChecksumAI,(s=this.useChecksumAIOptions)!=null&&s.assertions&&(this.page.setAIFallback(r,"assertion"),this.fallbackEnabled=!0))}get(r,i,s){if(typeof i!="string")return r[i];if(i==="checksumAI")return c=>(this.setThought(c),s);if(i==="withChecksumAI"||typeof r[i]=="function"){let c=i==="withChecksumAI"?this.withChecksumAIMatcher:r[i];return(...p)=>Xjn.includes(i)?c.call(r,...p):this.checksumAIThought?this.executeMatcherWithinStep(c,r,...p):this.executeMatcher(c,r,...p)}else{let c=r[i];return new Proxy(c,this)}}findNestedErrors(r,i){r.error&&r.infectParentStepsWithError&&i.push(r.error);for(let s of r.steps)this.findNestedErrors(s,i)}async callMatcher(r,i,...s){this.beforeMatcherCall();let c=r.call(i,...s),p=c instanceof Promise?await c:c;if(this.step){let _=[];if(this.step.error?_.push(this.step.error):this.findNestedErrors(this.step,_),_.length)throw _[0]}return p}executeMatcherWithinStep(r,i,...s){return this.page.step(this.checksumAIThought.thought,()=>this.callMatcher(r,i,...s).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:e(c=>this.step=c,"obtainStep")}).catch(c=>{if(!this.soft&&!(this.withChecksumAI&&c.message===pCe))throw c}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(r,i,...s){try{return await this.callMatcher(r,i,...s)}catch(c){await this.onMatcherFailure(c)}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}shouldInitiateFallback(r){var s;return!(!this.fallbackEnabled||((s=r.matcherResult)==null?void 0:s.name)==="toHaveScreenshot"&&!this.useChecksumAIOptions.visualComparison)}async onMatcherFailure(r){var i,s;if(!this.shouldInitiateFallback(r))throw mv("[onMatcherFailure] fallback disabled, continuing with error."),this.page.testRunAnalytics.testRunAssertionExecutionFailure({failedThought:(i=this.checksumAIThought)==null?void 0:i.thought,error:r.message,matcher:(s=r.matcherResult)==null?void 0:s.name}),r;if(mv("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought.thought),this.skipAutoRecovery){if(this.soft)return;throw r}try{await this.page.initiateFallbackSequence({type:"assertion",error:r,withChecksumAI:this.withChecksumAI,testInfo:this.page.testInfo})}catch(c){if(this.soft)return;throw c}throw this.soft=!0,r}};e(BQr,"ExpectCallProxyHandler");var YMt=BQr;var rpt=class rpt{constructor(r=void 0,i={}){this.page=r;this.configuration=i}get(r,i){return i==="setPage"?s=>{this.page=s}:i==="extend"?(...s)=>{let c=r.extend(...s);return new Proxy(c,this)}:i==="configure"?s=>{let c=r.configure(s);return new Proxy(c,new rpt(this.page,{...this.configuration,...s}))}:i==="soft"?(...s)=>{let c=this.manipulateArgsAndExtractThought(s),p=r.soft(...s);return new Proxy(p,this.makeExpectCallProxyHandler(c,!0))}:i==="poll"?(...s)=>{let c=this.manipulateArgsAndExtractThought(s),p=r.poll(...s);return new Proxy(p,this.makeExpectCallProxyHandler(c))}:i==="skipAutoRecovery"?new Proxy(()=>{},{apply:e((c,p,_)=>{let v=this.manipulateArgsAndExtractThought(_),E=r.apply(p,_);return new Proxy(E,this.makeExpectCallProxyHandler(v,void 0,!0))},"apply"),get:e((c,p)=>new Proxy(r,new rpt(this.page,{...this.configuration,skipAutoRecovery:!0}))[p],"get")}):r[i]instanceof Function?r[i].bind(r):r[i]}apply(r,i,s){let c=this.manipulateArgsAndExtractThought(s),p=r.apply(i,s);return new Proxy(p,this.makeExpectCallProxyHandler(c))}makeExpectCallProxyHandler(r,i,s){var c,p;return new YMt(this.page,r,i===!0?!0:(c=this.configuration)==null?void 0:c.soft,s===!0?!0:(p=this.configuration)==null?void 0:p.skipAutoRecovery,this.configuration)}manipulateArgsAndExtractThought(r){let i,s=r[1];if(typeof s=="string")i=s,r[1]=void 0;else if(typeof s=="object"){if(s.checksumAI===!1){r[1].checksumAI=void 0;return}s.checksumAI&&typeof s.checksumAI=="string"?(i=s.checksumAI,r[1].checksumAI=void 0):s.message&&(i=s.message,r[1].message=void 0)}return i}};e(rpt,"ExpectProxyHandler");var XMt=rpt;var ejt=class ejt{constructor(r){this.expect=r;this.proxy=new Proxy(this.expect,new XMt)}static init(r){return new ejt(r).proxy}};e(ejt,"ChecksumExpect");var ZMt=ejt;iS();var tUn=require("@playwright/test");xU();var Zjn=H0(sw()),tjt=require("fs");var npt=H0(require("path"));var uya=e(n=>{let r=X6e(n),i=new Z6e(r),s=Gut();return i.transformSourceFile([new Eke(n),new _$e(n,s,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[Zjn.factory.createIdentifier("__filename")]})]),`${MFn}
1910
1910
  ${i.getTestFileCode().code}`},"transformFileToHoRequireFormat"),lya=e(n=>{let r=npt.default.dirname(n),s=npt.default.basename(n).split(".")[0],c=Math.random().toString(36).substring(2,15),p=npt.default.extname(n);return npt.default.join(r,`${s}-${Date.now()}-${c}${p}`)},"generateTempFilePath"),pya=e((n,r)=>{let i=Gut();return new e7e(r,i).getResolvedPath(n)},"resolveFilePath"),fya=e((n,r=__filename)=>{let i;try{let s=require.resolve(pya(n,r)),c=uya(s);i=lya(s),(0,tjt.writeFileSync)(i,c);let p=require(i);return require.cache[s]=require.cache[i],p}catch(s){throw console.error("Error in require",s),s}finally{i&&(0,tjt.unlinkSync)(i)}},"checksumHotRequire"),eUn=fya;O1e();function dya(n){let r=SIt(),{options:i,apiKey:s,environments:c,defaultEnvironmentName:p}=r,_=c.find(M=>M.default);if(p&&(_=c.find(M=>M.name===p)),!_)throw new Error("No default environment found. Please set the default field to true on one of the environments in the checksum.config.ts file.");if(!_.baseURL)throw new Error("A baseURL is required. Please set the baseURL field in the default environment in the checksum.config.ts file.");if(!_.users.find(M=>M.default))throw new Error("A default user within the default environment is required. Please set one of the default environment users as default in the checksum.config.ts file.");if(!s)throw new Error("An API key is required. Please set the apiKey field in the checksum.config.ts file.");let E=process.env.CHECKSUM_REPL==="true",{test:D,defineChecksumTest:w}=Yjn(n??tUn.test,r,i,E),B=ZMt.init(D.expect),N=_ya();D._checksum={expect:B,checksumAI:N},E&&(console.log("Detected REPL mode"),D.beforeEach(async()=>{D.setTimeout(0)}),D.afterEach(async()=>{for(;;)await lb(1e3)}));let L=e(({name:M,userRole:V})=>{let{environment:Z,user:ue}=$ct(r,{environment:M,role:V},!0),le=DSn({config:r,throwIfEnvInfoInvalid:!0},{environmentName:Z.name,userRole:ue.role});return{environment:Z,user:ue,login:le}},"getEnvironment");return{test:D,expect:B,login:hye({config:r}),defineChecksumTest:w,getEnvironment:L,checksumAI:N}}e(dya,"init");var OQr=e(n=>new Proxy(n,{apply:e(function(i,s,c){let p={...i.options,...c[2]};return i.page.checksumAI(c[0],c[1],p)},"apply"),get:e(function(i,s){return s==="withDialog"?(i.options.withDialog=!0,OQr(n)):s==="skipAutoRecovery"?(i.options.skipAutoRecovery=!0,OQr(n)):i[s]},"get"),set:e(function(i,s,c){if(s==="page")return i[s]=c},"set")}),"makeChecksumAIProxy"),_ya=e(()=>{let n=e(function(){},"func");return n.page=void 0,n.options={withDialog:!1,withTomer:!1,skipAutoRecovery:!1},OQr(n)},"makeChecksumAI");0&&(module.exports={AutoRecoveryMode,RunMode,checksumHotRequire,getChecksumConfig,getLogin,init});
1911
1911
  /*! Bundled license information: