@checksum-ai/runtime 4.3.2-beta.10 → 4.3.2-beta.11

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.
Files changed (4) hide show
  1. package/.env +1 -1
  2. package/cli.js +44 -44
  3. package/index.js +1 -1
  4. package/package.json +1 -1
package/index.js CHANGED
@@ -612,7 +612,7 @@ ${this.executedSteps.map(_=>{switch(_.type){case"action":return _.thought;case"a
612
612
  `)[4])==null?void 0:u.trim().match(/\(([^)]+)\)/);if(!(g&&g[1]))throw new Error;let b=g[1].split(":"),w=b.slice(0,-2).join(":"),k=b[b.length-2],G=`${GQt.default.basename(w)}:${k}`;c&&(process.stdout.write(kGe.default.format("\x1B[34m",G,"\x1B[0m",...s)+`
613
613
  `),setTimeout(()=>this.listeners.forEach(z=>z.onLog(...s)),0)),this.logStream&&this.logStream.write(`[${G}] ${s.map(z=>{if(typeof z=="object")try{return JSON.stringify(z,null,2)}catch{}return String(z)}).join(" ")}
614
614
  `)}catch{c&&process.stdout.write(kGe.default.format(...s)+`
615
- `)}}shouldLog(n){switch(n){case"warning":return this.logLevel==="all"||this.logLevel==="warnings";case"error":return!0;case"info":return this.logLevel==="all";default:return!1}}addListener(n){this.listeners.push(n)}info(...n){this.log("info",...n)}warning(...n){this.log("warning",...n)}error(...n){this.log("error",...n)}setLogLevel(n){this.logLevel=n}setLogStream(n){this.logStream=n}};t(NGe,"Logger");var DGe=NGe,ej=new DGe,tzr=Object.assign((...i)=>ej.info(...i),{info:t((...i)=>ej.info(...i),"info"),warning:t((...i)=>ej.warning(...i),"warning"),error:t((...i)=>ej.error(...i),"error"),setLogLevel:t(i=>ej.setLogLevel(i),"setLogLevel"),setLogStream:t(i=>ej.setLogStream(i),"setLogStream"),addLogListener:t(i=>ej.addListener(i),"addLogListener")}),tj=tzr;var Uue=require("perf_hooks");var PGe=class PGe{constructor(n={}){this.options=n;this.priorityQueue=[];this.nonPriorityQueue=[];this.isRunning=!1;this.taskIndex=0;this.timeRunningTasks=0;this.timeGoingBack=0;this.tasksExecuted=0}enqueue(n){let s=this.taskIndex++,c={...n,index:s,queuedAt:Uue.performance.now()};if(n.priority)this.priorityQueue.push(c);else if(this.options.sortByTimestamp){let u=this.nonPriorityQueue.findIndex(_=>_.timestamp!==void 0&&n.timestamp!==void 0&&_.timestamp>n.timestamp);u===-1?this.nonPriorityQueue.push(c):this.nonPriorityQueue.splice(u,0,c)}else this.nonPriorityQueue.push(c);return s}popTask(){return this.priorityQueue.length>0?this.priorityQueue.shift():this.nonPriorityQueue.shift()}async runSingleTask(n,s){let c=Uue.performance.now();try{if(this.options.logPerformance){let _=Uue.performance.now()-n.queuedAt;tj.info(`Running task, timestamp: ${n.timestamp} \x1B[36m${n.name}\x1B[0m, index: ${n.index}, was pending for ${_}ms`)}await s(n);let u=Uue.performance.now()-c;this.timeRunningTasks+=u,this.options.logPerformance&&tj.info("Finished running task, took",u,"ms.","Queue lengths:",`priority=${this.priorityQueue.length}`,`non-priority=${this.nonPriorityQueue.length}`),this.tasksExecuted++}catch(u){tj.error("Task execution error:",u)}}async runTasks(n){if(!this.isRunning){this.isRunning=!0;try{for(;this.getQueueLength()>0;){let s=this.popTask();if(!s)break;await this.runSingleTask(s,n)}}finally{this.isRunning=!1,this.getQueueLength()>0&&this.options.logPerformance&&tj.info("Accumulated time running tasks:",this.timeRunningTasks,"ms, from which time spent going back:",this.timeGoingBack)}}}getTasksAtTimestamp(n){return[...this.priorityQueue.filter(s=>s.timestamp===n),...this.nonPriorityQueue.filter(s=>s.timestamp===n)]}removeTasksAtTimestamp(n){this.priorityQueue=this.priorityQueue.filter(s=>s.timestamp!==n),this.nonPriorityQueue=this.nonPriorityQueue.filter(s=>s.timestamp!==n)}getQueueLength(){return this.priorityQueue.length+this.nonPriorityQueue.length}setTimeGoingBack(n){this.timeGoingBack=n}};t(PGe,"TaskTimeMachineQueue");var jue=PGe;var wde=mc(uVt());function fVt(i){if(!i)return;let{username:n,password:s,server:c}=i;return n&&s?new wde.ProxyAgent({uri:`http://${n}:${s}@${c.replace("http://","")}`}):new wde.ProxyAgent({uri:c})}t(fVt,"makeWebProxyAgent");async function Son(i,n){let c=i.request().url();try{let _=await(0,wde.fetch)(c,n?{dispatcher:n}:{}),g=_.status,b={};_.headers.forEach((le,ye)=>b[ye]=le),b["access-control-allow-origin"]="*";let w=parseInt(_.headers.get("content-length")||"0",10),k=25*1024*1024;if(w>k){await i.continue();return}if(!_.body){await i.fulfill({status:g,headers:b});return}let G=await _.arrayBuffer(),z=Buffer.from(G);await i.fulfill({status:g,headers:b,body:z})}catch{await i.continue()}}t(Son,"handleCorsRoute");async function dVt(i,n,s){try{let c=i.page(),u=Nh(c);if(s.has(u))return;s.add(u),await c.route(/^https?:\/\/(?!(?:localhost|127\.0\.0\.1|::1)).*/,_=>Son(_,n))}catch{}}t(dVt,"preventCrossOriginErrors");var kde=require("perf_hooks");async function _Vt(i,{shouldGoBack:n,shouldBatch:s,task:c,timestamp:u,beforeTimestamp:_,name:g,resolve:b,reject:w}){if(i.requireTimeMachineFrame().isDetached()&&w(),n){let G=kde.performance.now();await i.goBack(u,_),i.addTimeGoingBack(kde.performance.now()-G)}let k=pVt(i,{taskForSafeRun:c,name:g,resolve:b,reject:w}),O=i.taskQueue.getQueueLength()>0&&s?Ion(i,{firstTask:k,timestamp:u,name:g,resolve:b,reject:w}):[k];for(let G of O)await G()}t(_Vt,"runTaskWrapper");function pVt(i,{taskForSafeRun:n,name:s,resolve:c,reject:u}){return async()=>{try{let _=kde.performance.now(),g=await Zm(n(i.requireTimeMachineFrame()),i.options.taskTimeout,()=>`Task execution timeout - ${s}, took ${kde.performance.now()-_}ms with timeout of ${i.options.taskTimeout}ms`);c(g)}catch(_){tj.error("Task execution error:",_.message),u(_)}}}t(pVt,"makeSafeRunTask");function Ion(i,{firstTask:n,timestamp:s,name:c,resolve:u,reject:_}){let g=[n],b=i.taskQueue.getTasksAtTimestamp(s);return g.push(...b.map(({task:w})=>pVt(i,{taskForSafeRun:t(()=>w({shouldGoBack:!1,shouldBatch:!1}),"taskForSafeRun"),name:c,resolve:u,reject:_}))),i.taskQueue.removeTasksAtTimestamp(s),g}t(Ion,"collectBatchedTasks");var Ton="checksum is not defined";async function srt(i,n,{retriesLeft:s=3,retryWaitMS:c=1e3}={}){try{let{reducedHTML:u,currentChecksumId:_}=await n.evaluate(async({errorMessage:g,...b})=>{if(!window.checksum)throw new Error(g);return window.checksum.testGenerator.reduceHTML({},b)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:i.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0,errorMessage:Ton});return i.currentChecksumId=_,{reducedHTML:u}}catch(u){if(s>0)return await Dh(c),srt(i,n,{retriesLeft:s-1,retryWaitMS:c});throw u}}t(srt,"getReducedHTMLWithRetries");function mVt({frameMsgBroker:i,recordingFrame:n,timeMachineFrame:s,handler:c}){let u="rrweb";if(!n)throw new Error("Recording frame is not initialized");i.subscribeToChannel(u,s,{originFrame:n,handler:c}),s.page().on("close",()=>i.unsubscribeFromChannel(u,s))}t(mVt,"subscribeToRrwebEvents");var gke="checksum is not defined",ort=class ort{constructor(n,s,c={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0}){this.frameMsgBroker=n;this.injectedScriptManager=s;this.options=c;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.currentChecksumId="0";this.timeGoingBack=0;this.pagesWithCorsInterception=new Set;this.reducedHTMLCache={};this.taskQueue=new jue({sortByTimestamp:c.sortByTimestamp,logPerformance:c.logPerformance}),this.webProxyAgent=fVt(c.webProxy)}requireTimeMachineFrame(){if(!this.timeMachineFrame)throw new Error("Time machine frame is not initialized");return this.timeMachineFrame}addTimeGoingBack(n){this.timeGoingBack+=n,this.taskQueue.setTimeGoingBack(this.timeGoingBack)}getPage(){return this.requireTimeMachineFrame().page()}getFrame(){return this.requireTimeMachineFrame()}async prepare(n,s,c){this.recordingFrame=n,await this.frameMsgBroker.register("live",n),s?this.timeMachineFrame=s:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),await dVt(this.timeMachineFrame,this.webProxyAgent,this.pagesWithCorsInterception),this.options.frameMsgBrokerRegisterName&&await this.frameMsgBroker.register(this.options.frameMsgBrokerRegisterName,this.timeMachineFrame),c&&c(this.timeMachineFrame),await this.injectedScriptManager.addTrackedFrame(this.timeMachineFrame),this.timeMachineFrame.page().on("framenavigated",async u=>{await this.injectedScriptManager.onFrameNavigated(u)}),mVt({frameMsgBroker:this.frameMsgBroker,recordingFrame:this.recordingFrame,timeMachineFrame:this.requireTimeMachineFrame(),handler:this.rrwebEventHandler.bind(this)}),this.taskQueue=new jue({sortByTimestamp:this.options.sortByTimestamp,logPerformance:this.options.logPerformance}),await this.start()}async start(){await this.requireTimeMachineFrame().evaluate(async n=>{if(!window.checksum)throw new Error(n);window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})},gke)}setBrowserContext(n){this.timeMachineBrowserContext=n}async executeTask(n,s,{name:c,beforeTimestamp:u=!1,priority:_=!1}={}){return new Promise((g,b)=>{let w=t((k={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled??!1})=>_Vt(this,{...k,task:n,timestamp:s,beforeTimestamp:u,name:c,resolve:g,reject:b}),"taskWrapper");this.taskQueue.enqueue({name:c,task:w,timestamp:u&&s!==void 0?s-1:s,priority:_}),this.runTasks()})}executeReducedHTMLTask(n,{priority:s=!1}={}){if(this.reducedHTMLCache[n]){let c=new Que(this.reducedHTMLCache[n]);return Promise.resolve(c.getRrwebIdsReducedDomString())}return this.executeTask(async c=>{let _=(await srt(this,c)).reducedHTML;return _&&(this.reducedHTMLCache[n]=_),new Que(_).getRrwebIdsReducedDomString()},n,{name:"getReducedHTMLForTimestamp",priority:s})}goBack(n,s=!1){return this.currentBeforeTimestamp===s&&this.currentTimestamp===n?Promise.resolve():(this.currentTimestamp=n,this.currentBeforeTimestamp=s,this.requireTimeMachineFrame().evaluate(({timestamp:c,beforeTimestamp:u,errorMessage:_})=>{if(!window.checksum)throw new Error(_);return c===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(c,{beforeTimestamp:u})},{timestamp:n,beforeTimestamp:s,errorMessage:gke}))}async runTasks(){await this.taskQueue.runTasks(async n=>{await n.task()})}async rrwebEventHandler(n){let s=JSON.stringify(n);try{await this.requireTimeMachineFrame().evaluate(function({eventsJSON:c,errorMessage:u}){if(!window.checksum)throw new Error(u);let _=JSON.parse(c);return window.checksum.timeMachine.handleEvents(_)},{eventsJSON:s,errorMessage:gke})}catch{}return s}async makeBrowserContext(){let n=[];this.options.debugPort&&n.push(`--remote-debugging-port=${this.options.debugPort}`);let{headless:s}=this.options,c=await hVt.chromium.launch({...s!==void 0?{headless:s}:{},args:n});return this.timeMachineBrowserContext=await c.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){if(!this.timeMachineBrowserContext)throw new Error("Time machine browser context is not initialized");return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}async toggleTimeMachineHandleEvents(n){try{await this.requireTimeMachineFrame().evaluate(({shouldHandleEvents:s,errorMessage:c})=>{if(!window.checksum)throw new Error(c);return window.checksum.timeMachine.setShouldHandleEvents(s)},{shouldHandleEvents:n,errorMessage:gke})}catch{}}};t(ort,"ChecksumTimeMachine");var yke=ort;var art=require("@playwright/test"),crt=mc(require("fs")),gVt=mc(require("fs/promises")),yVt=mc(require("path")),AVt=mc(d$e());var xon=1e3,won=t(()=>{},"noopPostProcessRRwebEvents"),lrt=class lrt extends yke{constructor(s,c,u={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0,recordRRwebEventsToFile:!1,recordRRwebEventsToFilePath:"events.json"}){super(s,c,u);this.options=u;this.rrwebEventsBuffer="";this.rrwebTotalBytes=0;this.rrwebRecordingCapped=!1;this.postProcessRRwebEvents=(0,AVt.debounce)(won,100,{leading:!0,trailing:!0});let _=this.options.recordRRwebEventsToFilePath;if(this.options.recordRRwebEventsToFile&&_){let g=yVt.default.dirname(_);crt.default.mkdirSync(g,{recursive:!0}),crt.default.writeFileSync(_,"")}}setTimeMachineBrowserContext(s){this.timeMachineBrowserContext=s}getTimeMachineBrowserContext(){return this.timeMachineBrowserContext}async makeBrowserContext(){art.chromium._checksumInternal=!0;let s=await art.chromium.launch({...this.options.headless!==void 0?{headless:this.options.headless}:{},args:Vl.useRemoteDebugging.enabled?["--remote-debugging-port=4444"]:[]});return s._checksumInternal=!0,this.timeMachineBrowserContext=await s.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(){if(!this.timeMachineBrowserContext)throw new Error("Time machine browser context is not initialized");let s=await this.timeMachineBrowserContext.newPage();s._checksumInternal=!0;let c=s.mainFrame();return c._checksumInternal=!0,c}async rrwebEventHandler(s){if(this.rrwebRecordingCapped)return"";let c=await super.rrwebEventHandler(s),u=this.options.maxRRwebBytes??0;if(this.rrwebTotalBytes+=c.length,bMt(this.rrwebTotalBytes,u)&&(this.rrwebRecordingCapped=!0,console.warn(`[checksum] rrweb recording exceeded ${u} bytes \u2014 truncating the recording to protect worker memory (set CHECKSUM_RUNTIME_RRWEB_MAX_BYTES to retune, 0 to disable)`)),!this.options.recordRRwebEventsToFile)return c;if(this.rrwebEventsBuffer+=c+`
615
+ `)}}shouldLog(n){switch(n){case"warning":return this.logLevel==="all"||this.logLevel==="warnings";case"error":return!0;case"info":return this.logLevel==="all";default:return!1}}addListener(n){this.listeners.push(n)}info(...n){this.log("info",...n)}warning(...n){this.log("warning",...n)}error(...n){this.log("error",...n)}setLogLevel(n){this.logLevel=n}setLogStream(n){this.logStream=n}};t(NGe,"Logger");var DGe=NGe,ej=new DGe,tzr=Object.assign((...i)=>ej.info(...i),{info:t((...i)=>ej.info(...i),"info"),warning:t((...i)=>ej.warning(...i),"warning"),error:t((...i)=>ej.error(...i),"error"),setLogLevel:t(i=>ej.setLogLevel(i),"setLogLevel"),setLogStream:t(i=>ej.setLogStream(i),"setLogStream"),addLogListener:t(i=>ej.addListener(i),"addLogListener")}),tj=tzr;var Uue=require("perf_hooks");var PGe=class PGe{constructor(n={}){this.options=n;this.priorityQueue=[];this.nonPriorityQueue=[];this.isRunning=!1;this.taskIndex=0;this.timeRunningTasks=0;this.timeGoingBack=0;this.tasksExecuted=0}enqueue(n){let s=this.taskIndex++,c={...n,index:s,queuedAt:Uue.performance.now()};if(n.priority)this.priorityQueue.push(c);else if(this.options.sortByTimestamp){let u=this.nonPriorityQueue.findIndex(_=>_.timestamp!==void 0&&n.timestamp!==void 0&&_.timestamp>n.timestamp);u===-1?this.nonPriorityQueue.push(c):this.nonPriorityQueue.splice(u,0,c)}else this.nonPriorityQueue.push(c);return s}popTask(){return this.priorityQueue.length>0?this.priorityQueue.shift():this.nonPriorityQueue.shift()}async runSingleTask(n,s){let c=Uue.performance.now();try{if(this.options.logPerformance){let _=Uue.performance.now()-n.queuedAt;tj.info(`Running task, timestamp: ${n.timestamp} \x1B[36m${n.name}\x1B[0m, index: ${n.index}, was pending for ${_}ms`)}await s(n);let u=Uue.performance.now()-c;this.timeRunningTasks+=u,this.options.logPerformance&&tj.info("Finished running task, took",u,"ms.","Queue lengths:",`priority=${this.priorityQueue.length}`,`non-priority=${this.nonPriorityQueue.length}`),this.tasksExecuted++}catch(u){tj.error("Task execution error:",u)}}async runTasks(n){if(!this.isRunning){this.isRunning=!0;try{for(;this.getQueueLength()>0;){let s=this.popTask();if(!s)break;await this.runSingleTask(s,n)}}finally{this.isRunning=!1,this.getQueueLength()>0&&this.options.logPerformance&&tj.info("Accumulated time running tasks:",this.timeRunningTasks,"ms, from which time spent going back:",this.timeGoingBack)}}}getTasksAtTimestamp(n){return[...this.priorityQueue.filter(s=>s.timestamp===n),...this.nonPriorityQueue.filter(s=>s.timestamp===n)]}removeTasksAtTimestamp(n){this.priorityQueue=this.priorityQueue.filter(s=>s.timestamp!==n),this.nonPriorityQueue=this.nonPriorityQueue.filter(s=>s.timestamp!==n)}getQueueLength(){return this.priorityQueue.length+this.nonPriorityQueue.length}setTimeGoingBack(n){this.timeGoingBack=n}};t(PGe,"TaskTimeMachineQueue");var jue=PGe;var wde=mc(uVt());function fVt(i){if(!i)return;let{username:n,password:s,server:c}=i;return n&&s?new wde.ProxyAgent({uri:`http://${n}:${s}@${c.replace("http://","")}`}):new wde.ProxyAgent({uri:c})}t(fVt,"makeWebProxyAgent");async function Son(i,n){let c=i.request().url();try{let _=await(0,wde.fetch)(c,n?{dispatcher:n}:{}),g=_.status,b={};_.headers.forEach((le,ye)=>b[ye]=le),b["access-control-allow-origin"]="*";let w=parseInt(_.headers.get("content-length")||"0",10),k=25*1024*1024;if(w>k){await i.continue();return}if(!_.body){await i.fulfill({status:g,headers:b});return}let G=await _.arrayBuffer(),z=Buffer.from(G);await i.fulfill({status:g,headers:b,body:z})}catch{await i.continue()}}t(Son,"handleCorsRoute");async function dVt(i,n,s){try{let c=i.page(),u=Nh(c);if(s.has(u))return;s.add(u),await c.route(/^https?:\/\/(?!(?:localhost|127\.0\.0\.1|::1)).*/,_=>Son(_,n))}catch{}}t(dVt,"preventCrossOriginErrors");var kde=require("perf_hooks");async function _Vt(i,{shouldGoBack:n,shouldBatch:s,task:c,timestamp:u,beforeTimestamp:_,name:g,resolve:b,reject:w}){if(i.requireTimeMachineFrame().isDetached()&&w(),n){let G=kde.performance.now();await i.goBack(u,_),i.addTimeGoingBack(kde.performance.now()-G)}let k=pVt(i,{taskForSafeRun:c,name:g,resolve:b,reject:w}),O=i.taskQueue.getQueueLength()>0&&s?Ion(i,{firstTask:k,timestamp:u,name:g,resolve:b,reject:w}):[k];for(let G of O)await G()}t(_Vt,"runTaskWrapper");function pVt(i,{taskForSafeRun:n,name:s,resolve:c,reject:u}){return async()=>{try{let _=kde.performance.now(),g=await Zm(n(i.requireTimeMachineFrame()),i.options.taskTimeout,()=>`Task execution timeout - ${s}, took ${kde.performance.now()-_}ms with timeout of ${i.options.taskTimeout}ms`);c(g)}catch(_){tj.error("Task execution error:",_.message),u(_)}}}t(pVt,"makeSafeRunTask");function Ion(i,{firstTask:n,timestamp:s,name:c,resolve:u,reject:_}){let g=[n],b=i.taskQueue.getTasksAtTimestamp(s);return g.push(...b.map(({task:w})=>pVt(i,{taskForSafeRun:t(()=>w({shouldGoBack:!1,shouldBatch:!1}),"taskForSafeRun"),name:c,resolve:u,reject:_}))),i.taskQueue.removeTasksAtTimestamp(s),g}t(Ion,"collectBatchedTasks");var Ton="checksum is not defined";async function srt(i,n,{retriesLeft:s=3,retryWaitMS:c=1e3}={}){try{let{reducedHTML:u,currentChecksumId:_}=await n.evaluate(async({errorMessage:g,...b})=>{if(!window.checksum)throw new Error(g);return window.checksum.testGenerator.reduceHTML({},b)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:i.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0,errorMessage:Ton});return i.currentChecksumId=_,{reducedHTML:u}}catch(u){if(s>0)return await Dh(c),srt(i,n,{retriesLeft:s-1,retryWaitMS:c});throw u}}t(srt,"getReducedHTMLWithRetries");function mVt({frameMsgBroker:i,recordingFrame:n,timeMachineFrame:s,handler:c}){let u="rrweb";if(!n)throw new Error("Recording frame is not initialized");i.subscribeToChannel(u,s,{originFrame:n,handler:c}),s.page().on("close",()=>i.unsubscribeFromChannel(u,s))}t(mVt,"subscribeToRrwebEvents");var gke="checksum is not defined",ort=class ort{constructor(n,s,c={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0}){this.frameMsgBroker=n;this.injectedScriptManager=s;this.options=c;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.currentChecksumId="0";this.timeGoingBack=0;this.pagesWithCorsInterception=new Set;this.reducedHTMLCache={};this.taskQueue=new jue({sortByTimestamp:c.sortByTimestamp,logPerformance:c.logPerformance}),this.webProxyAgent=fVt(c.webProxy)}requireTimeMachineFrame(){if(!this.timeMachineFrame)throw new Error("Time machine frame is not initialized");return this.timeMachineFrame}addTimeGoingBack(n){this.timeGoingBack+=n,this.taskQueue.setTimeGoingBack(this.timeGoingBack)}getPage(){return this.requireTimeMachineFrame().page()}getFrame(){return this.requireTimeMachineFrame()}async prepare(n,s,c){this.recordingFrame=n,await this.frameMsgBroker.register("live",n),s?this.timeMachineFrame=s:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),await dVt(this.timeMachineFrame,this.webProxyAgent,this.pagesWithCorsInterception),this.options.frameMsgBrokerRegisterName&&await this.frameMsgBroker.register(this.options.frameMsgBrokerRegisterName,this.timeMachineFrame),c&&c(this.timeMachineFrame),await this.injectedScriptManager.addTrackedFrame(this.timeMachineFrame),this.timeMachineFrame.page().on("framenavigated",async u=>{await this.injectedScriptManager.onFrameNavigated(u)}),mVt({frameMsgBroker:this.frameMsgBroker,recordingFrame:this.recordingFrame,timeMachineFrame:this.requireTimeMachineFrame(),handler:this.rrwebEventHandler.bind(this)}),this.taskQueue=new jue({sortByTimestamp:this.options.sortByTimestamp,logPerformance:this.options.logPerformance}),await this.start()}async start(){await this.requireTimeMachineFrame().evaluate(async n=>{if(!window.checksum)throw new Error(n);window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})},gke)}setBrowserContext(n){this.timeMachineBrowserContext=n}async executeTask(n,s,{name:c,beforeTimestamp:u=!1,priority:_=!1}={}){return new Promise((g,b)=>{let w=t((k={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled??!1})=>_Vt(this,{...k,task:n,timestamp:s,beforeTimestamp:u,name:c,resolve:g,reject:b}),"taskWrapper");this.taskQueue.enqueue({name:c,task:w,timestamp:u&&s!==void 0?s-1:s,priority:_}),this.runTasks()})}executeReducedHTMLTask(n,{priority:s=!1}={}){if(this.reducedHTMLCache[n]){let c=new Que(this.reducedHTMLCache[n]);return Promise.resolve(c.getRrwebIdsReducedDomString())}return this.executeTask(async c=>{let _=(await srt(this,c)).reducedHTML;return _&&(this.reducedHTMLCache[n]=_),new Que(_).getRrwebIdsReducedDomString()},n,{name:"getReducedHTMLForTimestamp",priority:s})}goBack(n,s=!1){return this.currentBeforeTimestamp===s&&this.currentTimestamp===n?Promise.resolve():(this.currentTimestamp=n,this.currentBeforeTimestamp=s,this.requireTimeMachineFrame().evaluate(({timestamp:c,beforeTimestamp:u,errorMessage:_})=>{if(!window.checksum)throw new Error(_);return c===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(c,{beforeTimestamp:u})},{timestamp:n,beforeTimestamp:s,errorMessage:gke}))}async runTasks(){await this.taskQueue.runTasks(async n=>{await n.task()})}async rrwebEventHandler(n){let s=JSON.stringify(n);try{await this.requireTimeMachineFrame().evaluate(function({eventsJSON:c,errorMessage:u}){if(!window.checksum)throw new Error(u);let _=JSON.parse(c);return window.checksum.timeMachine.handleEvents(_)},{eventsJSON:s,errorMessage:gke})}catch{}return s}async makeBrowserContext(){let n=[];this.options.debugPort&&n.push(`--remote-debugging-port=${this.options.debugPort}`);let{headless:s}=this.options,c=await hVt.chromium.launch({...s!==void 0?{headless:s}:{},args:n});return this.timeMachineBrowserContext=await c.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){if(!this.timeMachineBrowserContext)throw new Error("Time machine browser context is not initialized");return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}async toggleTimeMachineHandleEvents(n){try{await this.requireTimeMachineFrame().evaluate(({shouldHandleEvents:s,errorMessage:c})=>{if(!window.checksum)throw new Error(c);return window.checksum.timeMachine.setShouldHandleEvents(s)},{shouldHandleEvents:n,errorMessage:gke})}catch{}}};t(ort,"ChecksumTimeMachine");var yke=ort;var art=require("@playwright/test"),crt=mc(require("fs")),gVt=mc(require("fs/promises")),yVt=mc(require("path")),AVt=mc(d$e());var xon=1e3,won=t(()=>{},"noopPostProcessRRwebEvents"),lrt=class lrt extends yke{constructor(s,c,u={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4,debugPort:void 0,frameMsgBrokerRegisterName:void 0,recordRRwebEventsToFile:!1,recordRRwebEventsToFilePath:"events.json"}){super(s,c,u);this.options=u;this.rrwebEventsBuffer="";this.rrwebTotalBytes=0;this.rrwebRecordingCapped=!1;this.postProcessRRwebEvents=(0,AVt.debounce)(won,100,{leading:!0,trailing:!0});let _=this.options.recordRRwebEventsToFilePath;if(this.options.recordRRwebEventsToFile&&_){let g=yVt.default.dirname(_);crt.default.mkdirSync(g,{recursive:!0}),crt.default.writeFileSync(_,"")}}setTimeMachineBrowserContext(s){this.timeMachineBrowserContext=s}getTimeMachineBrowserContext(){return this.timeMachineBrowserContext}async makeBrowserContext(){art.chromium._checksumInternal=!0;let s=await art.chromium.launch({...this.options.headless!==void 0?{headless:this.options.headless}:{},args:Vl.useRemoteDebugging.enabled?["--remote-debugging-port=4444"]:[]});return s._checksumInternal=!0,this.timeMachineBrowserContext=await s.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(){if(!this.timeMachineBrowserContext)throw new Error("Time machine browser context is not initialized");let s=await this.timeMachineBrowserContext.newPage();s._checksumInternal=!0;let c=s.mainFrame();return c._checksumInternal=!0,c}async rrwebEventHandler(s){if(this.rrwebRecordingCapped)return"";let c=await super.rrwebEventHandler(s),u=this.options.maxRRwebBytes??0;if(this.rrwebTotalBytes+=c.length,!this.rrwebRecordingCapped&&bMt(this.rrwebTotalBytes,u)&&(this.rrwebRecordingCapped=!0,console.warn(`[checksum] rrweb recording exceeded ${u} bytes \u2014 truncating the recording to protect worker memory (set CHECKSUM_RUNTIME_RRWEB_MAX_BYTES to retune, 0 to disable)`)),!this.options.recordRRwebEventsToFile)return c;if(this.rrwebEventsBuffer+=c+`
616
616
  `,this.rrwebEventsBuffer.length>xon||this.rrwebRecordingCapped){let _=this.rrwebEventsBuffer;this.rrwebEventsBuffer="",this.flushRRwebEventsToFile(_)}return c}async flushRRwebEventsToFile(s){let c=this.options.recordRRwebEventsToFilePath;if(!this.options.recordRRwebEventsToFile||!c)return;let u=s??this.rrwebEventsBuffer;try{await gVt.default.appendFile(c,u)}catch(_){tf(_)}}getRRwebFilePath(){return this.options.recordRRwebEventsToFilePath}};t(lrt,"RuntimeTimeMachine");var Ake=lrt;var SVt=mc(require("path"));var vVt=!1,frt=class frt{constructor(n,s,c){this.frame=n;this.base=s;this.getAnalytics=c;this.LOCATORS_TIMEOUT=vVt?9999999:5e3;this.HANDLES_TIMEOUT=vVt?9999999:5e3;this.HANDLES_INTERVAL=300;this.locatorsChain=[];this.base??(this.base=this.frame)}setBase(n){this.base=n}setAnalytics(n){this.getAnalytics=n}init(...n){return this.sanitizeArgs(...n),new Proxy(this,{get:t((s,c)=>c==="setBase"?function(...u){this.setBase(u[0])}.bind(this):c==="setAnalytics"?function(...u){this.setAnalytics(u[0])}.bind(this):this.handleLocatorChain(s,c),"get")})}getLocatorSelector(n){if(n)return n._selector}sanitizeArgs(...n){if(n.length===1&&typeof n[0]=="object"){if(!n[0].anchors||typeof n[0].anchors!="function")throw new Error("Invalid compound selector format. Object must contain anchors property with a method value");this.anchorLocatorMethod=n[0].anchors,this.targetLocatorMethod=n[0].target;return}if(typeof n[0]!="function")throw new Error("Invalid compound selector format. First argument must be an object or a function");if(this.anchorLocatorMethod=n[0],n.length===2){if(typeof n[1]!="function")throw new Error("Invalid compound selector format. Second argument must be a function");this.targetLocatorMethod=n[1]}}async resolveLocator(){if(this.resolvedLocator)return this.resolvedLocator;tf("Waiting for locators..");let n=this.getLocatorsFromMethods();if(n.find(w=>!("_selector"in w)))throw new Error("Can't resolve at least one locator, make sure anchors and target are valid locators or strings");try{await Promise.all(n.map(async w=>Zm(w.first().waitFor({bypassChecksum:!0}),this.LOCATORS_TIMEOUT,"Waiting for compound selector locators timeout")))}catch(w){throw new Error(`Error while waiting for locators - ${w.message}`)}let s=await Zm(this.getElementHandles(n),this.HANDLES_TIMEOUT);tf(`Resolved to ${urt(s)} elements from ${n.length} locators`);let c=this.getLocatorSelector(this.getLocatorsFromMethods(!1,!0,this.frame)[0]),u=await this.frame.evaluate(async({handles:w,targetSelector:k})=>{var O;return(O=window.checksum)==null?void 0:O.testGenerator.getCompoundSelector().select(w,k??"")},{handles:s,targetSelector:c}),_=u==null?void 0:u[0];if(!u||u.length===0||_===void 0)throw new Error("Could not generate selectors from handles");tf(`Resolved compound selector to ${u.length} selectors`);let g=this.getBase(),b=g.locator(_);return u.slice(1,50).forEach(w=>{b=b.or(g.locator(w))}),this.locatorsChain.length&&this.locatorsChain.forEach(({name:w,args:k})=>{b=Reflect.get(b,w).apply(b,k)}),tf(`Compound locator selector: ${this.getLocatorSelector(b)}`),this.resolvedLocator=b,b}handleLocatorChain(n,s){if(typeof s=="symbol")return;if(s==="constructor")return t(function(...g){return this[s](...g)},"Locator");if(s==="toString")return()=>this.toString();let c=t(()=>new Proxy(n,{get:t((_,g)=>_.handleLocatorChain(_,g),"get")}),"createLocatorProxy");return s==="valueOf"?t(function(){return c()},"Locator"):s==="then"?(_,g)=>{this.resolveLocator().then(b=>_(b)).catch(g)}:Object.values([...Object.values(AL),...Object.values(WG)]).includes(s)?t(function(...g){return n.locatorsChain.push({name:s,args:g}),c()},"Locator"):t(async function(...g){return this.handleAction(s,g)},"Locator").bind(this)}async handleAction(n,s){var c,u;try{if(typeof n=="symbol")return;if(!this.anchorLocatorMethod)throw new Error("Compound selection is missing anchor locators");let _=await this.resolveLocator(),g;return this.frame.executeLocatorAction?g=await this.frame.executeLocatorAction(_,n,s):g=await Reflect.get(_??{},n)(...s),g}catch(_){throw tf(`Failed to execute compound selection action: ${_}`),(u=(c=this.getAnalytics)==null?void 0:c.call(this))==null||u.compoundSelectionFailure({error:_.toString(),selector:this.toString()}),_}}async getElementHandles(n){tf("Resolving compound selector elements");let s,c,u,_,g=0,b=t(()=>{g=2},"resetSameHandlesCount");do{s=c;let w=[];c=w,await Promise.all(n.map(async k=>{let O=await k.elementHandles({bypassChecksum:!0});if(O.length===0)throw new Error(`No elements found for locator: ${this.getLocatorSelector(k)}`);w.push(O)})),u=urt(w),_=s?urt(s):0,tf(`Handles itteration, previous: ${s?_:"-"}, current: ${u}`),_!==u&&b(),await Dh(this.HANDLES_INTERVAL)}while(!s||_!==u||--g>0);return c??[]}getLocatorsFromMethods(n=!0,s=!0,c=this.getBase()){return(n&&this.anchorLocatorMethod?this.anchorLocatorMethod(c):[]).concat(s&&this.targetLocatorMethod?[this.targetLocatorMethod(c)]:[]).map(u=>typeof u=="string"?c.getByText(u):u)}getBase(){return this.base}toString(){var n,s;return`CompoundSelection(${this.resolvedLocator?this.getLocatorSelector(this.resolvedLocator):`${(n=this.anchorLocatorMethod)==null?void 0:n.toString()}, ${(s=this.targetLocatorMethod)==null?void 0:s.toString()})`})`}};t(frt,"CompoundSelectorLocator");var OK=frt,urt=t(i=>i.reduce((n,s)=>n+s.length,0),"countHandleElements");var drt=require("path");var bVt=require("fs");var kon=!0,_rt=class _rt{constructor(n){this.options=n;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=t(async n=>{let s=Nh(n);if(this.trackedFramesGuid.includes(s))return this.frameNavigationPromises[s]=this.loadScript(n),this.frameNavigationPromises[s]},"onFrameNavigated");this.loadScript=t(async(n,{retriesLeft:s=3,retryWaitMS:c=2e3,useWrapper:u=!0}={})=>{if(u&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(n,{retriesLeft:s,retryWaitMS:c,useWrapper:!1}),n);if(await this.shouldSkipScriptLoad(n)||(await this.waitBefore(this.options.scriptAddWait,"adding script"),!await this.tryAddScriptTag(n,s,c,u)))return;let g=Nh(n),b=Date.now().toString(36)+Math.random().toString(36).slice(2);return this.navigatingFrames[g]=b,this.finalizeScriptLoad(n,g,b)},"loadScript");this.log=new Proxy(console,{get:t((n,s)=>(...c)=>{if(this.options.silenceLogs)return;let u=Don(n,s)?n[s]:void 0;if(typeof u=="function")return u.apply(n,c)},"get")});this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(n){return this.scriptLoadCallback=n,this}setScriptLoadCheck(n){return this.scriptLoadCheck=n,this}setScriptLoadWrapper(n){return this.scriptLoadWrapper=n,this}async addTrackedFrame(n,s=!0){let c="mainFrame"in n?n.mainFrame():n,u=Nh(c);if(this.trackedFramesGuid.includes(u)||this.trackedFramesGuid.push(u),s)return this.onFrameNavigated(c)}getNavigationPromise(n){if(!n){this.log.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let s=typeof n=="string"?n:"mainFrame"in n?Nh(n.mainFrame()):Nh(n);return this.frameNavigationPromises[s]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,drt.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}async makeInjectedScriptOptionsForAddScriptTag(){var n;if(this.options.scriptSource==="url"&&((n=this.addScriptTagOptions)!=null&&n.url)&&kon){let c=await(await fetch(this.addScriptTagOptions.url)).text(),u=(0,drt.join)(process.cwd(),"checksumlib.js");return(0,bVt.writeFileSync)(u,c),{path:u}}return this.addScriptTagOptions}isFrameClosed(n){return n.isDetached()||n.page().isClosed()}async waitBefore(n,s){n&&(this.log.log(`Waiting ${n}[ms] before ${s}...`),await Dh(n),this.log.log(`Done waiting before ${s}`))}async isAlreadyLoaded(n){try{return this.scriptLoadCheck?await this.scriptLoadCheck(n):!1}catch{return!1}}async tryAddScriptTag(n,s,c,u){try{return await n.addScriptTag(await this.makeInjectedScriptOptionsForAddScriptTag()),!0}catch(_){if(s<=0)throw _;return this.log.warn(`[InjectedScriptManager] Failed to add script to frame ${Nh(n)}, trying again in ${c/1e3} seconds, ${s-1} retries left.`,_.message),await Dh(c),await this.loadScript(n,{retriesLeft:s-1,retryWaitMS:c,useWrapper:u}),!1}}async shouldSkipScriptLoad(n){return this.addScriptTagOptions?this.isFrameClosed(n)||await this.isAlreadyLoaded(n)?!0:this.isFrameClosed(n):(this.log.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript"),!0)}async finalizeScriptLoad(n,s,c){var u;if(await this.waitBefore(this.options.scriptInitWait,"onScriptLoad"),!this.isFrameClosed(n)){if(this.navigatingFrames[s]&&this.navigatingFrames[s]!==c)return this.log.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[s];try{await((u=this.scriptLoadCallback)==null?void 0:u.call(this,n))}catch(_){this.log.error("[WebDriver] onScriptLoad error",_)}}}};t(_rt,"InjectedScriptManager");var vke=_rt;function Don(i,n){return typeof n=="string"&&n in i}t(Don,"isConsoleKey");var Non=t(()=>{let n=(new Error().stack??"").split(`
617
617
  `).find(c=>c.includes(".checksum.spec.ts"));if(!n)return;let s=n.split(":");return{lineNumber:parseInt(s[1]??""),columnNumber:parseInt(s[2]??"")}},"findCodeLocationFromStackTrace"),prt=class prt{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let n in this.store)Object.prototype.hasOwnProperty.call(this.store,n)&&delete this.store[n];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(n=>this.store[n]).filter(n=>n!==void 0)}setVariable(n,s){this.store[n]={name:n,value:s,type:s instanceof Function?"RandomValueGenerator":"FillValue"}}set(n,s,c){if(typeof s!="string")return!1;let u=Non();return n.store[s]={name:s,value:c,type:c instanceof Function?"RandomValueGenerator":"FillValue",...u,line:""},!0}get(n,s){var c;if(s in n)return Reflect.get(n,s);if(!(s in n.store))throw new Error(`Variable ${s} is not defined`);return n.activeVariablesSet.add(s),(c=n.store[s])==null?void 0:c.value}};t(prt,"VariableStore");var MK=prt;var yrt=class yrt{constructor(n){this.options=n}async handleError(n,s,c){let u=`Error in ${s} action during ${n} execution: ${c.message}`;throw new Error(u)}async guardedExecute(){try{return await(this.options.timeout!=null?Zm(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(n){return this.handleError(this.options.method,this.constructor.name,n)}}};t(yrt,"Action");var bke=yrt;function Pon(i,n){return i in n}t(Pon,"isLocatorMethod");var Art=class Art extends bke{async execute(){let{locator:n,method:s,args:c}=this.options;if(Pon(s,n)){let u=n[s];return typeof u=="function"?Reflect.apply(u,n,c):u}return n}};t(Art,"PlaywrightAction");var mrt=Art,vrt=class vrt extends bke{constructor(s,c){super(s);this.pageInteractor=c}};t(vrt,"APIAction");var hrt=vrt,brt=class brt extends hrt{constructor(n,s){super(n,s.pageInteractor)}async execute(){try{let{locator:n,args:s}=this.options,[c,u]=s,_=await n.screenshot({timeout:3e4}),b=(await this.pageInteractor.getTextDetection(_)).getRectangleByTextAndSizeRanking(c,u);if(!b)throw new Error("No matching text found");await n.click({position:b.center})}catch(n){throw new Error(`Error in canvas click action: ${n.message}`)}}};t(brt,"CanvasClickAction");var grt=brt,Cke=class Cke{static isCustomAction(n){return n in this.customActionMap}static createAction(n,s){return this.isCustomAction(n.method)?new this.customActionMap[n.method]({...n,timeout:15e3},s):new mrt(n)}};t(Cke,"ActionFactory"),Cke.customActionMap={canvasClick:grt};var Eke=Cke;function LK(i,n){return Reflect.get(i,n)}t(LK,"readDynamicProperty");function EVt(i,n,s){let c=LK(i,n);if(typeof c!="function")throw new Error(`Method ${n} is not a function`);return c.apply(i,s)}t(EVt,"callDynamicMethod");function CVt(i){if(typeof i=="object"&&i!==null&&"timeout"in i&&typeof i.timeout=="number")return i.timeout}t(CVt,"extractTimeout");var Ike=class Ike{constructor(n,s,c,u,_,g,b){this.frame=n;this.checksumPage=s;this.isReplMode=c;this.config=u;this.injectedScriptManager=_;this.getPageInteractor=g;this.onExecutionError=b;this.locatorStack=[];this.proxy=this.createFrameProxy(),this.checksumClient=new vY({apiURL:this.config.apiURL,apiKey:this.config.apiKey})}static init(n,s,c,u,_,g,b=!1){return new Ike(n,s,b,g,c,u,_).proxy}createFrameProxy(){return new Proxy(this,{get:t(function(s,c){return s.handleFrameMethod(c)},"get")})}handleFrameMethod(n){if(typeof n=="symbol")return;let s=LK(this,n);return typeof s=="function"?n==="constructor"?s:s.bind(this):[...Object.values(AL),...Object.values(WG)].includes(n)?(this.pushToLocatorStack([{type:n,base:this.frame}]),t(function(u,_){try{return this.executeLocator(u,_)}catch(g){throw this.popLocatorChain(),g}},"Locator").bind(this)):LK(this.frame,n)}page(){return this.checksumPage}compoundSelection(...n){var s;try{let c=this.locatorStack.length?(s=this.getCurrentLocatorInChain())==null?void 0:s.base:this.proxy;return new OK(this.proxy,c).init(...n)}catch{throw new Error("Failed generating compound selector")}}async wrapInternalSteps(n,s=this.frame){try{return s._checksumInternal=!0,await n()}finally{s._checksumInternal=!1}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.frame)}pushToLocatorStack(n){this.locatorStack.push(n)}getCurrentLocatorChain(){let n=this.locatorStack[this.locatorStack.length-1];if(!n){let s=[];return this.locatorStack.push(s),s}return n}popLocatorChain(){return this.locatorStack.pop()}getCurrentLocatorInChain(){let n=this.getCurrentLocatorChain();return n==null?void 0:n[n.length-1]}getLocator(n,s){let c=this.getCurrentLocatorInChain();if(!c)throw new Error("No locator in current chain");return EVt(c.base,c.type,[n,s])}executeLocator(n,s){var c;try{tf(`
618
618
  Executing locator ${(c=this.getCurrentLocatorInChain())==null?void 0:c.type} with ${typeof n=="string"?`selector ${n}`:"locator"}`);try{n&&typeof n=="object"&&"has"in n&&this.popLocatorChain()}catch{}let u=this.getLocator(n,s);return new Proxy(u,{get:t((_,g)=>this.getLocatorMethod(u,_,g),"get")})}catch(u){tf("Failed to locate",u);return}}getLocatorMethod(n,s,c){return c==="then"?this.handleThen(n,s,c):c==="catch"?this.handleCatch(n):c==="finally"?this.handleFinally(n):c==="constructor"?t(function(..._){return this.popLocatorChain(),s.constructor(..._)},"Locator"):c in s&&typeof LK(s,c)!="function"||c===Symbol.toPrimitive||c in Object||c==="evaluate"?(this.popLocatorChain(),LK(s,c)):c==="compoundSelection"?function(...u){let _=this.compoundSelection(...u);return _.setBase(n),_}.bind(this):[...Object.values(AL),...Object.values(WG)].includes(c)?["or","and"].includes(c)?(tf("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),LK(s,c)):(this.getCurrentLocatorChain().push({type:c,base:n}),t(function(..._){return this.executeLocator(_[0],_[1])},"Locator").bind(this)):c==="page"?()=>(this.popLocatorChain(),this.proxy.page()):t(async function(..._){let g=await this.executeLocatorAction(n,c,_);return this.popLocatorChain(),g},"Locator").bind(this)}async executeLocatorAction(n,s,c){var w;if(c&&Array.from(c).some(k=>(k==null?void 0:k.bypassChecksum)===!0))return EVt(n,s,c);let u=n._selector;tf("Executing",s,u);let _=s==="_expect"?"assertion":"action",g=((w=this.config.options)==null?void 0:w.consecutiveActionDelay)??100;g>0&&_==="action"&&this.lastLocatorActionType==="action"&&(tf("Adding minimal wait between consecutive actions..."),await new Promise(k=>setTimeout(k,g))),this.lastLocatorActionType=_,tf("Running initial locator...");let b;try{this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{tf("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{tf("[executeLocatorAction] checksum libs not loaded")}});let k=this.getLocatorActionTimeout(_,s,c);return await Eke.createAction({locator:n,method:s,args:c,...k!==void 0?{timeout:k}:{}},{api:this.checksumClient,pageInteractor:this.getPageInteractor()}).guardedExecute()}catch(k){tf("Failed initial execution. Exception:",k.message),b=k}if(_==="action"&&this.onExecutionError)return this.onExecutionError({error:b,locator:n,method:s,args:c},this.frame);throw b}setExpectConfiguration(n=void 0){this.expectConfiguration=n}getLocatorActionTimeout(n,s,c=[]){if(!this.isReplMode)try{if(n==="assertion"){let g=this.getAssertionTimeout(c);return tf(`Assertion timeout set to ${g}`),g}let u=["fill","dragTo"].includes(s)?1:0,_=CVt(c[u]);return _!==void 0&&!isNaN(_)?_:3e4}catch{return 3e4}}getAssertionTimeout(n=[]){var u,_,g,b;let s=CVt(n[1]);if(s!==void 0)return s;if(((u=this.expectConfiguration)==null?void 0:u.timeout)!==void 0)return(_=this.expectConfiguration)==null?void 0:_.timeout;let c=(b=(g=this.testInfo._projectInternal)==null?void 0:g.expect)==null?void 0:b.timeout;return c!==void 0?c:3e4}handleThen(n,s,c){return(u,_)=>Promise.resolve(n).then(g=>{let b=u?u(g):g;return b instanceof Promise?b:this.getLocatorMethod(b,s,c)},g=>{if(_)return _(g);throw g})}handleCatch(n){return s=>Promise.resolve(n).catch(c=>{if(s)return s(c);throw c})}handleFinally(n){return s=>Promise.resolve(n).finally(s)}};t(Ike,"ChecksumFrame");var Ske=Ike;function Ert(i,n){return Reflect.get(i,n)}t(Ert,"readDynamicProperty");function Bon(i,n,s){let c=Ert(i,n);if(typeof c!="function")throw new Error(`Method ${n} is not a function`);return c.apply(i,s)}t(Bon,"callDynamicMethod");var xke=class xke{constructor(n,s,c,u,_,g){this.page=n;this.config=c;this.getPageInteractor=u;this.injectedScriptManager=_;this._frames={};this.variableStore=new MK;this._isChecksumPage=!0;var b,w;if(this._context=s,this.proxy=this.createPageProxy(),!this.injectedScriptManager){let k=Vl.checksumScript.url,O=(b=c==null?void 0:c.options)==null?void 0:b.browserScriptInitWait,G=(w=c==null?void 0:c.options)==null?void 0:w.browserScriptAddWait;this.injectedScriptManager=new vke({scriptFile:Vl.checksumScript.path,scriptSource:Vl.checksumScript.source,...k!==void 0?{scriptURL:k}:{},isScriptFileAbsolute:!0,silenceLogs:!Vl.isDevMode,...O!==void 0?{scriptInitWait:O}:{},...G!==void 0?{scriptAddWait:G}:{}})}this.registerPageEvents(),this.page.frames().forEach(k=>{this.registerFrame(k)}),g!=null&&g.variableStore&&(this.variableStore=g.variableStore)}static makePage(n,s,c,u){let _=wke();return new xke(n,u,_,()=>s,c,void 0).proxy}async registerFrame(n){let s=this.getFrameGuid(n);if(n===this.page.mainFrame()&&(this.mainFrameGuid=s),this._frames[s])return;if(!this.injectedScriptManager)throw new Error("Injected script manager not initialized");let c=Ske.init(n,this.proxy,this.injectedScriptManager,this.getPageInteractor,this.onExecutionError.bind(this),this.config);this._frames[s]=c}async onExecutionError(n){throw n.error}getFrameGuid(n){return n._guid}getPageGuid(n){return n._guid}registerPageEvents(){this.page.on("frameattached",n=>{this.registerFrame(n)})}createPageProxy(){return new Proxy(this,{get:t(function(s,c){return s.getPageMethod(c)},"get")})}getPageMethod(n){let s=Ert(this,n);if(typeof s=="function")return n==="constructor"?s:s.bind(this);switch(n){case"pageInteractor":return this.getPageInteractor();case"variableStore":return this.variableStore;case"_isChecksumPage":return this._isChecksumPage}return Object.values(AL).includes(n)?t(function(u,_){return Bon(this.mainFrame(),n,[u,_])},"Page").bind(this):Ert(this.page,n)}mainFrame(){let n=this.mainFrameGuid!==void 0?this._frames[this.mainFrameGuid]:void 0;if(!n)throw new Error("Main frame not found");return n}frames(){return Object.values(this._frames)}context(){return this._context}getPage(n){return this._context.getPage(n)}getFrame(n){if(!this.page.frames().find(u=>this.getFrameGuid(u)===n))throw new Error(`Frame with guid ${n} not found`);let c=this._frames[n];if(!c)throw new Error(`Frame with guid ${n} not found`);return c}async waitForDialog(n){try{return this.getPageInteractor().waitForDialog(!0,n)}catch(s){throw new Error(`Failed to handle native dialog: ${s}`)}}async reauthenticate(n){try{await this.getPageInteractor().reauthenticate(n,this.proxy)}catch(s){throw new Error(`Failed to reauthenticate: ${s}`)}}resolveAssetsFolder(n){return n.map(s=>SVt.join(vle(Ux()),s))}compoundSelection(...n){try{return new OK(this.mainFrame()).init(...n)}catch{throw new Error("Failed generating compound selector")}}get navigationPromise(){var n;return(n=this.injectedScriptManager)==null?void 0:n.getNavigationPromise(this.page)}setExpectConfiguration(n=void 0){this.expectConfiguration=n,Object.values(this._frames).forEach(s=>s.setExpectConfiguration(n))}};t(xke,"ChecksumPage");var Tke=xke;var IVt=Object.defineProperty,Dp=t((i,n)=>{let s={};for(var c in i)IVt(s,c,{get:i[c],enumerable:!0});return n||IVt(s,Symbol.toStringTag,{value:"Module"}),s},"__exportAll");function rJ(i){return!!(i&&typeof i=="object"&&"type"in i&&i.type==="tool_call")}t(rJ,"_isToolCall");function TVt(i){return!!(i&&typeof i=="object"&&"toolCall"in i&&i.toolCall!=null&&typeof i.toolCall=="object"&&"id"in i.toolCall&&typeof i.toolCall.id=="string")}t(TVt,"_configHasToolCallId");var QK,Dde=(QK=class extends Error{output;constructor(n,s){super(n),this.output=s}},t(QK,"ToolInputParsingException"),QK);var Fon=/([A-Z]+)([A-Z][a-z0-9]+)/g,Ron=/([a-z0-9])([A-Z])/g,Oon=/[-_\s]+/g;function Mon(i){return i.replace(Fon,"$1_$2").replace(Ron,"$1_$2").replace(Oon,"_").toLowerCase()}t(Mon,"snakeCase");function xVt(i,n){return(n==null?void 0:n[i])||Mon(i)}t(xVt,"keyToJson");function wVt(i,n,s){let c={};for(let u in i)Object.hasOwn(i,u)&&(c[n(u,s)]=i[u]);return c}t(wVt,"mapKeys");var Lon="__lc_escaped__";function Qon(i){return"lc"in i||Object.keys(i).length===1&&"__lc_escaped__"in i}t(Qon,"needsEscaping");function Uon(i){return{[Lon]:i}}t(Uon,"escapeObject");function jon(i){return i!==null&&typeof i=="object"&&"lc_serializable"in i&&typeof i.toJSON=="function"}t(jon,"isSerializableLike");function Jon(i){var s;let n;return i!==null&&typeof i=="object"?"lc_id"in i&&Array.isArray(i.lc_id)?n=i.lc_id:n=[((s=i.constructor)==null?void 0:s.name)??"Object"]:n=[typeof i],{lc:1,type:"not_implemented",id:n}}t(Jon,"createNotImplemented");function kke(i,n=new WeakSet){if(i!==null&&typeof i=="object"&&!Array.isArray(i)){if(n.has(i))return Jon(i);if(jon(i))return i;n.add(i);let s=i;if(Qon(s))return n.delete(i),Uon(s);let c={};for(let[u,_]of Object.entries(s))c[u]=kke(_,n);return n.delete(i),c}return Array.isArray(i)?i.map(s=>kke(s,n)):i}t(kke,"escapeIfNeeded");function kVt(i){return Array.isArray(i)?[...i]:{...i}}t(kVt,"shallowCopy");function $on(i,n){let s=kVt(i);for(let[c,u]of Object.entries(n)){let[_,...g]=c.split(".").reverse(),b=s;for(let w of g.reverse()){if(b[w]===void 0)break;b[w]=kVt(b[w]),b=b[w]}b[_]!==void 0&&(b[_]={lc:1,type:"secret",id:[u]})}return s}t($on,"replaceSecrets");function Crt(i){let n=Object.getPrototypeOf(i);return typeof i.lc_name=="function"&&(typeof n.lc_name!="function"||i.lc_name()!==n.lc_name())?i.lc_name():i.name}t(Crt,"get_lc_unique_name");var nJ,R8=(nJ=class{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Crt(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(n,...s){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(n||{}).filter(([c])=>{var u;return(u=this.lc_serializable_keys)==null?void 0:u.includes(c)})):this.lc_kwargs=n??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof nJ||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let n={},s={},c=Object.keys(this.lc_kwargs).reduce((b,w)=>(b[w]=w in this?this[w]:this.lc_kwargs[w],b),{});for(let b=Object.getPrototypeOf(this);b;b=Object.getPrototypeOf(b))Object.assign(n,Reflect.get(b,"lc_aliases",this)),Object.assign(s,Reflect.get(b,"lc_secrets",this)),Object.assign(c,Reflect.get(b,"lc_attributes",this));Object.keys(s).forEach(b=>{let w=this,k=c,[O,...G]=b.split(".").reverse();for(let z of G.reverse()){if(!(z in w)||w[z]===void 0)return;(!(z in k)||k[z]===void 0)&&(typeof w[z]=="object"&&w[z]!=null?k[z]={}:Array.isArray(w[z])&&(k[z]=[])),w=w[z],k=k[z]}O in w&&w[O]!==void 0&&(k[O]=k[O]||w[O])});let u={},_=new WeakSet;_.add(this);for(let[b,w]of Object.entries(c))u[b]=kke(w,_);let g=wVt(Object.keys(s).length?$on(u,s):u,xVt,n);return{lc:1,type:"constructor",id:this.lc_id,kwargs:g}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}},t(nJ,"Serializable"),nJ);function UK(i){return typeof i=="object"&&i!==null&&"type"in i&&typeof i.type=="string"&&"source_type"in i&&(i.source_type==="url"||i.source_type==="base64"||i.source_type==="text"||i.source_type==="id")}t(UK,"isDataContentBlock");function DVt(i){return UK(i)&&i.source_type==="url"&&"url"in i&&typeof i.url=="string"}t(DVt,"isURLContentBlock");function NVt(i){return UK(i)&&i.source_type==="base64"&&"data"in i&&typeof i.data=="string"}t(NVt,"isBase64ContentBlock");function PVt(i){return UK(i)&&i.source_type==="id"&&"id"in i&&typeof i.id=="string"}t(PVt,"isIDContentBlock");function Srt({dataUrl:i,asTypedArray:n=!1}){let s=i.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),c;if(s){c=s[1].toLowerCase();let u=n?Uint8Array.from(atob(s[2]),_=>_.charCodeAt(0)):s[2];return{mime_type:c,data:u}}}t(Srt,"parseBase64DataUrl");function ca(i,n){return lc(i)&&i.type===n}t(ca,"_isContentBlock");function lc(i){return typeof i=="object"&&i!==null}t(lc,"_isObject");function mA(i){return Array.isArray(i)}t(mA,"_isArray");function ms(i){return typeof i=="string"}t(ms,"_isString");function FI(i){return typeof i=="number"}t(FI,"_isNumber");function Dke(i){return i instanceof Uint8Array}t(Dke,"_isBytesArray");function Irt(i){try{return JSON.parse(i)}catch{return}}t(Irt,"safeParseJson");var RI=t(i=>i(),"iife");function zon(i){if(i.type==="char_location"&&ms(i.document_title)&&FI(i.start_char_index)&&FI(i.end_char_index)&&ms(i.cited_text)){let{document_title:n,start_char_index:s,end_char_index:c,cited_text:u,..._}=i;return{..._,type:"citation",source:"char",title:n??void 0,startIndex:s,endIndex:c,citedText:u}}if(i.type==="page_location"&&ms(i.document_title)&&FI(i.start_page_number)&&FI(i.end_page_number)&&ms(i.cited_text)){let{document_title:n,start_page_number:s,end_page_number:c,cited_text:u,..._}=i;return{..._,type:"citation",source:"page",title:n??void 0,startIndex:s,endIndex:c,citedText:u}}if(i.type==="content_block_location"&&ms(i.document_title)&&FI(i.start_block_index)&&FI(i.end_block_index)&&ms(i.cited_text)){let{document_title:n,start_block_index:s,end_block_index:c,cited_text:u,..._}=i;return{..._,type:"citation",source:"block",title:n??void 0,startIndex:s,endIndex:c,citedText:u}}if(i.type==="web_search_result_location"&&ms(i.url)&&ms(i.title)&&ms(i.encrypted_index)&&ms(i.cited_text)){let{url:n,title:s,encrypted_index:c,cited_text:u,..._}=i;return{..._,type:"citation",source:"url",url:n,title:s,startIndex:Number(c),endIndex:Number(c),citedText:u}}if(i.type==="search_result_location"&&ms(i.source)&&ms(i.title)&&FI(i.start_block_index)&&FI(i.end_block_index)&&ms(i.cited_text)){let{source:n,title:s,start_block_index:c,end_block_index:u,cited_text:_,...g}=i;return{...g,type:"citation",source:"search",url:n,title:s??void 0,startIndex:c,endIndex:u,citedText:_}}}t(zon,"convertAnthropicAnnotation");function FVt(i){if(ca(i,"document")&&lc(i.source)&&"type"in i.source){if(i.source.type==="base64"&&ms(i.source.media_type)&&ms(i.source.data))return{type:"file",mimeType:i.source.media_type,data:i.source.data};if(i.source.type==="url"&&ms(i.source.url))return{type:"file",url:i.source.url};if(i.source.type==="file"&&ms(i.source.file_id))return{type:"file",fileId:i.source.file_id};if(i.source.type==="text"&&ms(i.source.data))return{type:"file",mimeType:String(i.source.media_type??"text/plain"),data:i.source.data}}else if(ca(i,"image")&&lc(i.source)&&"type"in i.source){if(i.source.type==="base64"&&ms(i.source.media_type)&&ms(i.source.data))return{type:"image",mimeType:i.source.media_type,data:i.source.data};if(i.source.type==="url"&&ms(i.source.url))return{type:"image",url:i.source.url};if(i.source.type==="file"&&ms(i.source.file_id))return{type:"image",fileId:i.source.file_id}}}t(FVt,"convertToV1FromAnthropicContentBlock");function RVt(i){function*n(){for(let s of i){let c=FVt(s);c?yield c:yield s}}return t(n,"iterateContent"),Array.from(n())}t(RVt,"convertToV1FromAnthropicInput");function BVt(i){function*n(){var c;let s=typeof i.content=="string"?[{type:"text",text:i.content}]:i.content;for(let u of s){if(ca(u,"text")&&ms(u.text)){let{text:_,citations:g,...b}=u;if(mA(g)&&g.length){let w=g.reduce((k,O)=>{let G=zon(O);return G?[...k,G]:k},[]);yield{...b,type:"text",text:_,annotations:w};continue}else{yield{...b,type:"text",text:_};continue}}else if(ca(u,"thinking")&&ms(u.thinking)){let{thinking:_,signature:g,...b}=u;yield{...b,type:"reasoning",reasoning:_,signature:g};continue}else if(ca(u,"redacted_thinking")){yield{type:"non_standard",value:u};continue}else if(ca(u,"tool_use")&&ms(u.name)&&ms(u.id)){yield{type:"tool_call",id:u.id,name:u.name,args:u.input};continue}else if(ca(u,"input_json_delta")){if(Won(i)&&((c=i.tool_call_chunks)!=null&&c.length)){let _=i.tool_call_chunks[0];yield{type:"tool_call_chunk",id:_.id,name:_.name,args:_.args,index:_.index};continue}}else if(ca(u,"server_tool_use")&&ms(u.name)&&ms(u.id)){let{name:_,id:g}=u;if(_==="web_search"){yield{id:g,type:"server_tool_call",name:"web_search",args:{query:RI(()=>{if(typeof u.input=="string")return u.input;if(lc(u.input)&&ms(u.input.query))return u.input.query;if(ms(u.partial_json)){let b=Irt(u.partial_json);if(b!=null&&b.query)return b.query}return""})}};continue}else if(u.name==="code_execution"){yield{id:g,type:"server_tool_call",name:"code_execution",args:{code:RI(()=>{if(typeof u.input=="string")return u.input;if(lc(u.input)&&ms(u.input.code))return u.input.code;if(ms(u.partial_json)){let b=Irt(u.partial_json);if(b!=null&&b.code)return b.code}return""})}};continue}}else if(ca(u,"web_search_tool_result")&&ms(u.tool_use_id)&&mA(u.content)){let{content:_,tool_use_id:g}=u;yield{type:"server_tool_call_result",name:"web_search",toolCallId:g,status:"success",output:{urls:_.reduce((b,w)=>ca(w,"web_search_result")?[...b,w.url]:b,[])}};continue}else if(ca(u,"code_execution_tool_result")&&ms(u.tool_use_id)&&lc(u.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:u.tool_use_id,status:"success",output:u.content};continue}else if(ca(u,"mcp_tool_use")){yield{id:u.id,type:"server_tool_call",name:"mcp_tool_use",args:u.input};continue}else if(ca(u,"mcp_tool_result")&&ms(u.tool_use_id)&&lc(u.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:u.tool_use_id,status:"success",output:u.content};continue}else if(ca(u,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:u.input};continue}else if(ca(u,"search_result")){yield{id:u.id,type:"non_standard",value:u};continue}else if(ca(u,"tool_result")){yield{id:u.id,type:"non_standard",value:u};continue}else{let _=FVt(u);if(_){yield _;continue}}yield{type:"non_standard",value:u}}}return t(n,"iterateContent"),Array.from(n())}t(BVt,"convertToV1FromAnthropicMessage");var OVt={translateContent:BVt,translateContentChunk:BVt};function Won(i){return typeof(i==null?void 0:i._getType)=="function"&&typeof i.concat=="function"&&i._getType()==="ai"}t(Won,"_isAIMessageChunk");function Hon(i){return DVt(i)?{type:i.type,mimeType:i.mime_type,url:i.url,metadata:i.metadata}:NVt(i)?{type:i.type,mimeType:i.mime_type??"application/octet-stream",data:i.data,metadata:i.metadata}:PVt(i)?{type:i.type,mimeType:i.mime_type,fileId:i.id,metadata:i.metadata}:i}t(Hon,"convertToV1FromDataContentBlock");function MVt(i){return i.map(Hon)}t(MVt,"convertToV1FromDataContent");function LVt(i){return!!(ca(i,"image_url")&&lc(i.image_url)||ca(i,"input_audio")&&lc(i.input_audio)||ca(i,"file")&&lc(i.file))}t(LVt,"isOpenAIDataBlock");function QVt(i){if(ca(i,"image_url")&&lc(i.image_url)&&ms(i.image_url.url)){let n=Srt({dataUrl:i.image_url.url});return n?{type:"image",mimeType:n.mime_type,data:n.data}:{type:"image",url:i.image_url.url}}else{if(ca(i,"input_audio")&&lc(i.input_audio)&&ms(i.input_audio.data)&&ms(i.input_audio.format))return{type:"audio",data:i.input_audio.data,mimeType:`audio/${i.input_audio.format}`};if(ca(i,"file")&&lc(i.file)&&ms(i.file.data)){let n=Srt({dataUrl:i.file.data});if(n)return{type:"file",data:n.data,mimeType:n.mime_type};if(ms(i.file.file_id))return{type:"file",fileId:i.file.file_id}}}return i}t(QVt,"convertToV1FromOpenAIDataBlock");function Von(i){let n=[];typeof i.content=="string"?i.content.length>0&&n.push({type:"text",text:i.content}):n.push(...Nke(i.content));for(let s of i.tool_calls??[])n.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return n}t(Von,"convertToV1FromChatCompletions");function qon(i){let n=[];typeof i.content=="string"?i.content.length>0&&n.push({type:"text",text:i.content}):n.push(...Nke(i.content));for(let s of i.tool_calls??[])n.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return n}t(qon,"convertToV1FromChatCompletionsChunk");function Nke(i){let n=[];for(let s of i)LVt(s)?n.push(QVt(s)):n.push(s);return n}t(Nke,"convertToV1FromChatCompletionsInput");function Gon(i){if(i.type==="url_citation"){let{url:n,title:s,start_index:c,end_index:u}=i;return{type:"citation",url:n,title:s,startIndex:c,endIndex:u}}if(i.type==="file_citation"){let{file_id:n,filename:s,index:c}=i;return{type:"citation",title:s,startIndex:c,endIndex:c,fileId:n}}return i}t(Gon,"convertResponsesAnnotation");function UVt(i){function*n(){var c;lc((c=i.additional_kwargs)==null?void 0:c.reasoning)&&mA(i.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:i.additional_kwargs.reasoning.summary.reduce((u,_)=>lc(_)&&ms(_.text)?`${u}${_.text}`:u,"")});let s=typeof i.content=="string"?[{type:"text",text:i.content}]:i.content;for(let u of s)if(ca(u,"text")){let{text:_,annotations:g,phase:b,extras:w,...k}=u,O=lc(w)?{...w}:{};ms(b)&&(O.phase=b);let G=Object.keys(O).length>0?{extras:O}:{};Array.isArray(g)?yield{...k,...G,type:"text",text:String(_),annotations:g.map(Gon)}:yield{...k,...G,type:"text",text:String(_)}}for(let u of i.tool_calls??[])yield{type:"tool_call",id:u.id,name:u.name,args:u.args};if(lc(i.additional_kwargs)&&mA(i.additional_kwargs.tool_outputs))for(let u of i.additional_kwargs.tool_outputs){if(ca(u,"web_search_call")){let _={};if(lc(u.action)&&ms(u.action.query)&&(_.query=u.action.query),yield{id:u.id,type:"server_tool_call",name:"web_search",args:_},u.status==="completed"||u.status==="failed"){let g={};lc(u.action)&&(g.action=u.action),yield{type:"server_tool_call_result",toolCallId:ms(u.id)?u.id:"",status:u.status==="completed"?"success":"error",output:g}}continue}else if(ca(u,"file_search_call")){yield{id:u.id,type:"server_tool_call",name:"file_search",args:{queries:mA(u.queries)?u.queries:[]}},(u.status==="completed"||u.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:ms(u.id)?u.id:"",status:u.status==="completed"?"success":"error",output:mA(u.results)?{results:u.results}:{}});continue}else if(ca(u,"computer_call")){yield{type:"non_standard",value:u};continue}else if(ca(u,"code_interpreter_call")){if(ms(u.code)&&(yield{id:u.id,type:"server_tool_call",name:"code_interpreter",args:{code:u.code}}),mA(u.outputs)){let _=RI(()=>{if(u.status!=="in_progress"){if(u.status==="completed")return 0;if(u.status==="incomplete")return 127;if(u.status!=="interpreting"&&u.status==="failed")return 1}});for(let g of u.outputs)if(ca(g,"logs")){yield{type:"server_tool_call_result",toolCallId:u.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:_??0,stderr:[0,void 0].includes(_)?void 0:String(g.logs),stdout:[0,void 0].includes(_)?String(g.logs):void 0}};continue}}continue}else if(ca(u,"mcp_call")){yield{id:u.id,type:"server_tool_call",name:"mcp_call",args:u.input};continue}else if(ca(u,"mcp_list_tools")){yield{id:u.id,type:"server_tool_call",name:"mcp_list_tools",args:u.input};continue}else if(ca(u,"mcp_approval_request")){yield{type:"non_standard",value:u};continue}else if(ca(u,"tool_search_call")){let _={};lc(u.arguments)&&Object.assign(_,u.arguments);let g={};ms(u.execution)&&(g.execution=u.execution),ms(u.status)&&(g.status=u.status),ms(u.call_id)&&(g.call_id=u.call_id),yield{id:ms(u.id)?u.id:"",type:"server_tool_call",name:"tool_search",args:_,...Object.keys(g).length>0?{extras:g}:{}};continue}else if(ca(u,"tool_search_output")){let _={name:"tool_search"};ms(u.execution)&&(_.execution=u.execution),yield{type:"server_tool_call_result",toolCallId:ms(u.id)?u.id:"",status:u.status==="completed"?"success":u.status==="failed"?"error":"success",output:{tools:mA(u.tools)?u.tools:[]},extras:_};continue}else if(ca(u,"image_generation_call")){ms(u.result)&&(yield{type:"image",mimeType:"image/png",data:u.result,id:ms(u.id)?u.id:void 0,metadata:{status:ms(u.status)?u.status:void 0}}),yield{type:"non_standard",value:u};continue}lc(u)&&(yield{type:"non_standard",value:u})}}return t(n,"iterateContent"),Array.from(n())}t(UVt,"convertToV1FromResponses");function Yon(i){function*n(){yield*UVt(i);for(let s of i.tool_call_chunks??[])yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args}}return t(n,"iterateContent"),Array.from(n())}t(Yon,"convertToV1FromResponsesChunk");var jVt={translateContent:t(i=>typeof i.content=="string"?Von(i):UVt(i),"translateContent"),translateContentChunk:t(i=>typeof i.content=="string"?qon(i):Yon(i),"translateContentChunk")};function JVt(i){return typeof i=="object"&&i!==null&&"type"in i&&"content"in i&&(typeof i.content=="string"||Array.isArray(i.content))}t(JVt,"isMessage");function $Vt(i,n="pretty"){return n==="pretty"?Zon(i):JSON.stringify(i)}t($Vt,"convertToFormattedString");function Zon(i){let n=[],s=` ${i.type.charAt(0).toUpperCase()+i.type.slice(1)} Message `,c=Math.floor((80-s.length)/2),u="=".repeat(c),_=s.length%2===0?u:`${u}=`;if(n.push(`${u}${s}${_}`),i.type==="ai"){let g=i;if(g.tool_calls&&g.tool_calls.length>0){n.push("Tool Calls:");for(let b of g.tool_calls){n.push(` ${b.name} (${b.id})`),n.push(` Call ID: ${b.id}`),n.push(" Args:");for(let[w,k]of Object.entries(b.args))n.push(` ${w}: ${typeof k=="object"?JSON.stringify(k):k}`)}}}if(i.type==="tool"){let g=i;g.name&&n.push(`Name: ${g.name}`)}return typeof i.content=="string"&&i.content.trim()&&(n.length>1&&n.push(""),n.push(i.content)),n.join(`
package/package.json CHANGED
@@ -43,5 +43,5 @@
43
43
  "url": "https://github.com/checksum-ai/checksum-ai-monorepo/issues"
44
44
  },
45
45
  "homepage": "https://github.com/checksum-ai/checksum-ai-monorepo/tree/main/packages/runtime#readme",
46
- "version": "4.3.2-beta.10"
46
+ "version": "4.3.2-beta.11"
47
47
  }