@checksum-ai/runtime 1.3.6 → 1.3.7

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 (3) hide show
  1. package/.env +1 -1
  2. package/index.js +2 -2
  3. package/package.json +1 -1
package/.env CHANGED
@@ -1 +1 @@
1
- CHECKSUM_RUNTIME_BUILD_TIME=2025-09-02T14:56:07.529Z
1
+ CHECKSUM_RUNTIME_BUILD_TIME=2025-09-03T15:09:21.259Z
package/index.js CHANGED
@@ -1827,7 +1827,7 @@ ${this.executedSteps.map(c=>{switch(c.type){case"action":return c.thought;case"a
1827
1827
  Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof t=="string"?`selector ${t}`:"locator"}`);try{t&&typeof t=="object"&&"has"in t&&this.popLocatorChain()}catch{}let a=this.getLocator(t,r);return new Proxy(a,{get:e((o,c)=>this.getLocatorMethod(a,o,c),"get")})}catch(a){Qv("Failed to locate",a)}}getLocatorMethod(t,r,a){return a==="then"?this.handleThen(t,r,a):a==="catch"?this.handleCatch(t,r):a==="finally"?this.handleFinally(t,r):a==="constructor"?e(function(...c){return this.popLocatorChain(),r.constructor(...c)},"Locator"):a in r&&typeof r[a]!="function"||a===Symbol.toPrimitive||a in Object||a==="evaluate"?(this.popLocatorChain(),r[a]):a==="compoundSelection"?function(...o){let c=this.compoundSelection(...o);return c.setBase(t),c}.bind(this):[...Object.values(yme),...Object.values(e$e)].includes(a)?["or","and"].includes(a)?(Qv("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),r[a]):(this.getCurrentLocatorChain().push({type:a,base:t}),e(function(...c){return this.executeLocator(c[0],c[1])},"Locator").bind(this)):a==="page"?()=>(this.popLocatorChain(),this.proxy.page()):e(async function(...c){let f=await this.executeLocatorAction(t,a,c);return this.popLocatorChain(),f},"Locator").bind(this)}async executeLocatorAction(t,r,a){if(a&&Array.from(a).some(_=>(_==null?void 0:_.bypassChecksum)===!0))return t[r](...a);let o=t._selector;Qv("Executing",r,o);let c=r==="_expect"?"assertion":"action";c==="action"&&this.lastLocatorActionType==="action"&&(Qv("Adding minimal wait between consecutive actions..."),await new Promise(_=>setTimeout(_,100))),this.lastLocatorActionType=c,Qv("Running initial locator...");let f;try{return this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{Qv("[executeLocatorAction] waitForFunction"),await this.frame.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{Qv("[executeLocatorAction] checksum libs not loaded")}}),await aqt.createAction({locator:t,method:r,args:a,timeout:this.getLocatorActionTimeout(c,r,a)},{api:this.checksumClient,pageInteractor:this.getPageInteractor()}).guardedExecute();f=new Error("Locator action error")}catch(_){Qv("Failed initial execution. Exception:",_.message),f=_}if(c==="action"&&this.onExecutionError)return this.onExecutionError({error:f,locator:t,method:r,args:a},this.frame);throw f}setExpectConfiguration(t=void 0){this.expectConfiguration=t}getLocatorActionTimeout(t,r,a=[]){var o;if(this.isReplMode)return null;try{if(t==="assertion"){let _=this.getAssertionTimeout(a);return Qv(`Assertion timeout set to ${_}`),_}let c=["fill","dragTo"].includes(r)?1:0,f=(o=a[c])==null?void 0:o.timeout;return isNaN(f)?3e4:f}catch{return 3e4}}getAssertionTimeout(t=[]){var o,c,f,_,b;let r=(o=t[1])==null?void 0:o.timeout;if(r!==void 0)return r;if(((c=this.expectConfiguration)==null?void 0:c.timeout)!==void 0)return(f=this.expectConfiguration)==null?void 0:f.timeout;let a=(b=(_=this.testInfo._projectInternal)==null?void 0:_.expect)==null?void 0:b.timeout;return a!==void 0?a:3e4}handleThen(t,r,a){return(o,c)=>Promise.resolve(t).then(f=>{let _=o?o(f):f;return _ instanceof Promise?_:this.getLocatorMethod(_,r,a)},f=>{if(c)return c(f);throw f})}handleCatch(t,r){return a=>Promise.resolve(t).catch(o=>{if(a)return a(o);throw o})}handleFinally(t,r){return a=>Promise.resolve(t).finally(a)}};e(uqt,"ChecksumFrame");var oqt=uqt;var cqt=class cqt{constructor(t,r,a,o,c){this.page=t;this.config=r;this.getPageInteractor=a;this.injectedScriptManager=o;this._frames={};this.isVTG=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;var f,_;this.setPageProxy(),this.injectedScriptManager||(this.injectedScriptManager=new Oze({scriptFile:o_.checksumScript.path,scriptSource:o_.checksumScript.source,scriptURL:o_.checksumScript.url,isScriptFileAbsolute:!0,silenceLogs:!o_.isDevMode,scriptInitWait:(f=r==null?void 0:r.options)==null?void 0:f.browserScriptInitWait,scriptAddWait:(_=r==null?void 0:r.options)==null?void 0:_.browserScriptAddWait})),this.registerPageEvents(),this.page.frames().forEach(b=>this.registerFrame(b)),c&&(this.variableStore=c.variableStore)}static makePage(t,r,a){let o=lqt();return new cqt(t,o,()=>r,a).proxy}async registerFrame(t){var o;let r=this.getFrameGuid(t);if(t===this.page.mainFrame()&&(this.mainFrameGuid=r),this._frames[r])return;let a=oqt.init(t,this.proxy,this.injectedScriptManager,this.getPageInteractor,(o=this.onExecutionError)==null?void 0:o.bind(this),this.config);this._frames[r]=a}async onExecutionError(t){throw t.error}getFrameGuid(t){return t._guid}registerPageEvents(){this.page.on("frameattached",async t=>{this.registerFrame(t)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getPageMethod(a)},"get")})}getPageMethod(t){if(typeof this[t]=="function")return t==="constructor"?this[t]:this[t].bind(this);switch(t){case"pageInteractor":return this.getPageInteractor();case"variableStore":return this.variableStore}return Object.values(yme).includes(t)?e(function(a,o){try{return this.mainFrame()[t](a,o)}catch(c){throw c}},"Page").bind(this):this.page[t]}mainFrame(){var t;return(t=this._frames)==null?void 0:t[this.mainFrameGuid]}frames(){return Object.values(this._frames)}getFrame(t){if(!this.page.frames().find(a=>this.getFrameGuid(a)===t))throw new Error(`Frame with guid ${t} not found`);return this._frames[t]}async waitForDialog(t){try{return this.getPageInteractor().waitForDialog(!0,t)}catch(r){throw new Error(`Failed to handle native dialog: ${r}`)}}async reauthenticate(t){try{await this.getPageInteractor().reauthenticate(t,this.proxy)}catch(r){throw new Error(`Failed to reauthenticate: ${r}`)}}resolveAssetsFolder(t){return t.map(r=>TOn.join(eft(Nne()),r))}compoundSelection(...t){try{return new Nze(this.mainFrame()).init(...t)}catch{throw new Error("Failed generating compound selector")}}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}setExpectConfiguration(t=void 0){this.expectConfiguration=t,Object.values(this._frames).forEach(r=>r.setExpectConfiguration(t))}};e(cqt,"ChecksumPage");var Bze=cqt;Dqr();II();var dbe=class dbe{constructor(){this.toolsMap={}}get addTool(){return this._addTool||(this._addTool=this.buildAddToolFacade()),this._addTool}getToolNames(){return Object.keys(this.toolRecord.names)}get tools(){return this.toolsMap}buildAddToolFacade(){let t={},r=this.toolRecord.tools;for(let a of Object.keys(r))t[a]=o=>this._addSingleTool(a,o);return t}static describeTool(t,r){if(t instanceof Nh.ZodObject){let a={},o=t.shape;for(let c of Object.keys(o)){let f=o[c],_=r==null?void 0:r[c];typeof _=="string"?a[c]=f.describe(_):_&&typeof _=="object"?a[c]=dbe.describeTool(f,_):a[c]=f}return Nh.object(a).strict()}if(t instanceof Nh.ZodArray){let a=t.element;return r&&typeof r=="object"&&r.element?Nh.array(dbe.describeTool(a,r.element)):t}return t instanceof Nh.ZodOptional?dbe.describeTool(t.unwrap(),r).optional():t instanceof Nh.ZodNullable?dbe.describeTool(t.unwrap(),r).nullable():typeof r=="string"?t.describe(r):t}_addSingleTool(t,r){let a=r.name??String(t),c=this.toolRecord.tools[t]._create({...r,name:a,params:r.params,handler:r.handler}),f=this.toolRecord.tools[t],_=dbe.describeTool(f,r.params),C=Aqr(e(async w=>{let T=_.parse(w);return r.handler(T)},"validatedHandler"),{name:c.name,description:c.description,schema:_});return this.toolsMap[t]=C,C}_buildOne(t,r){return this._addSingleTool(t,{...r,name:String(t)})}static buildTool(t,r,a){let o=String(r),f=t.tools[r]._create({name:o,description:"",handler:a,params:{}}),_=t.tools[r],b=dbe.describeTool(_,{});return Aqr(e(async T=>{let k=b.parse(T);return a(k)},"validatedHandler"),{name:f.name,description:f.description,schema:b})}};e(dbe,"AbstractToolContainer");var n7e=dbe;II();var D$t=class D$t{constructor(t,r){this.version=t;let a={};for(let c in r)a[c]=c;this.names=a;let o={};for(let c in r){let f=r[c];Object.defineProperty(f,"name",{value:c,configurable:!1,enumerable:!0,writable:!1}),f._create=(_=>b=>{let C=b.name??_;return{...b,name:C}})(c),o[c]=f}this.tools=o}static create(t,r){return new D$t(t,r)}};e(D$t,"ToolProtocol");var S$t=D$t;var Aj=S$t.create("v1",{readFile:Nh.object({path:Nh.string()}),getState:Nh.object({thought:Nh.string()}),invokeCode:Nh.object({code:Nh.string().refine(i=>{let t=i.trim();return t.includes("page.getByChecksumId(")||t.includes("page.getByChecksumId(")||t.startsWith("const ")||t.startsWith("let ")||t.startsWith("var ")||t.includes("=")||t.includes("variableStore.")},{message:"Code should use page.getByChecksumId() for element targeting, or be explicit variable assignments/function calls"}),thought:Nh.string()}),wait:Nh.object({time:Nh.number().optional()}),scroll:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),final_result:Nh.object({result:Nh.enum(["pass","fail"]),thought:Nh.string(),visualAnalysis:Nh.string().optional()}),getElementScreenshot:Nh.object({checksumId:Nh.string(),thought:Nh.string()}),analyze:Nh.object({previousImmediateSteps:Nh.string(),currentFailingStep:Nh.string(),nextImmediateSteps:Nh.string(),testStepToStopAt:Nh.string()}),think:Nh.object({thought:Nh.string()})});var $qr=uf(lqn(),1);var Mce=Object.create(null);Mce.open="0";Mce.close="1";Mce.ping="2";Mce.pong="3";Mce.message="4";Mce.upgrade="5";Mce.noop="6";var Umt=Object.create(null);Object.keys(Mce).forEach(i=>{Umt[Mce[i]]=i});var qmt={type:"error",data:"parser error"};var Qmt=e(({type:i,data:t},r,a)=>t instanceof ArrayBuffer||ArrayBuffer.isView(t)?a(r?t:"b"+pqn(t,!0).toString("base64")):a(Mce[i]+(t||"")),"encodePacket"),pqn=e((i,t)=>Buffer.isBuffer(i)||i instanceof Uint8Array&&!t?i:i instanceof ArrayBuffer?Buffer.from(i):Buffer.from(i.buffer,i.byteOffset,i.byteLength),"toBuffer"),kqr;function fqn(i,t){if(i.data instanceof ArrayBuffer||ArrayBuffer.isView(i.data))return t(pqn(i.data,!1));Qmt(i,!0,r=>{kqr||(kqr=new TextEncoder),t(kqr.encode(r))})}e(fqn,"encodePacketToBinary");var $mt=e((i,t)=>{if(typeof i!="string")return{type:"message",data:dqn(i,t)};let r=i.charAt(0);if(r==="b"){let a=Buffer.from(i.substring(1),"base64");return{type:"message",data:dqn(a,t)}}return Umt[r]?i.length>1?{type:Umt[r],data:i.substring(1)}:{type:Umt[r]}:qmt},"decodePacket"),dqn=e((i,t)=>{switch(t){case"arraybuffer":return i instanceof ArrayBuffer?i:Buffer.isBuffer(i)?i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength):i.buffer;case"nodebuffer":default:return Buffer.isBuffer(i)?i:Buffer.from(i)}},"mapBinary");var mqn="",_qn=e((i,t)=>{let r=i.length,a=new Array(r),o=0;i.forEach((c,f)=>{Qmt(c,!1,_=>{a[f]=_,++o===r&&t(a.join(mqn))})})},"encodePayload"),hqn=e((i,t)=>{let r=i.split(mqn),a=[];for(let o=0;o<r.length;o++){let c=$mt(r[o],t);if(a.push(c),c.type==="error")break}return a},"decodePayload");function gqn(){return new TransformStream({transform(i,t){fqn(i,r=>{let a=r.length,o;if(a<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,a);else if(a<65536){o=new Uint8Array(3);let c=new DataView(o.buffer);c.setUint8(0,126),c.setUint16(1,a)}else{o=new Uint8Array(9);let c=new DataView(o.buffer);c.setUint8(0,127),c.setBigUint64(1,BigInt(a))}i.data&&typeof i.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}e(gqn,"createPacketEncoderStream");var Iqr;function T$t(i){return i.reduce((t,r)=>t+r.length,0)}e(T$t,"totalLength");function k$t(i,t){if(i[0].length===t)return i.shift();let r=new Uint8Array(t),a=0;for(let o=0;o<t;o++)r[o]=i[0][a++],a===i[0].length&&(i.shift(),a=0);return i.length&&a<i[0].length&&(i[0]=i[0].slice(a)),r}e(k$t,"concatChunks");function yqn(i,t){Iqr||(Iqr=new TextDecoder);let r=[],a=0,o=-1,c=!1;return new TransformStream({transform(f,_){for(r.push(f);;){if(a===0){if(T$t(r)<1)break;let b=k$t(r,1);c=(b[0]&128)===128,o=b[0]&127,o<126?a=3:o===126?a=1:a=2}else if(a===1){if(T$t(r)<2)break;let b=k$t(r,2);o=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(T$t(r)<8)break;let b=k$t(r,8),C=new DataView(b.buffer,b.byteOffset,b.length),w=C.getUint32(0);if(w>Math.pow(2,21)-1){_.enqueue(qmt);break}o=w*Math.pow(2,32)+C.getUint32(4),a=3}else{if(T$t(r)<o)break;let b=k$t(r,o);_.enqueue($mt(c?b:Iqr.decode(b),t)),a=0}if(o===0||o>i){_.enqueue(qmt);break}}}})}e(yqn,"createPacketDecoderStream");var Pqr=4;var Oqn=uf(WPe(),1);var mbe=process.nextTick,Ez=global,bqn="nodebuffer";function xqn(){return new Fqr}e(xqn,"createCookieJar");function c2a(i){let t=i.split("; "),r=t[0].indexOf("=");if(r===-1)return;let a=t[0].substring(0,r).trim();if(!a.length)return;let o=t[0].substring(r+1).trim();o.charCodeAt(0)===34&&(o=o.slice(1,-1));let c={name:a,value:o};for(let f=1;f<t.length;f++){let _=t[f].split("=");if(_.length!==2)continue;let b=_[0].trim(),C=_[1].trim();switch(b){case"Expires":c.expires=new Date(C);break;case"Max-Age":let w=new Date;w.setUTCSeconds(w.getUTCSeconds()+parseInt(C,10)),c.expires=w;break;default:}}return c}e(c2a,"parse");var Nqr=class Nqr{constructor(){this._cookies=new Map}parseCookies(t){t&&t.forEach(r=>{let a=c2a(r);a&&this._cookies.set(a.name,a)})}get cookies(){let t=Date.now();return this._cookies.forEach((r,a)=>{var o;((o=r.expires)===null||o===void 0?void 0:o.getTime())<t&&this._cookies.delete(a)}),this._cookies.entries()}addCookies(t){let r=[];for(let[a,o]of this.cookies)r.push(`${a}=${o.value}`);r.length&&(t.setDisableHeaderCheck(!0),t.setRequestHeader("cookie",r.join("; ")))}appendCookies(t){for(let[r,a]of this.cookies)t.append("cookie",`${r}=${a.value}`)}};e(Nqr,"CookieJar");var Fqr=Nqr;function I$t(i,...t){return t.reduce((r,a)=>(i.hasOwnProperty(a)&&(r[a]=i[a]),r),{})}e(I$t,"pick");var l2a=Ez.setTimeout,p2a=Ez.clearTimeout;function _be(i,t){t.useNativeTimers?(i.setTimeoutFn=l2a.bind(Ez),i.clearTimeoutFn=p2a.bind(Ez)):(i.setTimeoutFn=Ez.setTimeout.bind(Ez),i.clearTimeoutFn=Ez.clearTimeout.bind(Ez))}e(_be,"installTimerFunctions");var f2a=1.33;function Aqn(i){return typeof i=="string"?d2a(i):Math.ceil((i.byteLength||i.size)*f2a)}e(Aqn,"byteLength");function d2a(i){let t=0,r=0;for(let a=0,o=i.length;a<o;a++)t=i.charCodeAt(a),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(a++,r+=4);return r}e(d2a,"utf8Length");function P$t(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}e(P$t,"randomString");function Eqn(i){let t="";for(let r in i)i.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(i[r]));return t}e(Eqn,"encode");function Cqn(i){let t={},r=i.split("&");for(let a=0,o=r.length;a<o;a++){let c=r[a].split("=");t[decodeURIComponent(c[0])]=decodeURIComponent(c[1])}return t}e(Cqn,"decode");var Bqn=uf(KPe(),1);var R2a=(0,Bqn.default)("engine.io-client:transport"),Mqr=class Mqr extends Error{constructor(t,r,a){super(t),this.description=r,this.context=a,this.type="TransportError"}};e(Mqr,"TransportError");var R$t=Mqr,jqr=class jqr extends Oqn.Emitter{constructor(t){super(),this.writable=!1,_be(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,r,a){return super.emitReserved("error",new R$t(t,r,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"?this.write(t):R2a("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){let r=$mt(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,r={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(r)}_hostname(){let t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){let r=Eqn(t);return r.length?"?"+r:""}};e(jqr,"Transport");var hbe=jqr;var Rqn=uf(KPe(),1);var jce=(0,Rqn.default)("engine.io-client:polling"),Uqr=class Uqr extends hbe{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";let r=e(()=>{jce("paused"),this.readyState="paused",t()},"pause");if(this._polling||!this.writable){let a=0;this._polling&&(jce("we are currently polling - waiting to pause"),a++,this.once("pollComplete",function(){jce("pre-pause polling complete"),--a||r()})),this.writable||(jce("we are currently writing - waiting to pause"),a++,this.once("drain",function(){jce("pre-pause writing complete"),--a||r()}))}else r()}_poll(){jce("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){jce("polling got data %s",t);let r=e(a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)},"callback");hqn(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():jce('ignoring poll - transport state "%s"',this.readyState))}doClose(){let t=e(()=>{jce("writing close packet"),this.write([{type:"close"}])},"close");this.readyState==="open"?(jce("transport open - closing"),t()):(jce("transport not open - deferring close"),this.once("open",t))}write(t){this.writable=!1,_qn(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=P$t()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}};e(Uqr,"Polling");var zmt=Uqr;var Uqn=uf(WPe(),1);var Lqn=!1;try{Lqn=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Mqn=Lqn;var qqn=uf(KPe(),1);var qqr=(0,qqn.default)("engine.io-client:polling");function L2a(){}e(L2a,"empty");var Qqr=class Qqr extends zmt{constructor(t){if(super(t),typeof location<"u"){let r=location.protocol==="https:",a=location.port;a||(a=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||a!==t.port}}doWrite(t,r){let a=this.request({method:"POST",data:t});a.on("success",r),a.on("error",(o,c)=>{this.onError("xhr post error",o,c)})}doPoll(){qqr("xhr poll");let t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,a)=>{this.onError("xhr poll error",r,a)}),this.pollXhr=t}};e(Qqr,"BaseXHR");var L$t=Qqr,TJe=class TJe extends Uqn.Emitter{constructor(t,r,a){super(),this.createRequest=t,_be(this,a),this._opts=a,this._method=a.method||"GET",this._uri=r,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var t;let r=I$t(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let a=this._xhr=this.createRequest(r);try{qqr("xhr open %s: %s",this._method,this._uri),a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let o in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(o)&&a.setRequestHeader(o,this._opts.extraHeaders[o])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var o;a.readyState===3&&((o=this._opts.cookieJar)===null||o===void 0||o.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},qqr("xhr data %s",this._data),a.send(this._data)}catch(o){this.setTimeoutFn(()=>{this._onError(o)},0);return}typeof document<"u"&&(this._index=TJe.requestsCount++,TJe.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=L2a,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete TJe.requests[this._index],this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};e(TJe,"Request");var gbe=TJe;gbe.requestsCount=0;gbe.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",jqn);else if(typeof addEventListener=="function"){let i="onpagehide"in Ez?"pagehide":"unload";addEventListener(i,jqn,!1)}}function jqn(){for(let i in gbe.requests)gbe.requests.hasOwnProperty(i)&&gbe.requests[i].abort()}e(jqn,"unloadHandler");var o7s=function(){let i=M2a({xdomain:!1});return i&&i.responseType!==null}();function M2a(i){let t=i.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Mqn))return new XMLHttpRequest}catch{}if(!t)try{return new Ez[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}e(M2a,"newRequest");var j2a=$qr.default||$qr,Vqr=class Vqr extends L$t{request(t={}){var r;return Object.assign(t,{xd:this.xd,cookieJar:(r=this.socket)===null||r===void 0?void 0:r._cookieJar},this.opts),new gbe(a=>new j2a(a),this.uri(),t)}};e(Vqr,"XHR");var kJe=Vqr;var Gva=uf(zqn(),1),Kva=uf(iQr(),1),Yva=uf(sQr(),1),bQr=uf(gQr(),1),Xva=uf(QQn(),1);var $Qn=uf(KPe(),1);var eba=(0,$Qn.default)("engine.io-client:websocket"),tba=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",xQr=class xQr extends hbe{get name(){return"websocket"}doOpen(){let t=this.uri(),r=this.opts.protocols,a=tba?{}:I$t(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,a)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;Qmt(a,this.supportsBinary,c=>{try{this.doWrite(a,c)}catch{eba("websocket closed before onclose event")}o&&mbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=P$t()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}};e(xQr,"BaseWS");var Y$t=xQr,W7s=Ez.WebSocket||Ez.MozWebSocket;var AQr=class AQr extends Y$t{createSocket(t,r,a){var o;if(!((o=this.socket)===null||o===void 0)&&o._cookieJar){a.headers=a.headers||{},a.headers.cookie=typeof a.headers.cookie=="string"?[a.headers.cookie]:a.headers.cookie||[];for(let[c,f]of this.socket._cookieJar.cookies)a.headers.cookie.push(`${c}=${f.value}`)}return new bQr.default(t,r,a)}doWrite(t,r){let a={};t.options&&(a.compress=t.options.compress),this.opts.perMessageDeflate&&(typeof r=="string"?Buffer.byteLength(r):r.length)<this.opts.perMessageDeflate.threshold&&(a.compress=!1),this.ws.send(r,a)}};e(AQr,"WS");var OJe=AQr;var VQn=uf(KPe(),1);var r_t=(0,VQn.default)("engine.io-client:webtransport"),EQr=class EQr extends hbe{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{r_t("transport closed gracefully"),this.onClose()}).catch(t=>{r_t("transport closed due to %s",t),this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{let r=yqn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=t.readable.pipeThrough(r).getReader(),o=gqn();o.readable.pipeTo(t.writable),this._writer=o.writable.getWriter();let c=e(()=>{a.read().then(({done:_,value:b})=>{if(_){r_t("session is closed");return}r_t("received chunk: %o",b),this.onPacket(b),c()}).catch(_=>{r_t("an error occurred while reading: %s",_)})},"read");c();let f={type:"open"};this.query.sid&&(f.data=`{"sid":"${this.query.sid}"}`),this._writer.write(f).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r<t.length;r++){let a=t[r],o=r===t.length-1;this._writer.write(a).then(()=>{o&&mbe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}};e(EQr,"WT");var BJe=EQr;var CQr={websocket:OJe,webtransport:BJe,polling:kJe};var rba=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nba=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function RJe(i){if(i.length>8e3)throw"URI too long";let t=i,r=i.indexOf("["),a=i.indexOf("]");r!=-1&&a!=-1&&(i=i.substring(0,r)+i.substring(r,a).replace(/:/g,";")+i.substring(a,i.length));let o=rba.exec(i||""),c={},f=14;for(;f--;)c[nba[f]]=o[f]||"";return r!=-1&&a!=-1&&(c.source=t,c.host=c.host.substring(1,c.host.length-1).replace(/;/g,":"),c.authority=c.authority.replace("[","").replace("]","").replace(/;/g,":"),c.ipv6uri=!0),c.pathNames=iba(c,c.path),c.queryKey=aba(c,c.query),c}e(RJe,"parse");function iba(i,t){let r=/\/{2,9}/g,a=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&a.splice(0,1),t.slice(-1)=="/"&&a.splice(a.length-1,1),a}e(iba,"pathNames");function aba(i,t){let r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,o,c){o&&(r[o]=c)}),r}e(aba,"queryKey");var zQn=uf(WPe(),1);var JQn=uf(KPe(),1);var C7=(0,JQn.default)("engine.io-client:socket"),wQr=typeof addEventListener=="function"&&typeof removeEventListener=="function",n_t=[];wQr&&addEventListener("offline",()=>{C7("closing %d connection(s) because the network was lost",n_t.length),n_t.forEach(i=>i())},!1);var LJe=class LJe extends zQn.Emitter{constructor(t,r){if(super(),this.binaryType=bqn,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let a=RJe(t);r.hostname=a.host,r.secure=a.protocol==="https"||a.protocol==="wss",r.port=a.port,a.query&&(r.query=a.query)}else r.host&&(r.hostname=RJe(r.host).host);_be(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(a=>{let o=a.prototype.name;this.transports.push(o),this._transportsByName[o]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Cqn(this.opts.query)),wQr&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(C7("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},n_t.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=xqn()),this._open()}createTransport(t){C7('creating transport "%s"',t);let r=Object.assign({},this.opts.query);r.EIO=Pqr,r.transport=t,this.id&&(r.sid=this.id);let a=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return C7("options: %j",a),new this._transportsByName[t](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&LJe.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){C7("setting transport %s",t.name),this.transport&&(C7("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){C7("socket open"),this.readyState="open",LJe.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(C7('socket receive: type "%s", data "%s"',t.type,t.data),this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}else C7('packet received with socket readyState "%s"',this.readyState)}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();C7("flushing %d packets in socket",t.length),this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let a=0;a<this.writeBuffer.length;a++){let o=this.writeBuffer[a].data;if(o&&(r+=Aqn(o)),a>0&&r>this._maxPayload)return C7("only send %d out of %d packets",a,this.writeBuffer.length),this.writeBuffer.slice(0,a);r+=2}return C7("payload size is %d (max: %d)",r,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(C7("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,mbe(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,a){return this._sendPacket("message",t,r,a),this}send(t,r,a){return this._sendPacket("message",t,r,a),this}_sendPacket(t,r,a,o){if(typeof r=="function"&&(o=r,r=void 0),typeof a=="function"&&(o=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;let c={type:t,data:r,options:a};this.emitReserved("packetCreate",c),this.writeBuffer.push(c),o&&this.once("flush",o),this.flush()}close(){let t=e(()=>{this._onClose("forced close"),C7("socket closing - telling transport to close"),this.transport.close()},"close"),r=e(()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},"cleanupAndClose"),a=e(()=>{this.once("upgrade",r),this.once("upgradeError",r)},"waitForUpgrade");return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():t()}):this.upgrading?a():t()),this}_onError(t){if(C7("socket error %j",t),LJe.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return C7("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(C7('socket close with reason: "%s"',t),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),wQr&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let a=n_t.indexOf(this._offlineEventListener);a!==-1&&(C7("removing listener for the 'offline' event"),n_t.splice(a,1))}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};e(LJe,"SocketWithoutUpgrade");var tFe=LJe;tFe.protocol=Pqr;var SQr=class SQr extends tFe{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){C7("starting upgrade probes");for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}}_probe(t){C7('probing transport "%s"',t);let r=this.createTransport(t),a=!1;tFe.priorWebsocketSuccess=!1;let o=e(()=>{a||(C7('probe transport "%s" opened',t),r.send([{type:"ping",data:"probe"}]),r.once("packet",T=>{if(!a)if(T.type==="pong"&&T.data==="probe"){if(C7('probe transport "%s" pong',t),this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;tFe.priorWebsocketSuccess=r.name==="websocket",C7('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{a||this.readyState!=="closed"&&(C7("changing transport and sending upgrade packet"),w(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{C7('probe transport "%s" failed',t);let k=new Error("probe error");k.transport=r.name,this.emitReserved("upgradeError",k)}}))},"onTransportOpen");function c(){a||(a=!0,w(),r.close(),r=null)}e(c,"freezeTransport");let f=e(T=>{let k=new Error("probe error: "+T);k.transport=r.name,c(),C7('probe transport "%s" failed because of error: %s',t,T),this.emitReserved("upgradeError",k)},"onerror");function _(){f("transport closed")}e(_,"onTransportClose");function b(){f("socket closed")}e(b,"onclose");function C(T){r&&T.name!==r.name&&(C7('"%s" works - aborting "%s"',T.name,r.name),c())}e(C,"onupgrade");let w=e(()=>{r.removeListener("open",o),r.removeListener("error",f),r.removeListener("close",_),this.off("close",b),this.off("upgrading",C)},"cleanup");r.once("open",o),r.once("error",f),r.once("close",_),this.once("close",b),this.once("upgrading",C),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{a||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){let r=[];for(let a=0;a<t.length;a++)~this.transports.indexOf(t[a])&&r.push(t[a]);return r}};e(SQr,"SocketWithUpgrade");var X$t=SQr,DQr=class DQr extends X$t{constructor(t,r={}){let a=typeof t=="object"?t:r;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(o=>CQr[o]).filter(o=>!!o)),super(t,a)}};e(DQr,"Socket");var MJe=DQr;var ADs=MJe.protocol;var XQn=uf(i_t(),1);var YQn=(0,XQn.default)("socket.io-client:url");function ZQn(i,t="",r){let a=i;r=r||typeof location<"u"&&location,i==null&&(i=r.protocol+"//"+r.host),typeof i=="string"&&(i.charAt(0)==="/"&&(i.charAt(1)==="/"?i=r.protocol+i:i=r.host+i),/^(https?|wss?):\/\//.test(i)||(YQn("protocol-less url %s",i),typeof r<"u"?i=r.protocol+"//"+i:i="https://"+i),YQn("parse %s",i),a=RJe(i)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";let c=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+c+":"+a.port+t,a.href=a.protocol+"://"+c+(r&&r.port===a.port?"":":"+a.port),a}e(ZQn,"url");var MQr={};nQ(MQr,{Decoder:()=>RQr,Encoder:()=>BQr,PacketType:()=>RE,protocol:()=>p$n});var c$n=uf(WPe(),1);var Cba=typeof ArrayBuffer=="function",wba=e(i=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer,"isView"),e$n=Object.prototype.toString,Sba=typeof Blob=="function"||typeof Blob<"u"&&e$n.call(Blob)==="[object BlobConstructor]",Dba=typeof File=="function"||typeof File<"u"&&e$n.call(File)==="[object FileConstructor]";function s_t(i){return Cba&&(i instanceof ArrayBuffer||wba(i))||Sba&&i instanceof Blob||Dba&&i instanceof File}e(s_t,"isBinary");function a_t(i,t){if(!i||typeof i!="object")return!1;if(Array.isArray(i)){for(let r=0,a=i.length;r<a;r++)if(a_t(i[r]))return!0;return!1}if(s_t(i))return!0;if(i.toJSON&&typeof i.toJSON=="function"&&arguments.length===1)return a_t(i.toJSON(),!0);for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)&&a_t(i[r]))return!0;return!1}e(a_t,"hasBinary");function t$n(i){let t=[],r=i.data,a=i;return a.data=IQr(r,t),a.attachments=t.length,{packet:a,buffers:t}}e(t$n,"deconstructPacket");function IQr(i,t){if(!i)return i;if(s_t(i)){let r={_placeholder:!0,num:t.length};return t.push(i),r}else if(Array.isArray(i)){let r=new Array(i.length);for(let a=0;a<i.length;a++)r[a]=IQr(i[a],t);return r}else if(typeof i=="object"&&!(i instanceof Date)){let r={};for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&(r[a]=IQr(i[a],t));return r}return i}e(IQr,"_deconstructPacket");function r$n(i,t){return i.data=PQr(i.data,t),delete i.attachments,i}e(r$n,"reconstructPacket");function PQr(i,t){if(!i)return i;if(i&&i._placeholder===!0){if(typeof i.num=="number"&&i.num>=0&&i.num<t.length)return t[i.num];throw new Error("illegal attachments")}else if(Array.isArray(i))for(let r=0;r<i.length;r++)i[r]=PQr(i[r],t);else if(typeof i=="object")for(let r in i)Object.prototype.hasOwnProperty.call(i,r)&&(i[r]=PQr(i[r],t));return i}e(PQr,"_reconstructPacket");var l$n=uf(o$n(),1);var OQr=(0,l$n.default)("socket.io-parser"),$ba=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],p$n=5,RE;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(RE||(RE={}));var jQr=class jQr{constructor(t){this.replacer=t}encode(t){return OQr("encoding packet %j",t),(t.type===RE.EVENT||t.type===RE.ACK)&&a_t(t)?this.encodeAsBinary({type:t.type===RE.EVENT?RE.BINARY_EVENT:RE.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let r=""+t.type;return(t.type===RE.BINARY_EVENT||t.type===RE.BINARY_ACK)&&(r+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(r+=t.nsp+","),t.id!=null&&(r+=t.id),t.data!=null&&(r+=JSON.stringify(t.data,this.replacer)),OQr("encoded %j as %s",t,r),r}encodeAsBinary(t){let r=t$n(t),a=this.encodeAsString(r.packet),o=r.buffers;return o.unshift(a),o}};e(jQr,"Encoder");var BQr=jQr;function u$n(i){return Object.prototype.toString.call(i)==="[object Object]"}e(u$n,"isObject");var aVt=class aVt extends c$n.Emitter{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let a=r.type===RE.BINARY_EVENT;a||r.type===RE.BINARY_ACK?(r.type=a?RE.EVENT:RE.ACK,this.reconstructor=new LQr(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(s_t(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,a={type:Number(t.charAt(0))};if(RE[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===RE.BINARY_EVENT||a.type===RE.BINARY_ACK){let c=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let f=t.substring(c,r);if(f!=Number(f)||t.charAt(r)!=="-")throw new Error("Illegal attachments");a.attachments=Number(f)}if(t.charAt(r+1)==="/"){let c=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););a.nsp=t.substring(c,r)}else a.nsp="/";let o=t.charAt(r+1);if(o!==""&&Number(o)==o){let c=r+1;for(;++r;){let f=t.charAt(r);if(f==null||Number(f)!=f){--r;break}if(r===t.length)break}a.id=Number(t.substring(c,r+1))}if(t.charAt(++r)){let c=this.tryParse(t.substr(r));if(aVt.isPayloadValid(a.type,c))a.data=c;else throw new Error("invalid payload")}return OQr("decoded %s as %j",t,a),a}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case RE.CONNECT:return u$n(r);case RE.DISCONNECT:return r===void 0;case RE.CONNECT_ERROR:return typeof r=="string"||u$n(r);case RE.EVENT:case RE.BINARY_EVENT:return Array.isArray(r)&&(typeof r[0]=="number"||typeof r[0]=="string"&&$ba.indexOf(r[0])===-1);case RE.ACK:case RE.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};e(aVt,"Decoder");var RQr=aVt,UQr=class UQr{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){let r=r$n(this.reconPack,this.buffers);return this.finishedReconstruction(),r}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};e(UQr,"BinaryReconstructor");var LQr=UQr;function yZ(i,t,r){return i.on(t,r),e(function(){i.off(t,r)},"subDestroy")}e(yZ,"on");var f$n=uf(WPe(),1),d$n=uf(i_t(),1);var aO=(0,d$n.default)("socket.io-client:socket"),Vba=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),qQr=class qQr extends f$n.Emitter{constructor(t,r,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=r,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let t=this.io;this.subs=[yZ(t,"open",this.onopen.bind(this)),yZ(t,"packet",this.onpacket.bind(this)),yZ(t,"error",this.onerror.bind(this)),yZ(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...r){var a,o,c;if(Vba.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(r.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(r),this;let f={type:RE.EVENT,data:r};if(f.options={},f.options.compress=this.flags.compress!==!1,typeof r[r.length-1]=="function"){let w=this.ids++;aO("emitting packet with ack id %d",w);let T=r.pop();this._registerAckCallback(w,T),f.id=w}let _=(o=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||o===void 0?void 0:o.writable,b=this.connected&&!(!((c=this.io.engine)===null||c===void 0)&&c._hasPingExpired());return this.flags.volatile&&!_?aO("discard packet as the transport is not currently writable"):b?(this.notifyOutgoingListeners(f),this.packet(f)):this.sendBuffer.push(f),this.flags={},this}_registerAckCallback(t,r){var a;let o=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(o===void 0){this.acks[t]=r;return}let c=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let _=0;_<this.sendBuffer.length;_++)this.sendBuffer[_].id===t&&(aO("removing packet with ack id %d from the buffer",t),this.sendBuffer.splice(_,1));aO("event with ack id %d has timed out after %d ms",t,o),r.call(this,new Error("operation has timed out"))},o),f=e((..._)=>{this.io.clearTimeoutFn(c),r.apply(this,_)},"fn");f.withError=!0,this.acks[t]=f}emitWithAck(t,...r){return new Promise((a,o)=>{let c=e((f,_)=>f?o(f):a(_),"fn");c.withError=!0,r.push(c),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());let a={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...c)=>a!==this._queue[0]?void 0:(o!==null?a.tryCount>this._opts.retries&&(aO("packet [%d] is discarded after %d tries",a.id,a.tryCount),this._queue.shift(),r&&r(o)):(aO("packet [%d] was successfully sent",a.id),this._queue.shift(),r&&r(null,...c)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(t=!1){if(aO("draining queue"),!this.connected||this._queue.length===0)return;let r=this._queue[0];if(r.pending&&!t){aO("packet [%d] has already been sent and is waiting for an ack",r.id);return}r.pending=!0,r.tryCount++,aO("sending packet [%d] (try n\xB0%d)",r.id,r.tryCount),this.flags=r.flags,this.emit.apply(this,r.args)}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){aO("transport is open - connecting"),typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:RE.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){aO("close (%s)",t),this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(a=>String(a.id)===t)){let a=this.acks[t];delete this.acks[t],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case RE.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case RE.EVENT:case RE.BINARY_EVENT:this.onevent(t);break;case RE.ACK:case RE.BINARY_ACK:this.onack(t);break;case RE.DISCONNECT:this.ondisconnect();break;case RE.CONNECT_ERROR:this.destroy();let a=new Error(t.data.message);a.data=t.data.data,this.emitReserved("connect_error",a);break}}onevent(t){let r=t.data||[];aO("emitting event %j",r),t.id!=null&&(aO("attaching ack callback to event"),r.push(this.ack(t.id))),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){let r=this._anyListeners.slice();for(let a of r)a.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){let r=this,a=!1;return function(...o){a||(a=!0,aO("sending ack %j",o),r.packet({type:RE.ACK,id:t,data:o}))}}onack(t){let r=this.acks[t.id];if(typeof r!="function"){aO("bad ack %s",t.id);return}delete this.acks[t.id],aO("calling ack %s with %j",t.id,t.data),r.withError&&t.data.unshift(null),r.apply(this,t.data)}onconnect(t,r){aO("socket connected with id %s",t),this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){aO("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(aO("performing disconnect (%s)",this.nsp),this.packet({type:RE.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){let r=this._anyListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){let r=this._anyOutgoingListeners;for(let a=0;a<r.length;a++)if(t===r[a])return r.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let r=this._anyOutgoingListeners.slice();for(let a of r)a.apply(this,t.data)}}};e(qQr,"Socket");var jJe=qQr;function rFe(i){i=i||{},this.ms=i.min||100,this.max=i.max||1e4,this.factor=i.factor||2,this.jitter=i.jitter>0&&i.jitter<=1?i.jitter:0,this.attempts=0}e(rFe,"Backoff");rFe.prototype.duration=function(){var i=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*i);i=Math.floor(t*10)&1?i+r:i-r}return Math.min(i,this.max)|0};rFe.prototype.reset=function(){this.attempts=0};rFe.prototype.setMin=function(i){this.ms=i};rFe.prototype.setMax=function(i){this.max=i};rFe.prototype.setJitter=function(i){this.jitter=i};var m$n=uf(WPe(),1),_$n=uf(i_t(),1);var Ej=(0,_$n.default)("socket.io-client:manager"),QQr=class QQr extends m$n.Emitter{constructor(t,r){var a;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,_be(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((a=r.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new rFe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;let o=r.parser||MQr;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(Ej("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Ej("opening %s",this.uri),this.engine=new MJe(this.uri,this.opts);let r=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;let o=yZ(r,"open",function(){a.onopen(),t&&t()}),c=e(_=>{Ej("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",_),t?t(_):this.maybeReconnectOnOpen()},"onError"),f=yZ(r,"error",c);if(this._timeout!==!1){let _=this._timeout;Ej("connect attempt will timeout after %d",_);let b=this.setTimeoutFn(()=>{Ej("connect attempt timed out after %d",_),o(),c(new Error("timeout")),r.close()},_);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(o),this.subs.push(f),this}connect(t){return this.open(t)}onopen(){Ej("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let t=this.engine;this.subs.push(yZ(t,"ping",this.onping.bind(this)),yZ(t,"data",this.ondata.bind(this)),yZ(t,"error",this.onerror.bind(this)),yZ(t,"close",this.onclose.bind(this)),yZ(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){mbe(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){Ej("error",t),this.emitReserved("error",t)}socket(t,r){let a=this.nsps[t];return a?this._autoConnect&&!a.active&&a.connect():(a=new jJe(this,t,r),this.nsps[t]=a),a}_destroy(t){let r=Object.keys(this.nsps);for(let a of r)if(this.nsps[a].active){Ej("socket %s is still active, skipping close",a);return}this._close()}_packet(t){Ej("writing packet %j",t);let r=this.encoder.encode(t);for(let a=0;a<r.length;a++)this.engine.write(r[a],t.options)}cleanup(){Ej("cleanup"),this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){Ej("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var a;Ej("closed due to %s",t),this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let t=this;if(this.backoff.attempts>=this._reconnectionAttempts)Ej("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let r=this.backoff.duration();Ej("will wait %dms before reconnect attempt",r),this._reconnecting=!0;let a=this.setTimeoutFn(()=>{t.skipReconnect||(Ej("attempting reconnect"),this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(Ej("reconnect attempt error"),t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):(Ej("reconnect success"),t.onreconnect())}))},r);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){let t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}};e(QQr,"Manager");var UJe=QQr;var g$n=uf(i_t(),1);var h$n=(0,g$n.default)("socket.io-client"),o_t={};function u_t(i,t){typeof i=="object"&&(t=i,i=void 0),t=t||{};let r=ZQn(i,t.path||"/socket.io"),a=r.source,o=r.id,c=r.path,f=o_t[o]&&c in o_t[o].nsps,_=t.forceNew||t["force new connection"]||t.multiplex===!1||f,b;return _?(h$n("ignoring socket cache for %s",a),b=new UJe(a,t)):(o_t[o]||(h$n("new io instance for %s",a),o_t[o]=new UJe(a,t)),b=o_t[o]),r.query&&!t.query&&(t.query=r.queryKey),b.socket(r.path,t)}e(u_t,"lookup");Object.assign(u_t,{Manager:UJe,Socket:jJe,io:u_t,connect:u_t});var sVt={URL:"http://localhost:3000",NAMESPACE:"auto-recovery",RECONNECTION_ATTEMPTS:5,RECONNECTION_DELAY:1e3},$Qr=class $Qr{constructor(t={}){this.socket=null;this.connectionState="disconnected";this.connectionPromise=null;this.resolution=null;this.options=t,this.url=t.url||sVt.URL,this.namespace=t.namespace||sVt.NAMESPACE,this.initializationPromise=this.createInitializationPromise()}createInitializationPromise(){return new Promise((t,r)=>{this.resolveInitialization=a=>t(a),this.rejectInitialization=a=>r(a)}).then(t=>(this.resolution=t,this.log("\u2705 Client initialization successful"),t),t=>{throw this.resolution=t,this.logError("\u274C Client initialization failed:",t),t}).finally(()=>{this.disconnect()})}defineHandlers(t){return t}async startSession(t,r){try{return await this.connect(),this.emit(t,r,a=>{this.resolveInitialization(a)}),this.initializationPromise}catch(a){throw this.logError("\u274C Failed to start session:",a),this.rejectInitialization(a),a}}isConnected(){var t;return((t=this.socket)==null?void 0:t.connected)||!1}getConnectionState(){return this.connectionState}success(t){return{success:!0,data:t}}error(t){return{success:!1,error:t}}log(t,...r){this.options.verbose&&console.log(`[${this.namespace}] ${t}`,...r)}logError(t,...r){this.options.verbose&&console.error(`[${this.namespace}] ${t}`,...r)}async connect(){var t;if(this.connectionPromise)return this.connectionPromise;if(this.connectionState==="connected"&&((t=this.socket)!=null&&t.connected))return Promise.resolve();this.connectionState="connecting",this.connectionPromise=this.establishConnection();try{await this.connectionPromise,this.connectionState="connected"}catch(r){throw this.connectionState="disconnected",this.connectionPromise=null,r}return this.connectionPromise}establishConnection(){return new Promise((t,r)=>{let a=!1;try{let o=`${this.url}/${this.namespace}`;this.log(`\u{1F517} Connecting to socket at: ${o}`),this.socket=u_t(o,{autoConnect:!0,reconnection:!0,reconnectionAttempts:sVt.RECONNECTION_ATTEMPTS,reconnectionDelay:sVt.RECONNECTION_DELAY,...this.options.path&&{path:this.options.path}}),this.setupConnectionHandlers(t,r,a)}catch(o){this.logError("\u274C Failed to create socket connection:",o),a||r(o)}})}setupConnectionHandlers(t,r,a){if(!this.socket)return;let o={resolve:t,reject:r,connectionResolved:a};this.socket.on("connect",()=>this.handleConnect(o)),this.socket.on("reconnect",()=>this.handleReconnect()),this.socket.on("connect_error",c=>this.handleConnectError(c,o)),this.socket.on("disconnect",c=>this.handleDisconnect(c,o)),this.socket.io.on("reconnect_attempt",c=>this.handleReconnectAttempt(c)),this.socket.io.on("reconnect_error",c=>this.handleReconnectError(c)),this.socket.io.on("reconnect_failed",()=>this.handleReconnectFailed(o))}handleConnect(t){this.log("\u2705 Connected to socket"),this.connectionState="connected",this.setupEventHandlers(),t.connectionResolved||(t.connectionResolved=!0,t.resolve())}handleReconnect(){this.log("\u2705 Reconnected to socket"),this.connectionState="connected"}handleConnectError(t,r){var a;this.logError("\u274C Connection error:",t),this.connectionState="disconnected",!r.connectionResolved&&((a=this.socket)==null?void 0:a.disconnected)!==!1&&(r.connectionResolved=!0,r.reject(t))}handleDisconnect(t,r){this.log("\u{1F50C} Disconnected from socket:",t),this.connectionState="disconnected",this.resolution===null&&t==="io server disconnect"&&this.rejectInitialization(t),!r.connectionResolved&&(t==="io server disconnect"||t==="transport close")&&(r.connectionResolved=!0,r.reject(new Error(t)))}handleReconnectAttempt(t){this.log(`\u{1F504} Reconnection attempt #${t}`),this.connectionState="reconnecting"}handleReconnectError(t){this.logError("\u274C Reconnection attempt failed:",t)}handleReconnectFailed(t){this.logError("\u274C All reconnection attempts failed"),this.connectionState="disconnected",this.resolution===null&&this.rejectInitialization("All reconnection attempts failed"),t.connectionResolved||(t.connectionResolved=!0,t.reject(new Error("All reconnection attempts failed")))}setupEventHandlers(){if(!this.socket){this.logError("\u274C Cannot setup event handlers: socket is null");return}this.log("\u2705 Setting up event handlers"),this.socket.on("__call",this.handleGatewayCall.bind(this))}async handleGatewayCall(t,r){this.log(`\u{1F4E5} Gateway called method: ${t.key} with args:`,t.args);try{let a=this.validateGatewayCall(t);if(a){r(a);return}let o=this.handlers[t.key];if(!o){let f=`No handler registered for method: ${t.key}`;this.logError(`\u274C ${f}`),r(this.error(f));return}let c=await o(...t.args);r(this.success(c))}catch(a){this.logError("\u274C Error handling gateway call:",a),r(this.error(a.message||"Unknown error occurred"))}}validateGatewayCall(t){return t.key?Array.isArray(t.args)?null:(this.logError("\u274C Received call with invalid args"),this.error("Args must be an array")):(this.logError("\u274C Received call with undefined key"),this.error("Key is undefined"))}emit(t,r,a){if(!this.socket){this.logError("\u274C Cannot emit: socket is null");return}this.log(`\u{1F4E4} Emitting event: ${t}`),this.socket.emit(t,r,o=>{a(o)})}disconnect(){this.connectionState!=="shutting_down"&&(this.connectionState="shutting_down",this.log("\u{1F50C} Initiating disconnect"),this.socket&&(this.socket.disconnect(),this.socket=null),this.connectionPromise=null,this.connectionState="disconnected",this.log("\u2705 Disconnected successfully"))}};e($Qr,"AbstractClient");var oVt=$Qr;var y$n,v$n,b$n,x$n,A$n,E$n,cVt=class cVt extends(E$n=oVt,A$n=Aj.names.getState,x$n=Aj.names.invokeCode,b$n=Aj.names.final_result,v$n=Aj.names.wait,y$n=Aj.names.getElementScreenshot,E$n){constructor(r,a){super({verbose:o_.testRun.autoRecovery.verboseConsoleLog,url:a.config.apiURL,namespace:"auto-recovery",path:"/auto-recovery/socket.io"});this.utils=r;this.initData=a;this.stepsThoughts=[];this.handlers=this.defineHandlers({callLangChainTool:e(async(r,a)=>{if(!this[r])throw new Error(`Tool ${r} not found`);return a.thought&&this.stepsThoughts.push(a.thought),await this[r].invoke(a)},"callLangChainTool"),getStatus:e(async r=>({sessionId:r,status:"active",data:{message:"Status retrieved successfully"}}),"getStatus")});this[A$n]=n7e.buildTool(Aj,Aj.names.getState,async r=>this.getStateHandler(r));this[x$n]=n7e.buildTool(Aj,Aj.names.invokeCode,async r=>this.invokeCodeHandler(r));this[b$n]=n7e.buildTool(Aj,Aj.names.final_result,async r=>this.finalResultHandler(r));this[v$n]=n7e.buildTool(Aj,Aj.names.wait,async r=>this.waitHandler(r));this[y$n]=n7e.buildTool(Aj,Aj.names.getElementScreenshot,async r=>this.getElementScreenshotHandler(r))}async init(){let r={...this.initData,version:Aj.version};return await this.startSession("initialize",r).catch(a=>{this.utils.analytics.ARError({error:a.message});let o="Auto-Recovery Failed";return this.utils.createChecksumStep({title:o,withError:!0}),{finalThought:o,stepsThoughts:[],result:"failed"}})}static async build(r){let a=await r.buildFallbackData();return new cVt(r,a)}async invokeCodeHandler(r){let a;return await this.utils.runConditionallyWithinStep(!0,r.thought||"Invoke Code",async()=>{try{let o=await this.utils.invokeCode(r.code);this.utils.createChecksumStep({title:"Code Invoked Successfully"}),a={success:!0,invokeCodeResult:`invokeCodeResult: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}catch(o){this.utils.createChecksumStep({title:"Error while invoking code",withError:!0}),a={success:!1,invokeCodeResult:`Error while invoking code: ${o}`,appState:(await this.utils.buildFallbackData()).applicationState}}}),a}async getStateHandler(r){return this.utils.createChecksumStep({title:r.thought}),this.utils.analytics.ARGetState(r.thought),{success:!0,appState:(await this.utils.buildFallbackData()).applicationState}}finalResultHandler(r){let a=r.result==="pass",o=this.initData.type==="assertion"?a?"soft_assertion":"hard_assertion":a?"finish":"failed";this.utils.analytics.ARFinalResult({finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts});let c={finalThought:r.thought,result:o,stepsThoughts:this.stepsThoughts};this.utils.addAutoRecoveryErrorToReport(r.thought,a),this.resolveInitialization(c)}async getElementScreenshotHandler(r){return{success:!0,screenshot:await this.utils.getScreenshotForElement(r.checksumId)}}async waitHandler(r){await new Promise(o=>setTimeout(o,r.time||5e3));let a=await this.utils.buildFallbackData();return{success:!0,waitResult:`waited for ${r.time} seconds, the current HTML of the application after the wait is: ${a.applicationState.reducedHTML}`}}};e(cVt,"AutoRecoveryAgent");var uVt=cVt;var C$n=require("fs"),w$n=uf(require("path"));var VQr=class VQr extends $H{constructor(r,a){let o=$H.getCurrentTestInfo();if(!o)throw new Error("TestRunAnalytics must be initialized with testInfo before FallbackAnalytics can be used");let c=$H.getCurrentInstance();if(!c)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating FallbackAnalytics");let f=c.getTestSuiteRunInfo();super(f,$H.isolatedMode,o);this.sessionId=null;this.fallbackId=r,this.fallbackType=a}updateToSessionId(r){this.sessionId!==r&&(this.sessionId=r,this.analytics&&this.analytics.alias({userId:r,previousId:this.fallbackId}))}get tableName(){return"auto_recovery"}get metadata(){return{...super.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(r){super.trackEventWithTable(r,this.metadata,this.tableName)}setFallbackType(r){this.fallbackType=r}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(r){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...r})}ARGetState(r){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:r})}ARInvokeCode(r,a){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:r,code:a})}ARFinalResult(r){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...r})}autoRecoveryDisconnect(r){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...r})}ARFinish(r){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...r})}ARError(r){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...r})}};e(VQr,"AutoRecoveryAnalytics");var lVt=VQr;var nFe=class nFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:b,variableStore:C}){this.page=t,this.evaluateWithChecksum=r,this.checksumPage=a,this.pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=b,this.variableStore=C,this._analytics=new lVt(this.sessionId,b.type)}static async start(t){return new nFe({...t})}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,b=!0)=>{if(!_)return"";try{return(0,C$n.readFileSync)(_,b?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:b,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:b,rrwebId:C}},t)}async getReducedHtml(t=nFe.currentChecksumId){let{reducedHTML:r,currentChecksumId:a}=await this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return nFe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async buildFallbackData(){let{reducedHTML:t,currentChecksumId:r}=await this.getReducedHtml();return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:t,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:r,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.runtimeFallbackData.testIdentification.testId,variableStore:this.variableStore.reduce((a,o)=>(a[`variablesStore.${o.name}`]=o.value,a),{}),arConfig:this.arConfig}}async scrollToElement(t){t&&await this.pageInteractor.scrollElementIntoViewByChecksumId(t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=w$n.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return N$e.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],b=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,C=(R=t.match(b))==null?void 0:R[1];if(!C)throw new Error("Checksum ID not found in the code");let w=await this.getSelectionDataForChecksumId(C);if(!(w!=null&&w.locator)||w.invalid)throw new Error(`Locator or selector not found for checksumId: ${C}`);a=a.replace(b,w.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(W=>W.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:C,locator:w.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
1828
1828
  ${t}`)}get createChecksumStep(){return t=>this.checksumPage.createChecksumStep(t)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(t,r,a)=>this.checksumPage.runConditionallyWithinStep(t,r,a)}async getScreenshotForElement(t){var r;try{let a=await this.getSelectionDataForChecksumId(t);if(!a)throw new Error(`Locator not found for checksumId: ${t}`);let o=((r=this.arConfig.modelConfig)==null?void 0:r.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(a.selector).screenshot({type:o})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${t}`)}}get analytics(){return this._analytics}};e(nFe,"AutoRecoveryRuntimeIteratorUtils"),nFe.currentChecksumId="0";var pVt=nFe;var qJe=class qJe extends Lme{init(t){var r;return this.initializationData=t,(r=this.initializationData.fallbackConfig).arMode??(r.arMode="fast"),this}canResolve(t){return!0}get failingThought(){return this.initializationData.thoughts.failing}getRecoveryAttemptTitle(){switch(this.initializationData.type){case"action":return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`;case"assertion":return`Checksum Auto-Recovery: trying to verify assertion "${this.failingThought}"...`}}static async registerSession(t){let r=t.config.apiURL,a=t.config.apiKey;return await(await fetch(`${r}${qJe.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:a},body:JSON.stringify({appName:t.testIdentification.testFileName,fallbackData:t})})).json()}async prepareSession(t){let r=await qJe.registerSession(this.initializationData);this.utils=new pVt({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:r.arConfig,sessionId:r.sessionId,runtimeFallbackData:this.initializationData,fallbackData:t,variableStore:this.variables});try{this.agent=await uVt.build(this.utils)}catch{throw new Error("Failed to prepare ARFallback")}}async resolve(t){let r=Date.now();await this.prepareSession(t),this.utils.analytics.ARStart();let a=await this.agent.init();return this.utils.analytics.ARFinish({duration:Date.now()-r}),{fbResult:a.result,thought:a.finalThought,stepsThoughts:a.stepsThoughts,steps:[]}}};e(qJe,"ARFallback"),qJe.API_BASE_ROUTE="/auto-recovery";var Abe=qJe;var zQr=1e3*30;var c_t=class c_t extends Bze{constructor(r,a="normal",o,c,f,_,b,C,w,T,k,R){var W,X,ne;super(r,T,()=>this.pageInteractor);this.page=r;this.runMode=a;this.testRunAnalytics=o;this.monitorBridge=c;this.testInfo=f;this.checksumTestId=_;this.test=b;this.options=C;this.isReplMode=w;this.config=T;this.pageInteractorAPI=k;this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.pages={};this.framesMsgBroker=new n$e;this.scriptLoadWrapper=e(async(r,a)=>(!this.isTimeMachineFrame(a)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(r,a.page())),"scriptLoadWrapper");this.scriptLoadCheck=e(async r=>r.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async r=>{await r.evaluate(async({appSpecificRules:a,esraTimeout:o,sessionRecorder:c,showFrontendLogs:f,showTMSeeker:_,filesObserver:b,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T,recordOptions:k})=>{var R;(R=window.checksum)==null||R.testGenerator.init(a,{esraTimeout:o,showFrontendLogs:f,skipElementHighlighting:!0,recordOptions:k},{assertionGenerator:!1,sessionRecorder:c,filesObserver:b,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T});try{_&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:zQr,sessionRecorder:!!(!this.isTimeMachineFrame(r)&&(this.timeMachine||this.isVTG)),showFrontendLogs:o_.isDevMode,showTMSeeker:this.isTimeMachineFrame(r)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:this.isVTG&&!this.isTimeMachineFrame(r),nativeDialogObserver:this.isVTG&&!this.isTimeMachineFrame(r),assertionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),actionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),recordOptions:this.isVTG?this.getVTGRecordOptions():void 0}),Qv(`[init] init script loaded for ${r.page().url()}`)},"scriptLoadCallback");D$n(C.printLogs),this.isVTG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1,arVersion:1,visualComparison:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1},dVt(this.page)),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let B=Ebe({config:this.config,throwIfAuthFailed:!0}),U=this.getPlaywrightProjectConfig();if(this.pageInteractor=new q6e(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Qv,logError:Qv},{navigationTimeout:(W=U.use)==null?void 0:W.navigationTimeout,actionTimeout:(X=U.use)==null?void 0:X.actionTimeout,testAssetsDir:eft(Nne()),waitActionDelay:1e3},this.pageInteractorAPI,B),this.checkForActiveTracing(),this.resetFallbacks(),R&&(this.highLevelThoughts=R.highLevelThoughts??[],this.pages=R.pages??{},this.timeMachineBrowserContext=R.timeMachineBrowserContext,this.variableStore=R.variableStore),o_.testRun.timeMachine.active){let ce=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:jAn(this.checksumTestId,this.testInfo.retry)}:{};this.timeMachine=new nqt(this.framesMsgBroker,this.injectedScriptManager,{...ce,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:o_.testRun.timeMachine.headless,webProxy:(ne=f.project.use)==null?void 0:ne.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)}this.pages[this.getPageGuid(r)]=this.proxy}static async init(r,a,o,c,f,_,b,C,w=!1){_||(_=TBt(5),console.warn(`Checksum test id was not defined for test "${f.title}" and was auto-generated. Please replace - "${f.title}" with -
1829
1829
  test(defineChecksumTest("${f.title}", "${_}"), async ({ page }) => {...`)),o.addTestInfo(_,f.testId),C.options.useChecksumAI!==void 0&&typeof C.options.useChecksumAI=="boolean"&&(C.options.useChecksumAI={actions:C.options.useChecksumAI,assertions:!1,visualComparison:!1});let T=new P$e(C),k=new c_t(r,C.runMode,a,o,f,_,b,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:C.runMode!=="normal",useMockData:!1,printLogs:!1,...C.options},w,C,T,{variableStore:c});return b._checksum.expect.setPage(k),b._checksum.checksumAI.page=k,c.clearAll(),k.testRunAnalytics.testRunStart(),await k.asyncInit(),k.proxy}async asyncInit(r=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),r||await this.prepareForTestArtifacts();let a=vZ.resolve(__dirname,"mock-auto-heal-agent.js");await this.page.addInitScript({path:a})}async getPage(r){let a=this.page.context().pages()[r];if(!a)throw new Error(`Page with index ${r} not found`);return this.makePage(a)}async makePage(r){let a=this.getPageGuid(r);if(this.pages[a])return this.pages[a];let o=new c_t(r,this.runMode,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,pages:this.pages,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await o.asyncInit(!0),o.proxy}getTimeMachinePage(){var r;return(r=this.timeMachine)==null?void 0:r.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(r){var a;return r===((a=this.timeMachine)==null?void 0:a.getFrame())}shouldRecordRRwebEvents(){return o_.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}getPageGuid(r){return r._guid}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var o;let a=(o=this.getPlaywrightProjectConfig().use)==null?void 0:o.trace;this.traceMode=typeof a=="string"?a:a==null?void 0:a.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async r=>{this.injectedScriptManager.onFrameNavigated(r)})}checksumSelector(r){return this.checksumStepId=r,this.options.useChecksumSelectors&&this.setSelectorFallback(r),this.proxy}checksumAI(r,a,o){let c=this.addNewThought(r,"action",!!a);return a&&typeof a=="function"?this.test.step(r,async f=>{var _;try{return o!=null&&o.withDialog&&this.pageInteractor.listenToDialog(),await a()}catch(b){if(c.children=[],!this.options.useChecksumAI.actions||o!=null&&o.withDialog||o!=null&&o.skipAIFallback)throw b;this.setAIFallback(r,"action");try{return await this.initiateFallbackSequence({type:"action",error:b,method:void 0,args:[],testInfo:this.testInfo,step:f},{fallbackTypes:[Dve,Abe]})}catch(C){throw this.testRunAnalytics.testRunError({failedThought:r,error:(C==null?void 0:C.message)||"Unknown error"}),C}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(_=this.currentThought)==null?void 0:_.parent}}):(this.options.useChecksumAI.actions&&this.setAIFallback(r,"action"),this.proxy)}resolveAssetsFolder(r){return r.map(a=>vZ.join(eft(Nne()),a))}getRuntimeOptions(){return this.options}addPwAnnotation(r){this.testInfo.annotations.push({type:r.type,description:`
1830
- ${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let b=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=b}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:zQr};this.pushFallback(this.constructFallback(Cdt).init(a)),this.pushFallback(this.constructFallback(Adt).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Edt).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:zQr}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===2,c=e(()=>{var R,B;let b=this.buildThoughtsChainForFallback(),C={title:this.testInfo.title},w={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:b.slice(0,-1),failing:r,next:b.slice(1)},k={storyInfo:C,testIdentification:w,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Abe).init(k)},"createArFallback"),f=e(()=>{var b,C;return this.constructFallback(Dve).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:o_.benchmark,arMode:(b=this.options.useChecksumAI)==null?void 0:b.arMode,overrideOptions:(C=this.options.useChecksumAI)==null?void 0:C.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(c()):this.pushFallback(f()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:o_.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await pD(c,r.timeout),_=Date.now()-o;r instanceof Dve&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Abe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let b=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${b}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${b}`,withError:!0}),new Mft(f.fbResult);if(r instanceof Dve&&f.summary&&this.arSummaries.push(f.summary),r instanceof Abe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${b}`}),f.steps.length===1){let C=f.steps[0];C.thought&&(this.currentThought.thought=C.thought)}else this.currentThought.children=f.steps.map((C,w)=>({id:`${this.currentThought.id}.${w+1}`,thought:C.thought,type:C.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){Qv(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof Dve);if(o){let _=o.getFailedThought(),b=this.variableStore.getActiveVariables();this.fallbacks.forEach(C=>{C.setThought(_),C.setVariables(b)})}let c=this.fallbacks.find(_=>_ instanceof Abe);if(c){let _=c.failingThought;this.fallbacks.forEach(b=>{b instanceof Abe&&b.setVariables(this.variableStore.getActiveVariables()),b.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((b,C)=>b||_ instanceof C,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let b=_==null?void 0:_.toString();b&&console.log(`Using ${b}`);let C;try{let w=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));C=!0}catch(w){if(C=!1,r.withChecksumAI&&w.message==="fetch failed")throw new Error(h4e);w instanceof Mft&&w.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),b&&console.log(`Failed to use ${b}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(wdt).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:vZ.basename(r)})}catch(r){Qv("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return Qv("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[wdt,Edt,Cdt,Adt,Dve];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"})}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=MAn(IBt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?UAn(IBt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=P3r(IBt(this.testInfo.file)),a=vZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Cz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=vZ.join(r,"tmp");(0,Cz.existsSync)(o)||(0,Cz.mkdirSync)(o);let c=(0,Cz.readFileSync)(a),f=await(0,S$n.loadAsync)(c);for(let b of Object.keys(f.files)){let C=await f.file(b).async("string"),w=vZ.join(o,b);(0,Cz.writeFileSync)(w,C),this.unzippedHarData.push(w)}let _=vZ.join(o,"test.har");if(!(0,Cz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Cz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Cz.rmSync)(vZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){Qv("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=vZ.join(YIe(Nne()),"settings.asr");if(!(0,Cz.existsSync)(r)){Qv("Could not find ASR file");return}let{ungzip:a}=I3r();try{let o=await a((0,Cz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){Qv("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(c_t,"RuntimePage");var fVt=c_t;var hVt=require("fs");var u7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},HTs={defaultMerge:u7e.defaultMerge};function zba(i,t){return t}e(zba,"defaultMetaDataUpdater");function Jba(i,t){return i.filter(r=>r!==void 0)}e(Jba,"defaultFilterValues");var T$n;(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(T$n||(T$n={}));function k$n(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:Gba(i)?1:i instanceof Set?3:i instanceof Map?4:5}e(k$n,"getObjectType");function Wba(i){let t=new Set;for(let r of i)for(let a of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(a);return t}e(Wba,"getKeys");function Hba(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}e(Hba,"objectHasProperty");function P$n(i){var a;let t=0,r=(a=i[0])==null?void 0:a[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var o;do{if(r===void 0)return{done:!0,value:void 0};let c=r.next();if(c.done===!0){t+=1,r=(o=i[t])==null?void 0:o[Symbol.iterator]();continue}return{done:!1,value:c.value}}while(!0)}}}}}e(P$n,"getIterableOfIterables");var I$n=["[object Object]","[object Module]"];function Gba(i){if(!I$n.includes(Object.prototype.toString.call(i)))return!1;let{constructor:t}=i;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!I$n.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}e(Gba,"isRecord");function Kba(i,t,r){let a={};for(let o of Wba(i)){let c=[];for(let b of i)Hba(b,o)&&c.push(b[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=F$n(c,t,f);_!==u7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}e(Kba,"mergeRecords$1");function Yba(i){return i.flat()}e(Yba,"mergeArrays$1");function Xba(i){return new Set(P$n(i))}e(Xba,"mergeSets$1");function Zba(i){return new Map(P$n(i))}e(Zba,"mergeMaps$1");function exa(i){return i.at(-1)}e(exa,"mergeOthers$1");var mVt={mergeRecords:Kba,mergeArrays:Yba,mergeSets:Xba,mergeMaps:Zba,mergeOthers:exa};function _Vt(...i){return txa({})(...i)}e(_Vt,"deepmerge");function txa(i,t){let r=rxa(i,a);function a(...o){return F$n(o,r,t)}return e(a,"customizedDeepmerge"),a}e(txa,"deepmergeCustom");function rxa(i,t){return{defaultMergeFunctions:mVt,mergeFunctions:{...mVt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(mVt,r)).map(([r,a])=>a===!1?[r,mVt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??zba,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??Jba,actions:u7e}}e(rxa,"getUtils");function F$n(i,t,r){var c;let a=((c=t.filterValues)==null?void 0:c.call(t,i,r))??i;if(a.length===0)return;if(a.length===1)return JQr(a,t,r);let o=k$n(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(k$n(a[f])!==o)return JQr(a,t,r)}switch(o){case 1:return nxa(a,t,r);case 2:return ixa(a,t,r);case 3:return axa(a,t,r);case 4:return sxa(a,t,r);default:return JQr(a,t,r)}}e(F$n,"mergeUnknowns");function nxa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}e(nxa,"mergeRecords");function ixa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}e(ixa,"mergeArrays");function axa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}e(axa,"mergeSets");function sxa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}e(sxa,"mergeMaps");function JQr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}e(JQr,"mergeOthers");var N$n=!1;function D$n(i){N$n=i}e(D$n,"setLogToConsole");function Qv(...i){N$n&&console.log(...i)}e(Qv,"log");async function E8n(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():pD(o(),a,"Execution timeout")}e(E8n,"executePlaywrightMethodWithTimeout");function l_t(i,{role:t,environment:r}={},a=!1){var _,b;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:C})=>r===C)),o||(o=(b=i.environments)==null?void 0:b.find(({default:C})=>C)),!o)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let c=o.users,f;if(c&&(t!==void 0&&(f=c.find(C=>C.role===t)),f||(f=c.find(C=>C.default))),!f)throw new Error(`User not found. Please make sure the users array for the "${o.name}" environment is properly defined in the checksum.config.ts file.`);if(r&&o.name!==r){if(a)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&f.role!==t){if(a)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:o,user:f}}e(l_t,"resolveEnvironment");function oxa(i){let t=`${i??Nne()}/login.ts`;if(!(0,hVt.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}e(oxa,"requireLogin");async function uxa(i,t,{environment:r,user:a,config:o}){try{let c=e(()=>t(i,{environment:r,user:a,config:o}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${a!=null&&a.role?` using ${a.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,c):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
1830
+ ${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let b=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=b}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:zQr};this.pushFallback(this.constructFallback(Cdt).init(a)),this.pushFallback(this.constructFallback(Adt).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Edt).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:zQr}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===1,c=e(()=>{var R,B;let b=this.buildThoughtsChainForFallback(),C={title:this.testInfo.title},w={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:b.slice(0,-1),failing:r,next:b.slice(1)},k={storyInfo:C,testIdentification:w,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Abe).init(k)},"createArFallback"),f=e(()=>{var b,C;return this.constructFallback(Dve).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:o_.benchmark,arMode:(b=this.options.useChecksumAI)==null?void 0:b.arMode,overrideOptions:(C=this.options.useChecksumAI)==null?void 0:C.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(f()):this.pushFallback(c()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:o_.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await pD(c,r.timeout),_=Date.now()-o;r instanceof Dve&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Abe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let b=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${b}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${b}`,withError:!0}),new Mft(f.fbResult);if(r instanceof Dve&&f.summary&&this.arSummaries.push(f.summary),r instanceof Abe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${b}`}),f.steps.length===1){let C=f.steps[0];C.thought&&(this.currentThought.thought=C.thought)}else this.currentThought.children=f.steps.map((C,w)=>({id:`${this.currentThought.id}.${w+1}`,thought:C.thought,type:C.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){Qv(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof Dve);if(o){let _=o.getFailedThought(),b=this.variableStore.getActiveVariables();this.fallbacks.forEach(C=>{C.setThought(_),C.setVariables(b)})}let c=this.fallbacks.find(_=>_ instanceof Abe);if(c){let _=c.failingThought;this.fallbacks.forEach(b=>{b instanceof Abe&&b.setVariables(this.variableStore.getActiveVariables()),b.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((b,C)=>b||_ instanceof C,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let b=_==null?void 0:_.toString();b&&console.log(`Using ${b}`);let C;try{let w=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));C=!0}catch(w){if(C=!1,r.withChecksumAI&&w.message==="fetch failed")throw new Error(h4e);w instanceof Mft&&w.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),b&&console.log(`Failed to use ${b}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(wdt).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:vZ.basename(r)})}catch(r){Qv("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return Qv("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[wdt,Edt,Cdt,Adt,Dve];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"})}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=MAn(IBt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?UAn(IBt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=P3r(IBt(this.testInfo.file)),a=vZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Cz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=vZ.join(r,"tmp");(0,Cz.existsSync)(o)||(0,Cz.mkdirSync)(o);let c=(0,Cz.readFileSync)(a),f=await(0,S$n.loadAsync)(c);for(let b of Object.keys(f.files)){let C=await f.file(b).async("string"),w=vZ.join(o,b);(0,Cz.writeFileSync)(w,C),this.unzippedHarData.push(w)}let _=vZ.join(o,"test.har");if(!(0,Cz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Cz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Cz.rmSync)(vZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){Qv("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=vZ.join(YIe(Nne()),"settings.asr");if(!(0,Cz.existsSync)(r)){Qv("Could not find ASR file");return}let{ungzip:a}=I3r();try{let o=await a((0,Cz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){Qv("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(c_t,"RuntimePage");var fVt=c_t;var hVt=require("fs");var u7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},HTs={defaultMerge:u7e.defaultMerge};function zba(i,t){return t}e(zba,"defaultMetaDataUpdater");function Jba(i,t){return i.filter(r=>r!==void 0)}e(Jba,"defaultFilterValues");var T$n;(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(T$n||(T$n={}));function k$n(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:Gba(i)?1:i instanceof Set?3:i instanceof Map?4:5}e(k$n,"getObjectType");function Wba(i){let t=new Set;for(let r of i)for(let a of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(a);return t}e(Wba,"getKeys");function Hba(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}e(Hba,"objectHasProperty");function P$n(i){var a;let t=0,r=(a=i[0])==null?void 0:a[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var o;do{if(r===void 0)return{done:!0,value:void 0};let c=r.next();if(c.done===!0){t+=1,r=(o=i[t])==null?void 0:o[Symbol.iterator]();continue}return{done:!1,value:c.value}}while(!0)}}}}}e(P$n,"getIterableOfIterables");var I$n=["[object Object]","[object Module]"];function Gba(i){if(!I$n.includes(Object.prototype.toString.call(i)))return!1;let{constructor:t}=i;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!I$n.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}e(Gba,"isRecord");function Kba(i,t,r){let a={};for(let o of Wba(i)){let c=[];for(let b of i)Hba(b,o)&&c.push(b[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=F$n(c,t,f);_!==u7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}e(Kba,"mergeRecords$1");function Yba(i){return i.flat()}e(Yba,"mergeArrays$1");function Xba(i){return new Set(P$n(i))}e(Xba,"mergeSets$1");function Zba(i){return new Map(P$n(i))}e(Zba,"mergeMaps$1");function exa(i){return i.at(-1)}e(exa,"mergeOthers$1");var mVt={mergeRecords:Kba,mergeArrays:Yba,mergeSets:Xba,mergeMaps:Zba,mergeOthers:exa};function _Vt(...i){return txa({})(...i)}e(_Vt,"deepmerge");function txa(i,t){let r=rxa(i,a);function a(...o){return F$n(o,r,t)}return e(a,"customizedDeepmerge"),a}e(txa,"deepmergeCustom");function rxa(i,t){return{defaultMergeFunctions:mVt,mergeFunctions:{...mVt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(mVt,r)).map(([r,a])=>a===!1?[r,mVt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??zba,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??Jba,actions:u7e}}e(rxa,"getUtils");function F$n(i,t,r){var c;let a=((c=t.filterValues)==null?void 0:c.call(t,i,r))??i;if(a.length===0)return;if(a.length===1)return JQr(a,t,r);let o=k$n(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(k$n(a[f])!==o)return JQr(a,t,r)}switch(o){case 1:return nxa(a,t,r);case 2:return ixa(a,t,r);case 3:return axa(a,t,r);case 4:return sxa(a,t,r);default:return JQr(a,t,r)}}e(F$n,"mergeUnknowns");function nxa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}e(nxa,"mergeRecords");function ixa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}e(ixa,"mergeArrays");function axa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}e(axa,"mergeSets");function sxa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}e(sxa,"mergeMaps");function JQr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===u7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}e(JQr,"mergeOthers");var N$n=!1;function D$n(i){N$n=i}e(D$n,"setLogToConsole");function Qv(...i){N$n&&console.log(...i)}e(Qv,"log");async function E8n(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():pD(o(),a,"Execution timeout")}e(E8n,"executePlaywrightMethodWithTimeout");function l_t(i,{role:t,environment:r}={},a=!1){var _,b;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:C})=>r===C)),o||(o=(b=i.environments)==null?void 0:b.find(({default:C})=>C)),!o)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let c=o.users,f;if(c&&(t!==void 0&&(f=c.find(C=>C.role===t)),f||(f=c.find(C=>C.default))),!f)throw new Error(`User not found. Please make sure the users array for the "${o.name}" environment is properly defined in the checksum.config.ts file.`);if(r&&o.name!==r){if(a)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&f.role!==t){if(a)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:o,user:f}}e(l_t,"resolveEnvironment");function oxa(i){let t=`${i??Nne()}/login.ts`;if(!(0,hVt.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}e(oxa,"requireLogin");async function uxa(i,t,{environment:r,user:a,config:o}){try{let c=e(()=>t(i,{environment:r,user:a,config:o}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${a!=null&&a.role?` using ${a.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,c):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
1831
1831
  `,c),c}}e(uxa,"proceedWithLogin");function Ebe(i){let{config:t,folder:r,throwIfAuthFailed:a}=i,o=oxa(r);return async(c,{role:f,environment:_}={})=>{let{environment:b,user:C}=l_t(t,{role:f,environment:_},i.throwIfEnvInfoInvalid);if(a&&!C)throw new Error("Could not find user credentials matching the provided role and/or environment");await uxa(c,o,{environment:b,user:C,config:t})}}e(Ebe,"makeUnboundLogin");function O$n(i,{environmentName:t,userRole:r}){let a=Ebe(i);return o=>a(o,{environment:t,role:r})}e(O$n,"makeBoundLogin");var QJe;function lqt(){if(QJe)return QJe;try{let i=(0,hVt.existsSync)(`${Nne()}/checksum.config.ts`)?"checksum.config.ts":(0,hVt.existsSync)(`${Nne()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(i)return gVt(require(`${Nne()}/${i}`).default)}catch{console.warn("Could not find checksum config file, will run with defaults")}return gVt()}e(lqt,"loadChecksumConfig");function gVt(i={}){var r,a,o,c;let t={apiKey:void 0,runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return((a=(r=i.options)==null?void 0:r.useChecksumAI)==null?void 0:a.visualComparison)===void 0&&((c=(o=i.options)==null?void 0:o.useChecksumAI)!=null&&c.assertions)&&(i.options.useChecksumAI.visualComparison=!0),QJe=_Vt(t,i),o_.testRun.disableAutoRecovery&&(QJe.options.useChecksumAI={actions:!1,assertions:!1,visualComparison:!1}),o_.testRun.disableHostReports&&(QJe.options.hostReports=!1),QJe}e(gVt,"getChecksumConfig");function dVt(i){let t=e(r=>{r.on("dialog",a=>{})},"makeDialogHandler");i.context().pages().forEach(t),i.context().on("page",r=>{t(r)})}e(dVt,"preventDialogAutoDismissal");var h4e="Checksum failed connecting to the server";var qce=class qce{constructor(t){this.workerInfo=t;this.hasMonitor=!1;qce.monitorAgentPort?this.hasMonitor=!0:Qv("CHECKSUM_UPLOAD_AGENT_PORT is not defined"),this.sendPlaywrightConfig()}addAsset(t){this.signalUpload(t,["trace","har","rrweb-recording"].includes(t.type))}addChecksumTestMetadata(t){let r={type:"checksumTestMetadata",payload:t};this.sendMessage(r)}addTestInfo(t,r){this.sendMessage({type:"testInfo",payload:{checksumTestId:t,pwTestId:r}})}addSingleTestStats(t,r){this.sendMessage({type:"testStats",payload:{passed:t,healed:r}})}sendPlaywrightConfig(){qce.playwrightConfigSent||(this.sendMessage({type:"playwrightConfig",payload:this.buildPlaywrightConfig()}),qce.playwrightConfigSent=!0)}buildPlaywrightConfig(){let{use:t,testDir:r,testMatch:a,testIgnore:o,timeout:c,outputDir:f,retries:_}=this.workerInfo.project,{reporter:b,configFile:C,projects:w}=this.workerInfo.config,T=Object.keys(w).filter(k=>[t,r,a,o,c,f,_].includes(k)).reduce((k,R)=>({...k,[R]:w[R]}),{});return{reporter:b,configFile:C,filteredProjects:T,use:t,testDir:r,testMatch:a,testIgnore:o,timeout:c,outputDir:f,retries:_}}sendMessage(t){if(this.hasMonitor)return fetch(`${qce.monitorAgentHost}:${qce.monitorAgentPort}`,{method:"POST",body:JSON.stringify(t)}).catch(r=>{Qv("Failed to send message to test run monitor",t,r)})}signalUpload(t,r=!1){return this.sendMessage({type:"asset",payload:t,watch:r})}};e(qce,"TestRunMonitorBridge"),qce.monitorAgentHost="http://localhost",qce.monitorAgentPort=process.env.CHECKSUM_UPLOAD_AGENT_PORT,qce.playwrightConfigSent=!1;var yVt=qce;var cxa=e(()=>{let t=new Error().stack.split(`
1832
1832
  `).find(r=>r.includes(".checksum.spec.ts"));if(t)return{lineNumber:parseInt(t.split(":")[1]),columnNumber:parseInt(t.split(":")[2])}},"findCodeLocationFromStackTrace"),WQr=class WQr{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let t in this.store)Object.prototype.hasOwnProperty.call(this.store,t)&&delete this.store[t];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(t=>this.store[t])}setVariable(t,r){this.store[t]={name:t,value:r,type:r instanceof Function?"RandomValueGenerator":"FillValue"}}set(t,r,a){if(typeof r!="string")return!1;let o=cxa();return t.store[r]={name:r,value:a,type:a instanceof Function?"RandomValueGenerator":"FillValue",...o,line:""},!0}get(t,r){var a;if(r in t)return t[r];if(!(r in t.store))throw new Error(`Variable ${r} is not defined`);return t.activeVariablesSet.add(r),(a=t.store[r])==null?void 0:a.value}};e(WQr,"VariableStore");var $Je=WQr;var Amn=require("crypto");var c7e=e(i=>i.name==="up"||i.name==="k"||i.ctrl&&i.name==="p","isUpKey"),VJe=e(i=>i.name==="down"||i.name==="j"||i.ctrl&&i.name==="n","isDownKey"),B$n=e(i=>i.name==="space","isSpaceKey"),zJe=e(i=>i.name==="backspace","isBackspaceKey"),vVt=e(i=>"123456789".includes(i.name),"isNumberKey"),JP=e(i=>i.name==="enter"||i.name==="return","isEnterKey");var HQr=class HQr extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t==null?void 0:t.cause}};e(HQr,"AbortPromptError");var bVt=HQr,GQr=class GQr extends Error{name="CancelPromptError";message="Prompt was canceled"};e(GQr,"CancelPromptError");var xVt=GQr,KQr=class KQr extends Error{name="ExitPromptError"};e(KQr,"ExitPromptError");var AVt=KQr,YQr=class YQr extends Error{name="HookError"};e(YQr,"HookError");var EVt=YQr,XQr=class XQr extends Error{name="ValidationError"};e(XQr,"ValidationError");var l7e=XQr;var r$r=require("async_hooks");var CVt=require("async_hooks");var R$n=new CVt.AsyncLocalStorage;function lxa(i){return{rl:i,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}e(lxa,"createStore");function L$n(i,t){let r=lxa(i);return R$n.run(r,()=>{function a(o){r.handleChange=()=>{r.index=0,o()},r.handleChange()}return e(a,"cycle"),t(a)})}e(L$n,"withHooks");function iFe(){let i=R$n.getStore();if(!i)throw new EVt("[Inquirer] Hook functions can only be called from within a prompt");return i}e(iFe,"getStore");function ZQr(){return iFe().rl}e(ZQr,"readline");function e$r(i){let t=e((...r)=>{let a=iFe(),o=!1,c=a.handleChange;a.handleChange=()=>{o=!0};let f=i(...r);return o&&c(),a.handleChange=c,f},"wrapped");return CVt.AsyncResource.bind(t)}e(e$r,"withUpdates");function JJe(i){let t=iFe(),{index:r}=t,a={get(){return t.hooks[r]},set(c){t.hooks[r]=c},initialized:r in t.hooks},o=i(a);return t.index++,o}e(JJe,"withPointer");function M$n(){iFe().handleChange()}e(M$n,"handleChange");var aFe={queue(i){let t=iFe(),{index:r}=t;t.hooksEffect.push(()=>{var o,c;(c=(o=t.hooksCleanup)[r])==null||c.call(o);let a=i(ZQr());if(a!=null&&typeof a!="function")throw new l7e("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=a})},run(){let i=iFe();e$r(()=>{i.hooksEffect.forEach(t=>{t()}),i.hooksEffect.length=0})()},clearAll(){let i=iFe();i.hooksCleanup.forEach(t=>{t==null||t()}),i.hooksEffect.length=0,i.hooksCleanup.length=0}};function av(i){return JJe(t=>{let r=e(o=>{t.get()!==o&&(t.set(o),M$n())},"setFn");if(t.initialized)return[t.get(),r];let a=typeof i=="function"?i():i;return t.set(a),[a,r]})}e(av,"useState");function Qce(i,t){JJe(r=>{let a=r.get();(!Array.isArray(a)||t.some((c,f)=>!Object.is(c,a[f])))&&aFe.queue(i),r.set(t)})}e(Qce,"useEffect");var Tie=uf(p7e(),1);var $ce=uf(require("process"),1);function fxa(){return $ce.default.platform!=="win32"?$ce.default.env.TERM!=="linux":!!$ce.default.env.WT_SESSION||!!$ce.default.env.TERMINUS_SUBLIME||$ce.default.env.ConEmuTask==="{cmd::Cmder}"||$ce.default.env.TERM_PROGRAM==="Terminus-Sublime"||$ce.default.env.TERM_PROGRAM==="vscode"||$ce.default.env.TERM==="xterm-256color"||$ce.default.env.TERM==="alacritty"||$ce.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}e(fxa,"isUnicodeSupported");var Q$n={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},$$n={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},dxa={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},mxa={...Q$n,...$$n},_xa={...Q$n,...dxa},hxa=fxa(),gxa=hxa?mxa:_xa,Die=gxa,I8s=Object.entries($$n);var V$n={prefix:{idle:Tie.default.blue("?"),done:Tie.default.green(Die.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(i=>Tie.default.yellow(i))},style:{answer:Tie.default.cyan,message:Tie.default.bold,error:e(i=>Tie.default.red(`> ${i}`),"error"),defaultAnswer:e(i=>Tie.default.dim(`(${i})`),"defaultAnswer"),help:Tie.default.dim,highlight:Tie.default.cyan,key:e(i=>Tie.default.cyan(Tie.default.bold(`<${i}>`)),"key")}};function z$n(i){if(typeof i!="object"||i===null)return!1;let t=i;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(i)===t}e(z$n,"isPlainObject");function J$n(...i){let t={};for(let r of i)for(let[a,o]of Object.entries(r)){let c=t[a];t[a]=z$n(c)&&z$n(o)?J$n(c,o):o}return t}e(J$n,"deepMerge");function F8(...i){let t=[V$n,...i.filter(r=>r!=null)];return J$n(...t)}e(F8,"makeTheme");function BI({status:i="idle",theme:t}){let[r,a]=av(!1),[o,c]=av(0),{prefix:f,spinner:_}=F8(t);return Qce(()=>{if(i==="loading"){let C,w=-1,T=setTimeout(r$r.AsyncResource.bind(()=>{a(!0),C=setInterval(r$r.AsyncResource.bind(()=>{w=w+1,c(w%_.frames.length)}),_.interval)}),300);return()=>{clearTimeout(T),clearInterval(C)}}else a(!1)},[i]),r?_.frames[o]:typeof f=="string"?f:f[i==="loading"?"idle":i]??f.idle}e(BI,"usePrefix");function bZ(i,t){return JJe(r=>{let a=r.get();if(!a||a.dependencies.length!==t.length||a.dependencies.some((o,c)=>o!==t[c])){let o=i();return r.set({value:o,dependencies:t}),o}return a.value})}e(bZ,"useMemo");function kie(i){return av({current:i})[0]}e(kie,"useRef");function RI(i){let t=kie(i);t.current=i,Qce(r=>{let a=!1,o=e$r((c,f)=>{a||t.current(f,r)});return r.input.on("keypress",o),()=>{a=!0,r.input.removeListener("keypress",o)}},[])}e(RI,"useKeypress");var xVn=uf(H$n(),1),AVn=uf(bVn(),1);function d_t(i,t){return i.split(`
1833
1833
  `).flatMap(r=>(0,AVn.default)(r,t,{trim:!1,hard:!0}).split(`
@@ -2039,7 +2039,7 @@ Supported model providers are: ${f}`)}}}catch(f){if("code"in f&&f.code.includes(
2039
2039
  `)}}),r.context().on("page",c=>{c!==r&&this.setupFrontendLogging(c)})}writeConsoleMessageToLog(r,a){var w;let o=r.text(),c=r.type(),f=r.location(),_=new Date().toISOString(),b=((w=r.page())==null?void 0:w.url())||"unknown",C=`[${_}] [${c.toUpperCase()}] [${b}] ${o}`;f&&(C+=`
2040
2040
  at ${f.url}:${f.lineNumber}:${f.columnNumber}`),a.write(C+`
2041
2041
  `)}async run(r){await this.init(r),this.buildServices(r),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let r=await this.getInitialServicesData();r&&(this.actionsManager.setActions(r.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=r.storyId,r.testGenerationData&&this.userStoryService.setTestGenerationData(r.testGenerationData))}async init(r){cf.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(r),this.webDriver.registerEventListener(this),this.taskTimeMachine=new Jve(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!o_.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:o_.vtg.taskTimeMachine.taskTimeout,debugPort:o_.vtg.isSeparateProcess?o_.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:o_.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new q6e(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?cf.info(a,...o):cf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?cf.error(a,...o):cf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new P$e(this.checksumConfig)),this.testAssetsManager=new aHt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new wJt,this.settingsService=new lHt(this.checksumRoot,this.vtgInternalFilesDir),this.apiService=new lzt(this.checksumConfig),this.userStoryService=new CJt(this.apiService,this.checksumConfig),this.variableStoreService=new dHt,this.evaluatorService=new _Ht(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new szt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new gzt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new Dzt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new uzt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new hzt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:o_.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new fHt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new EJt(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 gHt,this.aiChatService=new str(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new nHt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let r=`${this.checksumRoot}/playwright.config.ts`;if((0,l3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{cf.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(r){let a=this.storageService.getLocalSavedJSONFilePath(r,this.storyId),o=this.storageService.readLocalSavedDataFromJSONFile(a);if(!o)throw new Error(`No data found in ${r} while reading from ${a}`);return{actions:o.executedActions,storyId:o.story.id}}async getInitialServicesDataFromCloud(){let a=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:o,story:c,testGenerationData:f}=a,_=await fetch(o,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!_.ok)throw new Error(`HTTP error! Status: ${_.status}`);let b=await _.json();return{actions:this.initializeTestStepsWithIds(b),storyId:a.story.id}}initializeTestStepsWithIds(r){return r.map((a,o)=>({...a,id:(0,Amn.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,Amn.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,b,C;if(((a=this.vtgTestFileRunConfig)==null?void 0:a.mode)!=="edit")return;let r=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath;r=this.storageService.readJsonFile(w),(0,l3e.rmSync)(w,{force:!0}),r=this.initializeTestStepsWithIds(r)}if((c=this.vtgTestFileRunConfig)!=null&&c.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(f=this.vtgTestFileRunConfig)==null?void 0:f.internalTestId}/info`);if(!w.ok)throw new Error(`Error fetching test generation data: ${w.statusText}`);let T=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let k=this.storageService.getLocalSavedJSONFilePath("auto-save"),R=this.storageService.readLocalSavedDataFromJSONFile(k);if(!R)throw new Error(`No data found in auto-save while reading from ${k}`);r=R==null?void 0:R.executedActions}return{actions:r,storyId:T.story.id,testGenerationData:T.testGenerationData}}catch{cf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((b=this.vtgTestFileRunConfig)!=null&&b.storyId)return{actions:r,storyId:(C=this.vtgTestFileRunConfig)==null?void 0:C.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:r=!0}={}){var o,c;await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:a}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:a.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),o_.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,f=>this.webDriver.registerTimeMachineFrame(f)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),cf.info("VTG is ready with story:",{goal:(o=this.userStoryService.getStory())==null?void 0:o.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:f,stepsData:_,appViewport:b,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,b,this.checksumRuntimeVersion,C,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(c=this.userStoryService.getStory())==null?void 0:c.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var o,c,f,_;let r=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.navigationTimeout)||3e4,a=((_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.actionTimeout)||5e3;return{navigationTimeout:r,actionTimeout:a}}getPlaywrightProxySettings(){var f,_;let r=(_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.proxy,{server:a,username:o,password:c}=r||{};if(o&&c&&a)return{username:o,password:c,server:a}}getPlaywrightViewportSettings(){var o,c;let{width:r=1280,height:a=720}=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.viewport)||{};return{width:r,height:a}}buildWebDriver(r){var c,f,_,b,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new uHt({scriptSource:o_.checksumScript.source,scriptURL:o_.checksumScript.url,scriptFile:o_.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(c=this.checksumConfig.environments.find(T=>T.default))==null?void 0:c.baseURL,useProxy:!!a,webProxy:a,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:o_.vtg.remoteDebugging,remoteDebuggingPort:o_.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:o_.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!o_.vtg.isSeparateProcess&&!((b=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&b.skipDisableWebSecurity)&&!((w=(C=this.checksumConfig.options)==null?void 0:C.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},r)}async onWebDriverContextClose(){var r,a,o;this.evaluatorService.stopListening(),(r=this.vtgTestFileRunConfig)!=null&&r.evalFilePath&&(0,l3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,l3e.rmSync)((o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(r){var c;let a=r.indexOf("--edit"),o=r.indexOf("--cloud");if(r.indexOf("--test-file")!==-1){this.vtgTestFileMode=!0,this.vtgTestFileRunConfig=JSON.parse(process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG),this.vtgMode=this.vtgTestFileRunConfig.mode,this.storyId=((c=this.vtgTestFileRunConfig)==null?void 0:c.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}a!==-1&&(this.vtgMode="edit",this.editLocationPath=r.at(a+1)),o!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r.at(o+1)),this.vtgMode==="start"&&(this.storyId=r[0])}getWebDriver(){return this.webDriver}async eval(r){return this.evaluatorService.listenForExecution(r)}};e(Emn,"VisualTestGenerator");var otr=Emn;var kvi=require("child_process"),wmn=require("net");var Ivi=require("path");var Tvi=uf(F_t());var Cmn=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:b=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await Tvi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await rA(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&dVt(T),T}catch(C){if(!f||_&&b>=_)throw console.error(`${i} failed to connect to ${t}, retries were exhausted or disabled`,C),C;return console.log(`${i} is waiting and retrying connection to ${t} on port ${r}...`),await rA(1e3),Cmn(i,t,r,a,{...o,numberOfRetries:b+1})}},"connectToPage");var Smn=class Smn{constructor(t){this.checksumConfig=t;this.isReady=!1;this.onMessage=e(async(t,r)=>{let{id:a,err:o,result:c}=await this.execute(t);r.write(this.messageParser.makeMessage(JSON.stringify({id:a,err:this.serializedErr(o),result:c})))},"onMessage");this.messageParser=new aGe(this.onMessage),this.isReadyPromise=new Promise(r=>{this.isReadyResolve=r}),this.routeInterceptor=new fWe({completeOriginHeader:!0})}async eval(t){return this.listenForExecution(t)}async run(t){this.liveAppPage=t,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var r,a,o,c,f,_;if(!((o=(a=(r=this.checksumConfig.options)==null?void 0:r.modelConfig)==null?void 0:a.browserArgs)!=null&&o.skipDisableWebSecurity)&&!((f=(c=this.checksumConfig.options)==null?void 0:c.modelConfig)!=null&&f.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((_=this.liveAppPage)==null?void 0:_.route("**/*",async(b,C)=>this.routeInterceptor.intercept(b,C,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(b){cf.error("[WebDriver] applyRouteInterceptors error",b)}}startRunner(){let t=o_.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,Ivi.join)(__dirname,"vtg-pw-bridge-runner.js")}`;KKa(t,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,wmn.createServer)(t=>{t.on("data",async r=>{try{await this.messageParser.onMessage(t,r)}catch(a){t.write(JSON.stringify({err:a.message}))}}),t.on("end",()=>{}),t.on("error",r=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>cf.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(t){return t&&JSON.stringify(t,Object.getOwnPropertyNames(t))}async connectToVTG(){cf.info("[VTG PW Bridge] Connecting to VTG...");let t=e(r=>r.frames().find(a=>a.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",o_.vtg.vtgRemoteDebuggingPort,r=>r.find(a=>t(a))),this.vtgTimeMachineFrame=t(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",o_.vtg.taskTimeMachine.debugPort,r=>r[0]),cf.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(t,r,a){return Cmn("Playwright via Bridge",t,r,a,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((t,r)=>{let a=(0,wmn.createServer)();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})}async listenForExecution(t){return new Promise(r=>{this.resolveEvaluator=r,this.listener=t})}stopListening(){var t;(t=this.resolveEvaluator)==null||t.call(this)}buildContext(t){let{frame:r,expectConfig:a}=t,o={};switch(r){case"task-time-machine":o.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":o.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return a&&(o.expect=Tbe.expect.configure(a)),o}wrapCodeInContext(t,r){return`(async ({${Object.keys(r).join(", ")}}) => { ${t} })`}async execute(t){this.isReady||cf.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:r,code:a,options:o}=t,c=this.buildContext(o),f=this.wrapCodeInContext(a,c)+"(context)";return new Promise(_=>{this.listener&&this.listener(f,c,(b,C)=>{_({id:r,err:b,result:C})})})}};e(Smn,"VtgPwBridge");var utr=Smn;async function KKa(i,t={}){let r={...process.env,...t};(0,kvi.spawn)(i,{env:r,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",o=>{process.exit(o)})}e(KKa,"spawnCmd");var rbi=require("@playwright/test"),nbi=uf(tbi());var nae=class nae{constructor(t){this.options=t;this.importPluginPackages()}importPluginPackages(){nae.pw??(nae.pw=F_t()),nae.StealthPlugin??(nae.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:t}=F_t(),r=t(nae.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),r}catch(t){throw console.error("[StealthProvider] Error creating fresh instance:",t),t}}buildChromiumWithPlugins(t){let{project:r}=this.options,a=r.use.userAgent,o=r.use.playwrightExtra||[],c=nae.StealthPlugin();if(o.push(c),this.isCustomUserAgent(a)){c.enabledEvasions.delete("user-agent-override");let b=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:a});o.push(b)}let f=t??nae.pw.chromium;return o.forEach((_,b)=>{try{!(_ instanceof nbi.PuppeteerExtraPlugin)&&_!==c&&console.warn(`Plugin at index ${b} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),f.use(_)}catch(C){console.warn(C)}}),f}isCustomUserAgent(t){return t?!Object.values(rbi.devices).some(r=>t===r.userAgent):!1}};e(nae,"StealthProvider");var ptr=nae;function ibi(i,t){return{testSuiteRunId:t,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}e(ibi,"createDefaultTestSuiteRunInfo");var sbi=require("crypto");var Pmn={},avt=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,obi=e((i,t,r={},a=!1)=>{let{runMode:o,environments:c}=t,f=c.find(b=>b.default),_=i.extend({baseURL:f.baseURL,bypassCSP:!0,...avt?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},b,C)=>{if(!avt)await b(C.project.use.permissions);else{let w=new Set(C.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await b(Array.from(w))}},"permissions"),proxy:e(async({proxy:b},C)=>{b?await C({...b,bypass:"127.0.0.1,localhost"}):await C(b)},"proxy"),browser:e(async({browser:b,browserName:C,launchOptions:w},T,k)=>{if(!avt)await T(b);else if(o_.vtg.isSeparateProcess)await T(b);else{(k.project.use.playwrightExtra||[]).some(X=>X.constructor.name==="StealthPlugin")&&(console.log("StealthPlugin already configured"),await T(b));let W=await(await new ptr({project:k.project}).buildChromiumWithPlugins()).launch(w);await T(W)}},"browser"),launchOptions:e(async({launchOptions:b},C)=>{var k;let w=b!=null&&b.args?[...b.args]:[],T=e(R=>{w.includes(R)||w.push(R)},"pushArg");if(r.useMockData&&T("--disable-web-security"),o_.bypassProxyForLocalhost&&T("--proxy-bypass-list=localhost,127.0.0.1"),avt){T("--proxy-bypass-list=localhost,127.0.0.1"),o_.vtg.isSeparateProcess&&T(`--remote-debugging-port=${o_.vtg.appRemoteDebuggingPort}`);let R=((k=r.modelConfig)==null?void 0:k.browserArgs)??{};R.skipDisableWebSecurity||T("--disable-web-security"),R.skipAllowFileAccessFromFiles||T("--allow-file-access-from-files"),R.skipDisableSiteIsolationTrials||T("--disable-site-isolation-trials"),R.skipAllowRunningInsecureContent||T("--allow-running-insecure-content")}await C({...b,args:w})},"launchOptions"),variableStore:e(async({},b)=>{let C=new $Je;await b(C)},"variableStore"),vs:e(async({variableStore:b},C)=>{await C(b)},"vs"),variablesStore:e(async({variableStore:b},C)=>{await C(b)},"variablesStore"),testRunAnalytics:e(async({},b,C)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),ibi("playwright-run-version-unknown",(0,sbi.randomUUID)())}})(),T=abi(C),k=$H.getTestRunInstance({...w,checksumTestId:T},process.env.CHECKSUM_ISOLATED_MODE==="true",C);await b(k)},"testRunAnalytics"),monitorBridge:[async({},b,C)=>{let w=new yVt(C);await b(w)},{scope:"worker"}],page:e(async({page:b,monitorBridge:C,variableStore:w,testRunAnalytics:T},k,R)=>{let B=await fVt.init(b,T,C,w,R,abi(R),_,t,a);Object.defineProperty(B.constructor,"name",{value:"Page"}),await k(B),await B.onTestComplete(R.status==="passed"),await B.shutdown()},"page"),vtg:e(async({page:b},C)=>{if(!avt)C(null);else if(o_.vtg.isSeparateProcess){let w=new utr(t);await w.run(b),await C(w)}else{let w=new otr(["--test-file"],!1,t);await w.run(b),await C(w)}},"vtg")});return{test:_,defineChecksumTest:fYa}},"createChecksumTestExtension"),fYa=e((i,t,r)=>{let o=new Error().stack.split(`
2042
- `).filter(c=>c.includes(".checksum.spec.ts"))[0];if(!o)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return Pmn[o]=t,i},"defineChecksumTest");function abi(i){let{file:t,line:r}=i,a=Object.keys(Pmn).filter(c=>c.trim().includes(t.trim()));if(!a.length)return;let o=4;for(let c=0;c<o;c++)for(let f of a){let _;try{_=parseInt(f.split(":").reverse()[1])}catch{continue}if(_-c===parseInt(r))return Pmn[f]}}e(abi,"getCurrentTestIdFromMapping");var dYa=["toPass"],mYa=["toBeOK"],_Ya=["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"],hYa=["toHaveScreenshot","toHaveTitle","toHaveURL"],gYa=["toMatchSnapshot"],yYa=["toBe","toBeCloseTo","toBeDefined","toBeFalsy","toBeGreaterThan","toBeGreaterThanOrEqual","toBeInstanceOf","toBeLessThan","toBeLessThanOrEqual","toBeNaN","toBeNull","toBeTruthy","toBeUndefined","toContain","toContainEqual","toEqual","toHaveLength","toHaveProperty","toMatch","toMatchObject","toStrictEqual","toThrow","toThrowError"],ubi=[...yYa,...gYa],mRo=[...dYa,...mYa,..._Ya,...hYa];var Fmn=class Fmn{constructor(t,r,a=!1,o=!1,c={}){this.page=t;this.soft=a;this.skipAIFallback=o;this.configuration=c;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=e(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(r)}setThought(t){var r,a;t&&(this.checksumAIThought=this.page.addNewThought(t,"assertion"),this.useChecksumAIOptions=(r=this.page.getRuntimeOptions())==null?void 0:r.useChecksumAI,(a=this.useChecksumAIOptions)!=null&&a.assertions&&(this.page.setAIFallback(t,"assertion"),this.fallbackEnabled=!0))}get(t,r,a){if(typeof r!="string")return t[r];if(r==="checksumAI")return o=>(this.setThought(o),a);if(r==="withChecksumAI"||typeof t[r]=="function"){let o=r==="withChecksumAI"?this.withChecksumAIMatcher:t[r];return(...c)=>ubi.includes(r)?o.call(t,...c):this.checksumAIThought?this.executeMatcherWithinStep(o,t,...c):this.executeMatcher(o,t,...c)}else{let o=t[r];return new Proxy(o,this)}}findNestedErrors(t,r){t.error&&t.infectParentStepsWithError&&r.push(t.error);for(let a of t.steps)this.findNestedErrors(a,r)}async callMatcher(t,r,...a){this.beforeMatcherCall();let o=t.call(r,...a),c=o instanceof Promise?await o:o;if(this.step){let f=[];if(this.step.error?f.push(this.step.error):this.findNestedErrors(this.step,f),f.length)throw f[0]}return c}executeMatcherWithinStep(t,r,...a){return this.page.step(this.checksumAIThought.thought,()=>this.callMatcher(t,r,...a).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:e(o=>this.step=o,"obtainStep")}).catch(o=>{if(!this.soft&&!(this.withChecksumAI&&o.message===h4e))throw o}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(t,r,...a){try{return await this.callMatcher(t,r,...a)}catch(o){await this.onMatcherFailure(o)}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}shouldInitiateFallback(t){var a;return!(!this.fallbackEnabled||((a=t.matcherResult)==null?void 0:a.name)==="toHaveScreenshot"&&!this.useChecksumAIOptions.visualComparison)}async onMatcherFailure(t){var r;if(!this.shouldInitiateFallback(t))throw Qv("[onMatcherFailure] fallback disabled, continuing with error."),this.page.testRunAnalytics.testRunAssertionExecutionFailure({failedThought:this.checksumAIThought.thought,error:t.message,matcher:(r=t.matcherResult)==null?void 0:r.name}),t;if(Qv("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought.thought),this.skipAIFallback)throw t;try{await this.page.initiateFallbackSequence({type:"assertion",error:t,withChecksumAI:this.withChecksumAI,testInfo:this.page.testInfo})}catch(a){if(this.soft)return;throw a}throw this.soft=!0,t}};e(Fmn,"ExpectCallProxyHandler");var ftr=Fmn;var mtr=class mtr{constructor(t=void 0,r={}){this.page=t;this.configuration=r}get(t,r){return r==="setPage"?a=>{this.page=a}:r==="extend"?(...a)=>{let o=t.extend(...a);return new Proxy(o,this)}:r==="configure"?a=>{let o=t.configure(a);return new Proxy(o,new mtr(this.page,{...this.configuration,...a}))}:r==="soft"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.soft(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o,!0))}:r==="skipAIFallback"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o,void 0,!0))}:r==="poll"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.poll(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}:t[r]instanceof Function?t[r].bind(t):t[r]}apply(t,r,a){let o=this.manipulateArgsAndExtractThought(a),c=t.apply(r,a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}makeExpectCallProxyHandler(t,r,a){var o,c;return new ftr(this.page,t,r===!0?!0:(o=this.configuration)==null?void 0:o.soft,a===!0?!0:(c=this.configuration)==null?void 0:c.skipAIFallback,this.configuration)}manipulateArgsAndExtractThought(t){let r,a=t[1];if(typeof a=="string")r=a,t[1]=void 0;else if(typeof a=="object"){if(a.checksumAI===!1){t[1].checksumAI=void 0;return}a.checksumAI&&typeof a.checksumAI=="string"?(r=a.checksumAI,t[1].checksumAI=void 0):a.message&&(r=a.message,t[1].message=void 0)}return r}};e(mtr,"ExpectProxyHandler");var dtr=mtr;var htr=class htr{constructor(t){this.expect=t;this.proxy=new Proxy(this.expect,new dtr)}static init(t){return new htr(t).proxy}};e(htr,"ChecksumExpect");var _tr=htr;var pbi=require("@playwright/test");var cbi=uf(gT()),gtr=require("fs");var svt=uf(require("path"));var vYa=e(i=>{let t=T7e(i),r=new k7e(t),a=cht();return r.transformSourceFile([new FFe(i),new EHe(i,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[cbi.factory.createIdentifier("__filename")]})]),`${PYn}
2042
+ `).filter(c=>c.includes(".checksum.spec.ts"))[0];if(!o)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return Pmn[o]=t,i},"defineChecksumTest");function abi(i){let{file:t,line:r}=i,a=Object.keys(Pmn).filter(c=>c.trim().includes(t.trim()));if(!a.length)return;let o=4;for(let c=0;c<o;c++)for(let f of a){let _;try{_=parseInt(f.split(":").reverse()[1])}catch{continue}if(_-c===parseInt(r))return Pmn[f]}}e(abi,"getCurrentTestIdFromMapping");var dYa=["toPass"],mYa=["toBeOK"],_Ya=["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"],hYa=["toHaveScreenshot","toHaveTitle","toHaveURL"],gYa=["toMatchSnapshot"],yYa=["toBe","toBeCloseTo","toBeDefined","toBeFalsy","toBeGreaterThan","toBeGreaterThanOrEqual","toBeInstanceOf","toBeLessThan","toBeLessThanOrEqual","toBeNaN","toBeNull","toBeTruthy","toBeUndefined","toContain","toContainEqual","toEqual","toHaveLength","toHaveProperty","toMatch","toMatchObject","toStrictEqual","toThrow","toThrowError"],ubi=[...yYa,...gYa],mRo=[...dYa,...mYa,..._Ya,...hYa];var Fmn=class Fmn{constructor(t,r,a=!1,o=!1,c={}){this.page=t;this.soft=a;this.skipAIFallback=o;this.configuration=c;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=e(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(r)}setThought(t){var r,a;t&&(this.checksumAIThought=this.page.addNewThought(t,"assertion"),this.useChecksumAIOptions=(r=this.page.getRuntimeOptions())==null?void 0:r.useChecksumAI,(a=this.useChecksumAIOptions)!=null&&a.assertions&&(this.page.setAIFallback(t,"assertion"),this.fallbackEnabled=!0))}get(t,r,a){if(typeof r!="string")return t[r];if(r==="checksumAI")return o=>(this.setThought(o),a);if(r==="withChecksumAI"||typeof t[r]=="function"){let o=r==="withChecksumAI"?this.withChecksumAIMatcher:t[r];return(...c)=>ubi.includes(r)?o.call(t,...c):this.checksumAIThought?this.executeMatcherWithinStep(o,t,...c):this.executeMatcher(o,t,...c)}else{let o=t[r];return new Proxy(o,this)}}findNestedErrors(t,r){t.error&&t.infectParentStepsWithError&&r.push(t.error);for(let a of t.steps)this.findNestedErrors(a,r)}async callMatcher(t,r,...a){this.beforeMatcherCall();let o=t.call(r,...a),c=o instanceof Promise?await o:o;if(this.step){let f=[];if(this.step.error?f.push(this.step.error):this.findNestedErrors(this.step,f),f.length)throw f[0]}return c}executeMatcherWithinStep(t,r,...a){return this.page.step(this.checksumAIThought.thought,()=>this.callMatcher(t,r,...a).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:e(o=>this.step=o,"obtainStep")}).catch(o=>{if(!this.soft&&!(this.withChecksumAI&&o.message===h4e))throw o}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(t,r,...a){try{return await this.callMatcher(t,r,...a)}catch(o){await this.onMatcherFailure(o)}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}shouldInitiateFallback(t){var a;return!(!this.fallbackEnabled||((a=t.matcherResult)==null?void 0:a.name)==="toHaveScreenshot"&&!this.useChecksumAIOptions.visualComparison)}async onMatcherFailure(t){var r,a;if(!this.shouldInitiateFallback(t))throw Qv("[onMatcherFailure] fallback disabled, continuing with error."),this.page.testRunAnalytics.testRunAssertionExecutionFailure({failedThought:(r=this.checksumAIThought)==null?void 0:r.thought,error:t.message,matcher:(a=t.matcherResult)==null?void 0:a.name}),t;if(Qv("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought.thought),this.skipAIFallback)throw t;try{await this.page.initiateFallbackSequence({type:"assertion",error:t,withChecksumAI:this.withChecksumAI,testInfo:this.page.testInfo})}catch(o){if(this.soft)return;throw o}throw this.soft=!0,t}};e(Fmn,"ExpectCallProxyHandler");var ftr=Fmn;var mtr=class mtr{constructor(t=void 0,r={}){this.page=t;this.configuration=r}get(t,r){return r==="setPage"?a=>{this.page=a}:r==="extend"?(...a)=>{let o=t.extend(...a);return new Proxy(o,this)}:r==="configure"?a=>{let o=t.configure(a);return new Proxy(o,new mtr(this.page,{...this.configuration,...a}))}:r==="soft"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.soft(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o,!0))}:r==="skipAIFallback"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o,void 0,!0))}:r==="poll"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.poll(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}:t[r]instanceof Function?t[r].bind(t):t[r]}apply(t,r,a){let o=this.manipulateArgsAndExtractThought(a),c=t.apply(r,a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}makeExpectCallProxyHandler(t,r,a){var o,c;return new ftr(this.page,t,r===!0?!0:(o=this.configuration)==null?void 0:o.soft,a===!0?!0:(c=this.configuration)==null?void 0:c.skipAIFallback,this.configuration)}manipulateArgsAndExtractThought(t){let r,a=t[1];if(typeof a=="string")r=a,t[1]=void 0;else if(typeof a=="object"){if(a.checksumAI===!1){t[1].checksumAI=void 0;return}a.checksumAI&&typeof a.checksumAI=="string"?(r=a.checksumAI,t[1].checksumAI=void 0):a.message&&(r=a.message,t[1].message=void 0)}return r}};e(mtr,"ExpectProxyHandler");var dtr=mtr;var htr=class htr{constructor(t){this.expect=t;this.proxy=new Proxy(this.expect,new dtr)}static init(t){return new htr(t).proxy}};e(htr,"ChecksumExpect");var _tr=htr;var pbi=require("@playwright/test");var cbi=uf(gT()),gtr=require("fs");var svt=uf(require("path"));var vYa=e(i=>{let t=T7e(i),r=new k7e(t),a=cht();return r.transformSourceFile([new FFe(i),new EHe(i,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[cbi.factory.createIdentifier("__filename")]})]),`${PYn}
2043
2043
  ${r.getTestFileCode().code}`},"transformFileToHoRequireFormat"),bYa=e(i=>{let t=svt.default.dirname(i),a=svt.default.basename(i).split(".")[0],o=Math.random().toString(36).substring(2,15),c=svt.default.extname(i);return svt.default.join(t,`${a}-${Date.now()}-${o}${c}`)},"generateTempFilePath"),xYa=e((i,t)=>{let r=cht();return new I7e(t,r).getResolvedPath(i)},"resolveFilePath"),AYa=e((i,t=__filename)=>{let r;try{let a=require.resolve(xYa(i,t)),o=vYa(a);r=bYa(a),(0,gtr.writeFileSync)(r,o);let c=require(r);return require.cache[a]=require.cache[r],c}catch(a){throw console.error("Error in require",a),a}finally{r&&(0,gtr.unlinkSync)(r)}},"checksumHotRequire"),lbi=AYa;function EYa(i){let t=lqt(),{options:r,apiKey:a,environments:o}=t,c=o.find(R=>R.default);if(!c)throw new Error("No default environment found. Please set the default field to true on one of the environments in the checksum.config.ts file.");if(!c.baseURL)throw new Error("A baseURL is required. Please set the baseURL field in the default environment in the checksum.config.ts file.");if(!c.users.find(R=>R.default))throw new Error("A default user within the default environment is required. Please set one of the default environment users as default in the checksum.config.ts file.");if(!a)throw new Error("An API key is required. Please set the apiKey field in the checksum.config.ts file.");let _=process.env.CHECKSUM_REPL==="true",{test:b,defineChecksumTest:C}=obi(i??pbi.test,t,r,_),w=_tr.init(b.expect),T=CYa();b._checksum={expect:w,checksumAI:T},_&&(console.log("Detected REPL mode"),b.beforeEach(async()=>{b.setTimeout(0)}),b.afterEach(async()=>{for(;;)await rA(1e3)}));let k=e(({name:R,userRole:B})=>{let{environment:U,user:W}=l_t(t,{environment:R,role:B},!0),X=O$n({config:t,throwIfEnvInfoInvalid:!0},{environmentName:U.name,userRole:W.role});return{environment:U,user:W,login:X}},"getEnvironment");return{test:b,expect:w,login:Ebe({config:t}),defineChecksumTest:C,getEnvironment:k,checksumAI:T}}e(EYa,"init");var Nmn=e(i=>new Proxy(i,{apply:e(function(r,a,o){return r.page.checksumAI(o[0],o[1],r.options)},"apply"),get:e(function(r,a){return a==="withDialog"?(r.options.withDialog=!0,Nmn(i)):a==="skipAIFallback"?(r.options.skipAIFallback=!0,Nmn(i)):r[a]},"get"),set:e(function(r,a,o){if(a==="page")return r[a]=o},"set")}),"makeChecksumAIProxy"),CYa=e(()=>{let i=e(function(){},"func");return i.page=void 0,i.options={withDialog:!1,withTomer:!1,skipAIFallback:!1},Nmn(i)},"makeChecksumAI");0&&(module.exports={AutoRecoveryMode,RunMode,checksumHotRequire,getChecksumConfig,getLogin,init});
2044
2044
  /*! Bundled license information:
2045
2045
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checksum-ai/runtime",
3
- "version": "1.3.6",
3
+ "version": "1.3.7",
4
4
  "description": "Checksum.ai test runtime",
5
5
  "main": "index.js",
6
6
  "dependencies": {