momentic 2.29.4 → 2.29.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e53eea05-eeb0-5ef4-b24a-5fc5e9a1ea42")}catch(e){}}();
4
- var BN=Object.defineProperty;var mt=(t,e)=>()=>(t&&(e=t(t=0)),e);var zN=(t,e)=>{for(var r in e)BN(t,r,{get:e[r],enumerable:!0})};var o_,i_=mt(()=>{"use strict";o_=typeof globalThis=="object"?globalThis:global});var a_=mt(()=>{"use strict";i_()});var s_=mt(()=>{"use strict";a_()});var ho,fS=mt(()=>{"use strict";ho="1.9.0"});function Pj(t){var e=new Set([t]),r=new Set,n=t.match(l_);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===t};function i(s){return r.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;var l=c.match(l_);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var l_,c_,u_=mt(()=>{"use strict";fS();l_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;c_=Pj(ho)});function ys(t,e,r,n){var o;n===void 0&&(n=!1);var i=sc[ac]=(o=sc[ac])!==null&&o!==void 0?o:{version:ho};if(!n&&i[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(i.version!==ho){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+ho);return r.error(a.stack||a.message),!1}return i[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+ho+"."),!0}function go(t){var e,r,n=(e=sc[ac])===null||e===void 0?void 0:e.version;if(!(!n||!c_(n)))return(r=sc[ac])===null||r===void 0?void 0:r[t]}function Es(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+ho+".");var r=sc[ac];r&&delete r[t]}var Ij,ac,sc,lc=mt(()=>{"use strict";s_();fS();u_();Ij=ho.split(".")[0],ac=Symbol.for("opentelemetry.js.api."+Ij),sc=o_});function cc(t,e,r){var n=go("diag");if(n)return r.unshift(e),n[t].apply(n,Lj([],Oj(r),!1))}var Oj,Lj,d_,p_=mt(()=>{"use strict";lc();Oj=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Lj=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},d_=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("verbose",this._namespace,e)},t}()});var at,gp=mt(()=>{"use strict";(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(at||(at={}))});function m_(t,e){t<at.NONE?t=at.NONE:t>at.ALL&&(t=at.ALL),e=e||{};function r(n,o){var i=e[n];return typeof i=="function"&&t>=o?i.bind(e):function(){}}return{error:r("error",at.ERROR),warn:r("warn",at.WARN),info:r("info",at.INFO),debug:r("debug",at.DEBUG),verbose:r("verbose",at.VERBOSE)}}var h_=mt(()=>{"use strict";gp()});var Nj,Dj,kj,Bn,uc=mt(()=>{"use strict";p_();h_();gp();lc();Nj=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Dj=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},kj="diag",Bn=function(){function t(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=go("diag");if(s)return s[o].apply(s,Dj([],Nj(i),!1))}}var r=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:at.INFO}),o===r){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=go("diag"),d=m_((s=i.logLevel)!==null&&s!==void 0?s:at.INFO,o);if(u&&!i.suppressOverrideMessage){var p=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return ys("diag",d,r,!0)};r.setLogger=n,r.disable=function(){Es(kj,r)},r.createComponentLogger=function(o){return new d_(o)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}()});var g_,f_=mt(()=>{"use strict";g_=Symbol("BaggageEntryMetadata")});function SS(t){return typeof t!="string"&&(Fj.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:g_,toString:function(){return t}}}var Fj,S_=mt(()=>{"use strict";uc();f_();Fj=Bn.instance()});function yS(t){return Symbol.for(t)}var Uj,ES,bS=mt(()=>{"use strict";Uj=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var i=new t(r._currentContext);return i._currentContext.set(n,o),i},r.deleteValue=function(n){var o=new t(r._currentContext);return o._currentContext.delete(n),o}}return t}(),ES=new Uj});function RS(){return vS}var Ki,Bj,fp,zj,Hj,Gj,jj,TS,Vj,$j,Wj,vS,qj,Kj,Yj,Xj,Jj,Qj,Zj,AS=mt(()=>{"use strict";Ki=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Bj=function(){function t(){}return t.prototype.createGauge=function(e,r){return Kj},t.prototype.createHistogram=function(e,r){return Yj},t.prototype.createCounter=function(e,r){return qj},t.prototype.createUpDownCounter=function(e,r){return Xj},t.prototype.createObservableGauge=function(e,r){return Qj},t.prototype.createObservableCounter=function(e,r){return Jj},t.prototype.createObservableUpDownCounter=function(e,r){return Zj},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),fp=function(){function t(){}return t}(),zj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(fp),Hj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(fp),Gj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(fp),jj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(fp),TS=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),Vj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(TS),$j=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(TS),Wj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(TS),vS=new Bj,qj=new zj,Kj=new Gj,Yj=new jj,Xj=new Hj,Jj=new Vj,Qj=new $j,Zj=new Wj});var Pr,y_=mt(()=>{"use strict";(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(Pr||(Pr={}))});var eV,tV,E_,b_=mt(()=>{"use strict";bS();eV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},tV=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},E_=function(){function t(){}return t.prototype.active=function(){return ES},t.prototype.with=function(e,r,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return r.call.apply(r,tV([n],eV(o),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}()});var rV,nV,wS,oV,T_,v_=mt(()=>{"use strict";b_();lc();uc();rV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},nV=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},wS="context",oV=new E_,T_=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return ys(wS,e,Bn.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,nV([e,r,n],rV(i),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return go(wS)||oV},t.prototype.disable=function(){this._getContextManager().disable(),Es(wS,Bn.instance())},t}()});var bs,R_=mt(()=>{"use strict";v_();bs=T_.getInstance()});var K,A_=mt(()=>{"use strict";uc();K=Bn.instance()});var iV,w_,C_=mt(()=>{"use strict";AS();iV=function(){function t(){}return t.prototype.getMeter=function(e,r,n){return vS},t}(),w_=new iV});var CS,x_,__=mt(()=>{"use strict";C_();lc();uc();CS="metrics",x_=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return ys(CS,e,Bn.instance())},t.prototype.getMeterProvider=function(){return go(CS)||w_},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){Es(CS,Bn.instance())},t}()});var Sp,M_=mt(()=>{"use strict";__();Sp=x_.getInstance()});var Xe=mt(()=>{"use strict";S_();bS();gp();AS();y_();R_();A_();M_()});var Xs=(t,e)=>{},nh=!1;try{let t=await import("@sentry/node");Xs=t.captureException,t.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),nh=!0}catch{}import{Command as u5,Option as hr}from"@commander-js/extra-typings";import{execSync as d5}from"child_process";import{existsSync as eB,statSync as tB}from"fs";import{z as oh}from"zod";var R5=oh.object({input:oh.string(),agentConfigVersion:oh.string().optional()});import{z as Pt}from"zod";var C5=Pt.object({srcs:Pt.array(Pt.string()),urls:Pt.array(Pt.string()),desiredSrc:Pt.string().optional(),desiredUrl:Pt.string().optional()}),CE=Pt.object({srcRegex:Pt.string().optional(),urlRegex:Pt.string().optional()}),xE=Pt.object({x:Pt.number(),y:Pt.number(),correlation:Pt.number()}),x5=Pt.object({searchImageBase64String:Pt.string(),pageImageBase64String:Pt.string(),id:Pt.string().uuid(),timeoutMs:Pt.number().max(1e4).min(0).optional()});import{z as P}from"zod";import*as k from"zod";import{extendZodWithOpenApi as HN}from"zod-openapi";HN(k);var vo=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(vo||{}),GN=k.object({mPathSelectorTokens:k.string().array(),frameSrcRegex:k.string().optional(),frameUrlRegex:k.string().optional(),indices:k.number().array()}),Js=k.object({result:k.number(),traceId:k.string()}).array(),Xn=k.object({type:k.literal("GCS_TRACES"),traces:Js}),gr=(o=>(o.PRECISE="precise",o.NARROW="narrow",o.BROAD="broad",o.IRRELEVANT="irrelevant",o))(gr||{}),_E=k.object({attributes:k.record(k.string(),k.string()).optional(),text:k.string().optional(),position:k.object({x1:k.number(),y1:k.number(),x2:k.number(),y2:k.number(),tolerance:k.nativeEnum(gr)}).optional(),shape:k.object({width:k.number(),height:k.number(),tolerance:k.nativeEnum(gr)}).optional(),boundingBox:k.object({x:k.number(),y:k.number(),width:k.number(),height:k.number()}).optional()}),jN=k.object({selectors:k.string().array(),requirements:_E.optional()}),Ro=k.object({id:k.number().int(),dataMomenticId:k.number().int().optional(),selector:k.string().optional(),hybridSelector:k.object({textContent:k.string().nullish(),attributes:k.record(k.string(),k.string().optional()),tagName:k.string(),expandShadowRoot:k.boolean().optional(),classNames:k.string().array(),nthChild:k.number()}).array().optional(),generatedSelectors:k.string().array().optional(),requirements:_E.optional(),additionalElements:jN.array().optional(),role:k.string().optional(),name:k.string().optional(),numChildren:k.number().optional(),content:k.string().optional(),pathFromRoot:k.string().optional(),serializedHtml:k.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:k.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:k.string().url().optional(),boundingBox:k.object({x:k.number().optional(),y:k.number().optional(),width:k.number(),height:k.number()}).describe("css pixel bounding box").optional(),frameCache:GN.optional(),inputDescription:k.string().optional().describe("the description that generated this cache"),targetSource:k.nativeEnum(vo).optional(),targetUpdateTime:k.string().optional(),targetUpdateLoggerTags:k.record(k.string(),k.string()).optional(),cacheResolutionUpdateSource:k.string().optional(),cacheResolutionUpdateTime:k.string().optional(),cacheResolutionUpdateLoggerTags:k.record(k.string(),k.string()).optional(),memory:Xn.optional()}).openapi({ref:"ElementTargetCache"});function ru(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var VN=k.object({type:k.literal("description"),elementDescriptor:k.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),$N=k.object({x:k.number(),y:k.number()}),WN=k.object({type:k.literal("coordinates"),pixels:$N}).openapi({ref:"CoordinatesTarget"});function Ao(t){return t.type==="description"}function bn(t){return t.type==="coordinates"}var $t=k.discriminatedUnion("type",[VN,WN]).openapi({ref:"ElementTarget"});function ih(t){if(!t)return!1;switch(t.type){case"description":return!!t.elementDescriptor}return!0}function Wt(t){if(!t)return"";switch(t.type){case"description":return t.elementDescriptor;case"coordinates":return`x: ${t.pixels.x}, y: ${t.pixels.y}`}}function nu(t){return Xn.safeParse(t).success}import{v4 as ke}from"uuid";import*as R from"zod";import{extendZodWithOpenApi as nD}from"zod-openapi";import{z as Ee}from"zod";import{extendZodWithOpenApi as qN}from"zod-openapi";import{z as Zs}from"zod";import ME from"zod";var Qs=ME.object({updatedAt:ME.coerce.date().optional()});var el=Zs.object({result:Zs.boolean(),traceId:Zs.string()}).array(),tl=Zs.object({type:Zs.literal("GCS_TRACES"),traces:el}),ya=Qs.extend({memory:tl.optional()});qN(Ee);var PE=Ee.object({thoughts:Ee.string(),result:Ee.boolean(),relevantElements:Ee.array(Ee.number()).optional(),updatedMemory:el.optional()}),nn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(nn||{});var KN=Ee.object({type:Ee.literal("ELEMENT_NAME"),negated:Ee.boolean().optional(),operation:Ee.nativeEnum(nn),value:Ee.string()}).openapi({ref:"ElementNameAssertion"}),YN=Ee.object({type:Ee.literal("ELEMENT_STYLE"),negated:Ee.boolean().optional(),operation:Ee.nativeEnum(nn),property:Ee.string(),value:Ee.string()}).openapi({ref:"ElementStyleAssertion"}),XN=Ee.object({type:Ee.literal("ELEMENT_CONTENT"),negated:Ee.boolean().optional(),operation:Ee.nativeEnum(nn),value:Ee.string()}).openapi({ref:"ElementContentAssertion"}),JN=Ee.object({type:Ee.literal("ELEMENT_ATTRIBUTE"),negated:Ee.boolean().optional(),operation:Ee.nativeEnum(nn),attr:Ee.string(),value:Ee.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Jn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Jn||{});var QN=Ee.object({type:Ee.literal("ELEMENT_EXISTENCE"),negated:Ee.boolean().optional(),condition:Ee.nativeEnum(Jn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),ou=Ee.discriminatedUnion("type",[XN,JN,QN,KN,YN]).openapi({ref:"ManualElementAssertion"});var ZN=Ee.object({type:Ee.literal("CONTENT"),negated:Ee.boolean().optional(),value:Ee.string()}).openapi({ref:"PageContentAssertion"}),IE=Ee.discriminatedUnion("type",[ZN]).openapi({ref:"ManualPageAssertion"});import or from"zod";var ah=or.discriminatedUnion("type",[or.object({type:or.literal("SUBSTRING"),url:or.string()}),or.object({type:or.literal("GLOB"),glob:or.string()}),or.object({type:or.literal("REGEX"),regex:or.string()}),or.object({type:or.literal("DOMAIN"),domain:or.string()})]),rl=or.object({urlMatcher:ah,method:or.string().optional()});import{z as ge}from"zod";var eD=ge.object({type:ge.literal("json"),content:ge.string().describe("The JSON content to send in the request body")}),tD=ge.object({type:ge.literal("form-urlencoded"),content:ge.record(ge.string(),ge.string()).describe("The form fields to send in the request body")}),rD=ge.discriminatedUnion("type",[eD,tD]),gi=ge.object({url:ge.string(),method:ge.union([ge.literal("GET"),ge.literal("POST"),ge.literal("PUT"),ge.literal("DELETE"),ge.literal("PATCH")]),headers:ge.record(ge.string(),ge.string()).optional(),params:ge.record(ge.string(),ge.string()).optional(),body:rD.optional(),timeout:ge.number().int().optional().describe("Max seconds to wait for the request to complete")}),OE=ge.object({url:ge.string(),headers:ge.record(ge.string(),ge.string()).optional(),query:ge.string(),variables:ge.string().optional(),timeout:ge.number().int().optional().describe("Max seconds to wait for the request to complete")}),iu=ge.object({code:ge.string(),fragment:ge.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:ge.union([ge.literal("NODE"),ge.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:ge.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Je=(J=>(J.AI_EXTRACT="AI_EXTRACT",J.AI_ASSERTION="AI_ASSERTION",J.AUTH_LOAD="AUTH_LOAD",J.AUTH_SAVE="AUTH_SAVE",J.BLUR="BLUR",J.CAPTCHA="CAPTCHA",J.CLICK="CLICK",J.COOKIE="COOKIE",J.COPY="COPY",J.DIALOG="DIALOG",J.DRAG="DRAG",J.ELEMENT_CHECK="ELEMENT_CHECK",J.FILE_UPLOAD="FILE_UPLOAD",J.FOCUS="FOCUS",J.GO_BACK="GO_BACK",J.GO_FORWARD="GO_FORWARD",J.HOVER="HOVER",J.JAVASCRIPT="JAVASCRIPT",J.LOCAL_STORAGE="LOCAL_STORAGE",J.MOUSE_DRAG="MOUSE_DRAG",J.NAVIGATE="NAVIGATE",J.NEW_TAB="NEW_TAB",J.PAGE_CHECK="PAGE_CHECK",J.PASTE="PASTE",J.PRESS="PRESS",J.KEY_DOWN="KEY_DOWN",J.KEY_UP="KEY_UP",J.REFRESH="REFRESH",J.REQUEST="REQUEST",J.GRAPHQL_REQUEST="GRAPHQL_REQUEST",J.SCROLL_DOWN="SCROLL_DOWN",J.SCROLL_UP="SCROLL_UP",J.SCROLL_LEFT="SCROLL_LEFT",J.SCROLL_RIGHT="SCROLL_RIGHT",J.SELECT_OPTION="SELECT_OPTION",J.SWITCH_TAB="TAB",J.TYPE="TYPE",J.VISUAL_DIFF="VISUAL_DIFF",J.WAIT="WAIT",J.WAIT_FOR_URL="WAIT_FOR_URL",J.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",J.AWAIT_LISTENER="AWAIT_LISTENER",J.RECORD_REQUESTS="RECORD_REQUESTS",J.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",J.SET_HEADER="SET_HEADER",J.MOCK_ROUTE="MOCK_ROUTE",J.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",J.OFFLINE_MODE="OFFLINE_MODE",J.SUCCESS="SUCCESS",J))(Je||{});nD(R);var te=R.object({thoughts:R.string().optional(),id:R.string().uuid().describe("unique identifier to this step, used for step cache")}),Dr=R.object({useSelector:R.boolean().optional(),force:R.boolean().optional(),disableCache:R.boolean().optional().describe("disable element caching for this step"),iframeUrl:R.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Rr=Qs.extend({target:Ro}).optional().openapi({ref:"SingleTargetCache"});function LE(t){return Rr.safeParse(t).success}var su=R.object({loadTimeout:R.number().int().max(60).optional().describe("Max seconds for the page to load")}),NE=te.merge(su).merge(R.object({type:R.literal("NAVIGATE"),url:R.string()})).openapi({ref:"NavigateCommand"}),lu=Dr.merge(R.object({cache:Rr})),Si=te.merge(lu.merge(R.object({target:$t.optional(),type:R.literal("SCROLL_UP"),deltaY:R.number().optional()}))).openapi({ref:"ScrollUpCommand"}),yi=te.merge(lu.merge(R.object({target:$t.optional(),type:R.literal("SCROLL_DOWN"),deltaY:R.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Ea=te.merge(lu.merge(R.object({target:$t.optional(),type:R.literal("SCROLL_LEFT"),deltaX:R.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),ba=te.merge(lu.merge(R.object({target:$t.optional(),type:R.literal("SCROLL_RIGHT"),deltaX:R.number().optional()}))).openapi({ref:"ScrollRightCommand"}),iX=R.discriminatedUnion("type",[Si,yi,Ea,ba]).openapi({ref:"AllScrollCommands"}),oD=te.merge(R.object({type:R.literal("DIALOG"),action:R.union([R.literal("ACCEPT"),R.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),DE=te.merge(R.object({type:R.literal("WAIT"),delay:R.number()})).openapi({ref:"WaitCommand"}),iD=R.object({caseInsensitive:R.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:R.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:R.number().int().optional().describe("Max seconds to wait for the URL to match")}),kE=te.extend({type:R.literal("WAIT_FOR_URL"),matcher:ah}).merge(iD).openapi({ref:"WaitUrlCommand"}),FE=te.merge(su).merge(R.object({type:R.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),UE=te.merge(R.object({type:R.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),BE=te.merge(R.object({type:R.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),aD=te.extend({type:R.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),sD=te.extend({type:R.literal("AUTH_LOAD"),storageState:R.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),sh=te.merge(Dr).extend({type:R.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),zE=te.extend({type:R.literal("COPY"),value:R.string()}).openapi({ref:"CopyCommand"}),HE=te.extend({type:R.literal("PASTE")}).openapi({ref:"PasteCommand"}),GE=te.merge(iu).extend({type:R.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Ta=te.merge(Dr).extend({type:R.literal("CLICK"),target:$t,doubleClick:R.boolean().optional(),rightClick:R.boolean().optional(),waitForDownload:R.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:R.number().optional(),downloadTimeoutMs:R.number().optional(),cache:Rr,relativePosition:R.object({x:R.number(),y:R.number()}).optional()}).openapi({ref:"ClickCommand"}),lh=Qs.extend({fromTarget:Ro.optional(),toTarget:Ro.optional()}),va=te.merge(Dr).merge(R.object({type:R.literal("DRAG"),fromTarget:$t,toTarget:$t,steps:R.number().optional(),hoverSeconds:R.number().optional().describe("Seconds to hover the object before dropping"),cache:lh.optional()})).openapi({ref:"DragCommand"}),Ra=te.merge(Dr).merge(R.object({type:R.literal("MOUSE_DRAG"),target:$t.optional(),deltaX:R.string().describe("pixels to move horizontally, can be template"),deltaY:R.string().describe("pixels to move vertically, can be template"),steps:R.number().optional(),cache:Rr})).openapi({ref:"MouseDragCommand"}),Aa=te.merge(Dr).merge(R.object({type:R.literal("HOVER"),target:$t,cache:Rr})).openapi({ref:"HoverCommand"}),nl=te.merge(Dr).merge(R.object({type:R.literal("FOCUS"),target:$t,cache:Rr})).openapi({ref:"FocusCommand"}),ol=te.merge(Dr).extend({type:R.literal("BLUR"),target:$t.optional(),cache:Rr}).openapi({ref:"BlurCommand"}),lD=R.object({type:R.literal("URL"),url:R.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),cD=R.object({type:R.literal("USER_FILE"),name:R.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),uD=te.extend({type:R.literal("FILE_UPLOAD"),fileSource:R.discriminatedUnion("type",[lD,cD]),filename:R.string().optional()}).openapi({ref:"FileUploadCommand"}),ch=R.discriminatedUnion("type",[R.object({type:R.literal("VALUE"),value:R.string()}),R.object({type:R.literal("LABEL"),label:R.string()}),R.object({type:R.literal("INDEX"),index:R.coerce.string()})]),wa=te.merge(Dr).extend({type:R.literal("SELECT_OPTION"),target:$t,cache:Rr,choice:ch.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),uh=R.union([R.literal("MULTIMODAL"),R.literal("VISION_ONLY")]),il=te.merge(R.object({type:R.literal("AI_ASSERTION"),assertion:R.string(),disableCache:R.boolean().optional(),iframeUrl:R.string().optional(),contextChoice:uh.optional(),timeout:R.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:ya.optional()})).openapi({ref:"AIAssertionCommand"}),Tn=5,Ca=600,xa=te.merge(Dr).extend({type:R.literal("ELEMENT_CHECK"),target:$t,assertion:ou,cache:Rr.or(ya).optional(),timeout:R.number().int().min(0).max(Ca).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),jE=te.extend({type:R.literal("PAGE_CHECK"),assertion:IE,iframeUrl:R.string().optional().describe("url or url regex for the iframe"),timeout:R.number().int().min(0).max(Ca).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),VE=te.merge(R.object({type:R.literal("AI_EXTRACT"),goal:R.string(),schema:R.string().optional(),envKey:R.string().optional(),disableCache:R.boolean().optional(),iframeUrl:R.string().optional()})).openapi({ref:"AIExtractCommand"}),dD=R.object({clearContent:R.boolean().optional(),forceClearContent:R.boolean().optional(),delay:R.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:R.boolean().optional(),pressEnter:R.boolean().optional(),relativePosition:R.object({x:R.number(),y:R.number()}).optional()}),$E=25,_a=te.merge(Dr).merge(dD).extend({type:R.literal("TYPE"),target:$t.optional(),value:R.string(),cache:Rr}).openapi({ref:"TypeCommand"}),WE=te.merge(R.object({type:R.literal("PRESS"),value:R.string(),repeat:R.number().optional(),convertMeta:R.boolean().optional(),delayMs:R.number().optional()})).openapi({ref:"PressCommand"}),qE=te.merge(R.object({type:R.literal("KEY_DOWN"),value:R.string(),convertMeta:R.boolean().optional()})).openapi({ref:"KeyDownCommand"}),KE=te.merge(R.object({type:R.literal("KEY_UP"),value:R.string(),convertMeta:R.boolean().optional()})).openapi({ref:"KeyUpCommand"}),pD=R.object({type:R.literal("SUBSTRING"),substring:R.string()}),mD=R.object({type:R.literal("REGEX"),pattern:R.string()}),hD=R.object({type:R.literal("INDEX"),index:R.coerce.string()}),gD=R.discriminatedUnion("type",[pD,mD,hD]),fD=te.merge(su).merge(R.object({type:R.literal("TAB"),action:gD})).openapi({ref:"TabCommand"}),YE=te.merge(su).merge(R.object({type:R.literal("NEW_TAB"),url:R.string()})).openapi({ref:"NewTabCommand"}),SD=te.merge(R.object({type:R.literal("COOKIE"),value:R.string()})).openapi({ref:"CookieCommand"}),XE=te.merge(R.object({type:R.literal("LOCAL_STORAGE"),key:R.string(),value:R.string()})).openapi({ref:"LocalStorageCommand"}),JE=te.extend({type:R.literal("REQUEST")}).merge(gi).openapi({ref:"RequestCommand"}),al=R.object({status:R.number().optional(),headers:R.record(R.string(),R.string()),json:R.unknown().optional(),text:R.string().optional(),cookies:R.record(R.string(),R.unknown()).array().optional(),request:R.object({url:R.string(),method:R.string(),headers:R.record(R.string(),R.string()),json:R.unknown().optional()})}),QE=te.extend({type:R.literal("GRAPHQL_REQUEST")}).merge(OE).openapi({ref:"GraphQLRequestCommand"}),ZE=te.merge(R.object({type:R.literal("SUCCESS"),condition:il.optional()})).openapi({ref:"SuccessCommand"}),eb=te.merge(R.object({type:R.literal("FAILURE")})).openapi({ref:"FailureCommand"}),yD=R.object({data:R.string().describe("location at which to find a jpg"),width:R.number(),height:R.number()}),sl=te.merge(Dr).merge(R.object({type:R.literal("VISUAL_DIFF"),threshold:R.number().optional().describe("default 0.1"),target:$t.optional(),screenshot:yD.optional(),cache:Rr})).openapi({ref:"VisualDiffCommand"}),ED=te.merge(R.object({type:R.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:rl,key:R.string()})).openapi({ref:"RegisterRequestListenerCommand"}),bD=te.merge(R.object({type:R.literal("AWAIT_LISTENER"),key:R.string(),timeout:R.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),TD=te.merge(R.object({type:R.literal("RECORD_REQUESTS"),requestMatcher:rl,key:R.string()})).openapi({ref:"RecordRequestsCommand"}),vD=te.merge(R.object({type:R.literal("GET_RECORDED_REQUESTS"),key:R.string()})).openapi({ref:"GetRecordedRequestsCommand"}),RD=te.merge(R.object({type:R.literal("SET_HEADER"),name:R.string(),value:R.string(),requestMatcher:rl.optional()})).openapi({ref:"SetHeaderCommand"}),AD=te.merge(R.object({type:R.literal("MOCK_ROUTE"),requestMatcher:rl,responseGenerator:R.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:R.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:R.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),wD=te.merge(R.object({type:R.literal("REMOVE_ROUTE_MOCK"),key:R.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),CD=te.merge(R.object({type:R.literal("OFFLINE_MODE"),enable:R.boolean()})).openapi({ref:"OfflineModeCommand"}),xD=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],aX=[...xD,"DRAG"],_D=R.discriminatedUnion("type",[Ta,_a,WE,qE,KE,wa,NE,yi,Si,il,UE,Aa,DE]),MD=R.discriminatedUnion("type",[..._D.options,va]),PD=R.discriminatedUnion("type",[...MD.options]),tb=R.discriminatedUnion("type",[...PD.options,ZE]),dh=R.discriminatedUnion("type",[ZE,Ta,_a,WE,qE,KE,wa,NE,yi,Si,il,UE,Aa,DE,GE,xa,jE,YE,kE,VE,zE,BE,XE,va,Ra,HE,FE,JE,QE]),ID=R.discriminatedUnion("type",[VE,sD,aD,sh,SD,zE,oD,xa,uD,BE,GE,XE,Ra,YE,jE,HE,FE,JE,QE,Ea,ba,fD,sl,nl,ol,kE,ED,bD,TD,vD,RD,AD,wD,CD]),Ma=R.discriminatedUnion("type",[...tb.options,...ID.options]).openapi({ref:"Command"}),cu=R.discriminatedUnion("type",[...tb.options,eb]),sX=R.discriminatedUnion("type",[...dh.options,eb]);function Qn(t){let e;switch(t){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:ke(),type:t};break;case"AUTH_LOAD":{e={id:ke(),type:t,storageState:""};break}case"AI_EXTRACT":e={id:ke(),type:t,goal:""};break;case"DIALOG":e={id:ke(),type:t,action:"DISMISS"};break;case"DRAG":e={id:ke(),type:t,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ke(),type:t,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ke(),type:t,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ke(),type:t,delay:1};break;case"BLUR":e={id:ke(),type:t};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ke(),type:t,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ke(),type:t,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ke(),type:t,value:""};break;case"SELECT_OPTION":e={id:ke(),type:t,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ke(),type:t,url:""};case"TAB":e={id:ke(),type:t,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ke(),type:t,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ke(),type:t,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ke(),type:t,key:"",value:""};break;case"JAVASCRIPT":e={id:ke(),type:t,code:""};break;case"AI_ASSERTION":e={id:ke(),type:t,assertion:""};break;case"FILE_UPLOAD":{e={id:ke(),type:t,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ke(),type:t,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ke(),type:t,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ke(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ke(),type:t,key:""};break}case"RECORD_REQUESTS":{e={id:ke(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ke(),type:t,key:""};break}case"SET_HEADER":{e={id:ke(),type:t,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ke(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ke(),type:t};break}case"OFFLINE_MODE":{e={id:ke(),type:t,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function rb(t){switch(t.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{z as OD}from"zod";var pX=OD.discriminatedUnion("type",[ol,sh,Ta,va,nl,Aa,Ra,Si,yi,Ea,ba,wa,_a,sl,xa]);function nb(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as LD}from"zod";import{z as wo}from"zod";function ll(t){return wo.object({key:wo.string(),testId:wo.string().optional(),moduleId:wo.string().optional(),organizationId:wo.string(),value:t})}function cl(t){return ll(t).extend({uniqueKey:wo.string()})}function uu(t){return wo.record(wo.string(),cl(t))}var ir={type:!0,cache:!0},Zn=LD.discriminatedUnion("type",[il.pick(ir),ol.pick(ir),Ta.pick(ir),va.pick(ir),xa.pick(ir),nl.pick(ir),Aa.pick(ir),Ra.pick(ir),Si.pick(ir),yi.pick(ir),Ea.pick(ir),ba.pick(ir),wa.pick(ir),_a.pick(ir),sl.pick(ir)]),du=Object.values(Je).filter(t=>Zn.options.some(e=>e.shape.type.safeParse(t).success));Ma.options.forEach(t=>{if("target"in t.shape&&!du.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function pu(t){return du.includes(t.type)}var ob=ll(Zn),ib=cl(Zn),bX=uu(Zn);import{v4 as Ke}from"uuid";import{z as x}from"zod";var sb=Symbol("Let zodToJsonSchema decide on which parser to use");var ab={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},lb=t=>typeof t=="string"?{...ab,name:t}:{...ab,...t};var cb=t=>{let e=lb(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ph(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Ce(t,e,r,n,o){t[e]=r,ph(t,e,n,o)}var mu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};import{ZodFirstPartyTypeKind as Ae}from"zod";function lt(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?mu(e,t.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as ND}from"zod";function ub(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ND.ZodAny&&(r.items=re(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),Ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function db(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Ce(r,"minimum",n.value,n.message,e):Ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Ce(r,"maximum",n.value,n.message,e):Ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":Ce(r,"multipleOf",n.value,n.message,e);break}return r}function pb(){return{type:"boolean"}}function hu(t,e){return re(t.type._def,e)}var mb=(t,e)=>re(t.innerType._def,e);function mh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>mh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return DD(t,e)}}var DD=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Ce(r,"minimum",n.value,n.message,e);break;case"max":Ce(r,"maximum",n.value,n.message,e);break}return r};function hb(t,e){return{...re(t.innerType._def,e),default:t.defaultValue()}}function gb(t,e){return e.effectStrategy==="input"?re(t.schema._def,e):lt(e)}function fb(t){return{type:"string",enum:Array.from(t.values)}}var kD=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Sb(t,e){let r=[re(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),re(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(i=>{if(kD(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function yb(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}import{ZodFirstPartyTypeKind as ul}from"zod";var hh,on={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(hh===void 0&&(hh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hh),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":an(r,"email",n.message,e);break;case"format:idn-email":an(r,"idn-email",n.message,e);break;case"pattern:zod":ar(r,on.email,n.message,e);break}break;case"url":an(r,"uri",n.message,e);break;case"uuid":an(r,"uuid",n.message,e);break;case"regex":ar(r,n.regex,n.message,e);break;case"cuid":ar(r,on.cuid,n.message,e);break;case"cuid2":ar(r,on.cuid2,n.message,e);break;case"startsWith":ar(r,RegExp(`^${gh(n.value,e)}`),n.message,e);break;case"endsWith":ar(r,RegExp(`${gh(n.value,e)}$`),n.message,e);break;case"datetime":an(r,"date-time",n.message,e);break;case"date":an(r,"date",n.message,e);break;case"time":an(r,"time",n.message,e);break;case"duration":an(r,"duration",n.message,e);break;case"length":Ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ar(r,RegExp(gh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&an(r,"ipv4",n.message,e),n.version!=="v4"&&an(r,"ipv6",n.message,e);break}case"base64url":ar(r,on.base64url,n.message,e);break;case"jwt":ar(r,on.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ar(r,on.ipv4Cidr,n.message,e),n.version!=="v4"&&ar(r,on.ipv6Cidr,n.message,e);break}case"emoji":ar(r,on.emoji(),n.message,e);break;case"ulid":{ar(r,on.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{an(r,"binary",n.message,e);break}case"contentEncoding:base64":{Ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ar(r,on.base64,n.message,e);break}}break}case"nanoid":ar(r,on.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function gh(t,e){return e.patternStrategy==="escape"?UD(t):t}var FD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function UD(t){let e="";for(let r=0;r<t.length;r++)FD.has(t[r])||(e+="\\"),e+=t[r];return e}function an(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Ce(t,"format",e,r,n)}function ar(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Eb(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ce(t,"pattern",Eb(e,n),r,n)}function Eb(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",i=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){s?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],s=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="caf37916-b13c-5d5d-bd34-16124b2fedc0")}catch(e){}}();
4
+ var BN=Object.defineProperty;var mt=(t,e)=>()=>(t&&(e=t(t=0)),e);var zN=(t,e)=>{for(var r in e)BN(t,r,{get:e[r],enumerable:!0})};var o_,i_=mt(()=>{"use strict";o_=typeof globalThis=="object"?globalThis:global});var a_=mt(()=>{"use strict";i_()});var s_=mt(()=>{"use strict";a_()});var ho,fS=mt(()=>{"use strict";ho="1.9.0"});function Pj(t){var e=new Set([t]),r=new Set,n=t.match(l_);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(c){return c===t};function i(s){return r.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;var l=c.match(l_);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var l_,c_,u_=mt(()=>{"use strict";fS();l_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;c_=Pj(ho)});function ys(t,e,r,n){var o;n===void 0&&(n=!1);var i=sc[ac]=(o=sc[ac])!==null&&o!==void 0?o:{version:ho};if(!n&&i[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(i.version!==ho){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+ho);return r.error(a.stack||a.message),!1}return i[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+ho+"."),!0}function go(t){var e,r,n=(e=sc[ac])===null||e===void 0?void 0:e.version;if(!(!n||!c_(n)))return(r=sc[ac])===null||r===void 0?void 0:r[t]}function Es(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+ho+".");var r=sc[ac];r&&delete r[t]}var Ij,ac,sc,lc=mt(()=>{"use strict";s_();fS();u_();Ij=ho.split(".")[0],ac=Symbol.for("opentelemetry.js.api."+Ij),sc=o_});function cc(t,e,r){var n=go("diag");if(n)return r.unshift(e),n[t].apply(n,Lj([],Oj(r),!1))}var Oj,Lj,d_,p_=mt(()=>{"use strict";lc();Oj=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Lj=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},d_=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return cc("verbose",this._namespace,e)},t}()});var at,gp=mt(()=>{"use strict";(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(at||(at={}))});function m_(t,e){t<at.NONE?t=at.NONE:t>at.ALL&&(t=at.ALL),e=e||{};function r(n,o){var i=e[n];return typeof i=="function"&&t>=o?i.bind(e):function(){}}return{error:r("error",at.ERROR),warn:r("warn",at.WARN),info:r("info",at.INFO),debug:r("debug",at.DEBUG),verbose:r("verbose",at.VERBOSE)}}var h_=mt(()=>{"use strict";gp()});var Nj,Dj,kj,Bn,uc=mt(()=>{"use strict";p_();h_();gp();lc();Nj=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Dj=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},kj="diag",Bn=function(){function t(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=go("diag");if(s)return s[o].apply(s,Dj([],Nj(i),!1))}}var r=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:at.INFO}),o===r){var l=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=go("diag"),d=m_((s=i.logLevel)!==null&&s!==void 0?s:at.INFO,o);if(u&&!i.suppressOverrideMessage){var p=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return ys("diag",d,r,!0)};r.setLogger=n,r.disable=function(){Es(kj,r)},r.createComponentLogger=function(o){return new d_(o)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}()});var g_,f_=mt(()=>{"use strict";g_=Symbol("BaggageEntryMetadata")});function SS(t){return typeof t!="string"&&(Fj.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:g_,toString:function(){return t}}}var Fj,S_=mt(()=>{"use strict";uc();f_();Fj=Bn.instance()});function yS(t){return Symbol.for(t)}var Uj,ES,bS=mt(()=>{"use strict";Uj=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var i=new t(r._currentContext);return i._currentContext.set(n,o),i},r.deleteValue=function(n){var o=new t(r._currentContext);return o._currentContext.delete(n),o}}return t}(),ES=new Uj});function RS(){return vS}var Ki,Bj,fp,zj,Hj,Gj,jj,TS,Vj,$j,Wj,vS,qj,Kj,Yj,Xj,Jj,Qj,Zj,AS=mt(()=>{"use strict";Ki=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Bj=function(){function t(){}return t.prototype.createGauge=function(e,r){return Kj},t.prototype.createHistogram=function(e,r){return Yj},t.prototype.createCounter=function(e,r){return qj},t.prototype.createUpDownCounter=function(e,r){return Xj},t.prototype.createObservableGauge=function(e,r){return Qj},t.prototype.createObservableCounter=function(e,r){return Jj},t.prototype.createObservableUpDownCounter=function(e,r){return Zj},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),fp=function(){function t(){}return t}(),zj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(fp),Hj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e}(fp),Gj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(fp),jj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e}(fp),TS=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),Vj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(TS),$j=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(TS),Wj=function(t){Ki(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(TS),vS=new Bj,qj=new zj,Kj=new Gj,Yj=new jj,Xj=new Hj,Jj=new Vj,Qj=new $j,Zj=new Wj});var Pr,y_=mt(()=>{"use strict";(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(Pr||(Pr={}))});var eV,tV,E_,b_=mt(()=>{"use strict";bS();eV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},tV=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},E_=function(){function t(){}return t.prototype.active=function(){return ES},t.prototype.with=function(e,r,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return r.call.apply(r,tV([n],eV(o),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}()});var rV,nV,wS,oV,T_,v_=mt(()=>{"use strict";b_();lc();uc();rV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},nV=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},wS="context",oV=new E_,T_=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return ys(wS,e,Bn.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,nV([e,r,n],rV(i),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return go(wS)||oV},t.prototype.disable=function(){this._getContextManager().disable(),Es(wS,Bn.instance())},t}()});var bs,R_=mt(()=>{"use strict";v_();bs=T_.getInstance()});var K,A_=mt(()=>{"use strict";uc();K=Bn.instance()});var iV,w_,C_=mt(()=>{"use strict";AS();iV=function(){function t(){}return t.prototype.getMeter=function(e,r,n){return vS},t}(),w_=new iV});var CS,x_,__=mt(()=>{"use strict";C_();lc();uc();CS="metrics",x_=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return ys(CS,e,Bn.instance())},t.prototype.getMeterProvider=function(){return go(CS)||w_},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){Es(CS,Bn.instance())},t}()});var Sp,M_=mt(()=>{"use strict";__();Sp=x_.getInstance()});var Je=mt(()=>{"use strict";S_();bS();gp();AS();y_();R_();A_();M_()});var Xs=(t,e)=>{},nh=!1;try{let t=await import("@sentry/node");Xs=t.captureException,t.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),nh=!0}catch{}import{Command as u5,Option as hr}from"@commander-js/extra-typings";import{execSync as d5}from"child_process";import{existsSync as eB,statSync as tB}from"fs";import{z as oh}from"zod";var R5=oh.object({input:oh.string(),agentConfigVersion:oh.string().optional()});import{z as Pt}from"zod";var C5=Pt.object({srcs:Pt.array(Pt.string()),urls:Pt.array(Pt.string()),desiredSrc:Pt.string().optional(),desiredUrl:Pt.string().optional()}),CE=Pt.object({srcRegex:Pt.string().optional(),urlRegex:Pt.string().optional()}),xE=Pt.object({x:Pt.number(),y:Pt.number(),correlation:Pt.number()}),x5=Pt.object({searchImageBase64String:Pt.string(),pageImageBase64String:Pt.string(),id:Pt.string().uuid(),timeoutMs:Pt.number().max(1e4).min(0).optional()});import{z as P}from"zod";import*as k from"zod";import{extendZodWithOpenApi as HN}from"zod-openapi";HN(k);var vo=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(vo||{}),GN=k.object({mPathSelectorTokens:k.string().array(),frameSrcRegex:k.string().optional(),frameUrlRegex:k.string().optional(),indices:k.number().array()}),Js=k.object({result:k.number(),traceId:k.string()}).array(),Xn=k.object({type:k.literal("GCS_TRACES"),traces:Js}),gr=(o=>(o.PRECISE="precise",o.NARROW="narrow",o.BROAD="broad",o.IRRELEVANT="irrelevant",o))(gr||{}),_E=k.object({attributes:k.record(k.string(),k.string()).optional(),text:k.string().optional(),position:k.object({x1:k.number(),y1:k.number(),x2:k.number(),y2:k.number(),tolerance:k.nativeEnum(gr)}).optional(),shape:k.object({width:k.number(),height:k.number(),tolerance:k.nativeEnum(gr)}).optional(),boundingBox:k.object({x:k.number(),y:k.number(),width:k.number(),height:k.number()}).optional()}),jN=k.object({selectors:k.string().array(),requirements:_E.optional()}),Ro=k.object({id:k.number().int(),dataMomenticId:k.number().int().optional(),selector:k.string().optional(),hybridSelector:k.object({textContent:k.string().nullish(),attributes:k.record(k.string(),k.string().optional()),tagName:k.string(),expandShadowRoot:k.boolean().optional(),classNames:k.string().array(),nthChild:k.number()}).array().optional(),generatedSelectors:k.string().array().optional(),requirements:_E.optional(),additionalElements:jN.array().optional(),role:k.string().optional(),name:k.string().optional(),numChildren:k.number().optional(),content:k.string().optional(),pathFromRoot:k.string().optional(),serializedHtml:k.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:k.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:k.string().url().optional(),boundingBox:k.object({x:k.number().optional(),y:k.number().optional(),width:k.number(),height:k.number()}).describe("css pixel bounding box").optional(),frameCache:GN.optional(),inputDescription:k.string().optional().describe("the description that generated this cache"),targetSource:k.nativeEnum(vo).optional(),targetUpdateTime:k.string().optional(),targetUpdateLoggerTags:k.record(k.string(),k.string()).optional(),cacheResolutionUpdateSource:k.string().optional(),cacheResolutionUpdateTime:k.string().optional(),cacheResolutionUpdateLoggerTags:k.record(k.string(),k.string()).optional(),memory:Xn.optional()}).openapi({ref:"ElementTargetCache"});function ru(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var VN=k.object({type:k.literal("description"),elementDescriptor:k.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),$N=k.object({x:k.number(),y:k.number()}),WN=k.object({type:k.literal("coordinates"),pixels:$N}).openapi({ref:"CoordinatesTarget"});function Ao(t){return t.type==="description"}function bn(t){return t.type==="coordinates"}var $t=k.discriminatedUnion("type",[VN,WN]).openapi({ref:"ElementTarget"});function ih(t){if(!t)return!1;switch(t.type){case"description":return!!t.elementDescriptor}return!0}function Wt(t){if(!t)return"";switch(t.type){case"description":return t.elementDescriptor;case"coordinates":return`x: ${t.pixels.x}, y: ${t.pixels.y}`}}function nu(t){return Xn.safeParse(t).success}import{v4 as ke}from"uuid";import*as R from"zod";import{extendZodWithOpenApi as nD}from"zod-openapi";import{z as Ee}from"zod";import{extendZodWithOpenApi as qN}from"zod-openapi";import{z as Zs}from"zod";import ME from"zod";var Qs=ME.object({updatedAt:ME.coerce.date().optional()});var el=Zs.object({result:Zs.boolean(),traceId:Zs.string()}).array(),tl=Zs.object({type:Zs.literal("GCS_TRACES"),traces:el}),ya=Qs.extend({memory:tl.optional()});qN(Ee);var PE=Ee.object({thoughts:Ee.string(),result:Ee.boolean(),relevantElements:Ee.array(Ee.number()).optional(),updatedMemory:el.optional()}),nn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(nn||{});var KN=Ee.object({type:Ee.literal("ELEMENT_NAME"),negated:Ee.boolean().optional(),operation:Ee.nativeEnum(nn),value:Ee.string()}).openapi({ref:"ElementNameAssertion"}),YN=Ee.object({type:Ee.literal("ELEMENT_STYLE"),negated:Ee.boolean().optional(),operation:Ee.nativeEnum(nn),property:Ee.string(),value:Ee.string()}).openapi({ref:"ElementStyleAssertion"}),XN=Ee.object({type:Ee.literal("ELEMENT_CONTENT"),negated:Ee.boolean().optional(),operation:Ee.nativeEnum(nn),value:Ee.string()}).openapi({ref:"ElementContentAssertion"}),JN=Ee.object({type:Ee.literal("ELEMENT_ATTRIBUTE"),negated:Ee.boolean().optional(),operation:Ee.nativeEnum(nn),attr:Ee.string(),value:Ee.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Jn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Jn||{});var QN=Ee.object({type:Ee.literal("ELEMENT_EXISTENCE"),negated:Ee.boolean().optional(),condition:Ee.nativeEnum(Jn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),ou=Ee.discriminatedUnion("type",[XN,JN,QN,KN,YN]).openapi({ref:"ManualElementAssertion"});var ZN=Ee.object({type:Ee.literal("CONTENT"),negated:Ee.boolean().optional(),value:Ee.string()}).openapi({ref:"PageContentAssertion"}),IE=Ee.discriminatedUnion("type",[ZN]).openapi({ref:"ManualPageAssertion"});import or from"zod";var ah=or.discriminatedUnion("type",[or.object({type:or.literal("SUBSTRING"),url:or.string()}),or.object({type:or.literal("GLOB"),glob:or.string()}),or.object({type:or.literal("REGEX"),regex:or.string()}),or.object({type:or.literal("DOMAIN"),domain:or.string()})]),rl=or.object({urlMatcher:ah,method:or.string().optional()});import{z as ge}from"zod";var eD=ge.object({type:ge.literal("json"),content:ge.string().describe("The JSON content to send in the request body")}),tD=ge.object({type:ge.literal("form-urlencoded"),content:ge.record(ge.string(),ge.string()).describe("The form fields to send in the request body")}),rD=ge.discriminatedUnion("type",[eD,tD]),gi=ge.object({url:ge.string(),method:ge.union([ge.literal("GET"),ge.literal("POST"),ge.literal("PUT"),ge.literal("DELETE"),ge.literal("PATCH")]),headers:ge.record(ge.string(),ge.string()).optional(),params:ge.record(ge.string(),ge.string()).optional(),body:rD.optional(),timeout:ge.number().int().optional().describe("Max seconds to wait for the request to complete")}),OE=ge.object({url:ge.string(),headers:ge.record(ge.string(),ge.string()).optional(),query:ge.string(),variables:ge.string().optional(),timeout:ge.number().int().optional().describe("Max seconds to wait for the request to complete")}),iu=ge.object({code:ge.string(),fragment:ge.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:ge.union([ge.literal("NODE"),ge.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:ge.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Qe=(J=>(J.AI_EXTRACT="AI_EXTRACT",J.AI_ASSERTION="AI_ASSERTION",J.AUTH_LOAD="AUTH_LOAD",J.AUTH_SAVE="AUTH_SAVE",J.BLUR="BLUR",J.CAPTCHA="CAPTCHA",J.CLICK="CLICK",J.COOKIE="COOKIE",J.COPY="COPY",J.DIALOG="DIALOG",J.DRAG="DRAG",J.ELEMENT_CHECK="ELEMENT_CHECK",J.FILE_UPLOAD="FILE_UPLOAD",J.FOCUS="FOCUS",J.GO_BACK="GO_BACK",J.GO_FORWARD="GO_FORWARD",J.HOVER="HOVER",J.JAVASCRIPT="JAVASCRIPT",J.LOCAL_STORAGE="LOCAL_STORAGE",J.MOUSE_DRAG="MOUSE_DRAG",J.NAVIGATE="NAVIGATE",J.NEW_TAB="NEW_TAB",J.PAGE_CHECK="PAGE_CHECK",J.PASTE="PASTE",J.PRESS="PRESS",J.KEY_DOWN="KEY_DOWN",J.KEY_UP="KEY_UP",J.REFRESH="REFRESH",J.REQUEST="REQUEST",J.GRAPHQL_REQUEST="GRAPHQL_REQUEST",J.SCROLL_DOWN="SCROLL_DOWN",J.SCROLL_UP="SCROLL_UP",J.SCROLL_LEFT="SCROLL_LEFT",J.SCROLL_RIGHT="SCROLL_RIGHT",J.SELECT_OPTION="SELECT_OPTION",J.SWITCH_TAB="TAB",J.TYPE="TYPE",J.VISUAL_DIFF="VISUAL_DIFF",J.WAIT="WAIT",J.WAIT_FOR_URL="WAIT_FOR_URL",J.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",J.AWAIT_LISTENER="AWAIT_LISTENER",J.RECORD_REQUESTS="RECORD_REQUESTS",J.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",J.SET_HEADER="SET_HEADER",J.MOCK_ROUTE="MOCK_ROUTE",J.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",J.OFFLINE_MODE="OFFLINE_MODE",J.SUCCESS="SUCCESS",J))(Qe||{});nD(R);var re=R.object({thoughts:R.string().optional(),id:R.string().uuid().describe("unique identifier to this step, used for step cache")}),Dr=R.object({useSelector:R.boolean().optional(),force:R.boolean().optional(),disableCache:R.boolean().optional().describe("disable element caching for this step"),iframeUrl:R.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Rr=Qs.extend({target:Ro}).optional().openapi({ref:"SingleTargetCache"});function LE(t){return Rr.safeParse(t).success}var su=R.object({loadTimeout:R.number().int().max(60).optional().describe("Max seconds for the page to load")}),NE=re.merge(su).merge(R.object({type:R.literal("NAVIGATE"),url:R.string()})).openapi({ref:"NavigateCommand"}),lu=Dr.merge(R.object({cache:Rr})),Si=re.merge(lu.merge(R.object({target:$t.optional(),type:R.literal("SCROLL_UP"),deltaY:R.number().optional()}))).openapi({ref:"ScrollUpCommand"}),yi=re.merge(lu.merge(R.object({target:$t.optional(),type:R.literal("SCROLL_DOWN"),deltaY:R.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Ea=re.merge(lu.merge(R.object({target:$t.optional(),type:R.literal("SCROLL_LEFT"),deltaX:R.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),ba=re.merge(lu.merge(R.object({target:$t.optional(),type:R.literal("SCROLL_RIGHT"),deltaX:R.number().optional()}))).openapi({ref:"ScrollRightCommand"}),iX=R.discriminatedUnion("type",[Si,yi,Ea,ba]).openapi({ref:"AllScrollCommands"}),oD=re.merge(R.object({type:R.literal("DIALOG"),action:R.union([R.literal("ACCEPT"),R.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),DE=re.merge(R.object({type:R.literal("WAIT"),delay:R.number()})).openapi({ref:"WaitCommand"}),iD=R.object({caseInsensitive:R.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:R.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:R.number().int().optional().describe("Max seconds to wait for the URL to match")}),kE=re.extend({type:R.literal("WAIT_FOR_URL"),matcher:ah}).merge(iD).openapi({ref:"WaitUrlCommand"}),FE=re.merge(su).merge(R.object({type:R.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),UE=re.merge(R.object({type:R.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),BE=re.merge(R.object({type:R.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),aD=re.extend({type:R.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),sD=re.extend({type:R.literal("AUTH_LOAD"),storageState:R.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),sh=re.merge(Dr).extend({type:R.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),zE=re.extend({type:R.literal("COPY"),value:R.string()}).openapi({ref:"CopyCommand"}),HE=re.extend({type:R.literal("PASTE")}).openapi({ref:"PasteCommand"}),GE=re.merge(iu).extend({type:R.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Ta=re.merge(Dr).extend({type:R.literal("CLICK"),target:$t,doubleClick:R.boolean().optional(),rightClick:R.boolean().optional(),waitForDownload:R.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:R.number().optional(),downloadTimeoutMs:R.number().optional(),cache:Rr,relativePosition:R.object({x:R.number(),y:R.number()}).optional()}).openapi({ref:"ClickCommand"}),lh=Qs.extend({fromTarget:Ro.optional(),toTarget:Ro.optional()}),va=re.merge(Dr).merge(R.object({type:R.literal("DRAG"),fromTarget:$t,toTarget:$t,steps:R.number().optional(),hoverSeconds:R.number().optional().describe("Seconds to hover the object before dropping"),cache:lh.optional()})).openapi({ref:"DragCommand"}),Ra=re.merge(Dr).merge(R.object({type:R.literal("MOUSE_DRAG"),target:$t.optional(),deltaX:R.string().describe("pixels to move horizontally, can be template"),deltaY:R.string().describe("pixels to move vertically, can be template"),steps:R.number().optional(),cache:Rr})).openapi({ref:"MouseDragCommand"}),Aa=re.merge(Dr).merge(R.object({type:R.literal("HOVER"),target:$t,cache:Rr})).openapi({ref:"HoverCommand"}),nl=re.merge(Dr).merge(R.object({type:R.literal("FOCUS"),target:$t,cache:Rr})).openapi({ref:"FocusCommand"}),ol=re.merge(Dr).extend({type:R.literal("BLUR"),target:$t.optional(),cache:Rr}).openapi({ref:"BlurCommand"}),lD=R.object({type:R.literal("URL"),url:R.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),cD=R.object({type:R.literal("USER_FILE"),name:R.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),uD=re.extend({type:R.literal("FILE_UPLOAD"),fileSource:R.discriminatedUnion("type",[lD,cD]),filename:R.string().optional()}).openapi({ref:"FileUploadCommand"}),ch=R.discriminatedUnion("type",[R.object({type:R.literal("VALUE"),value:R.string()}),R.object({type:R.literal("LABEL"),label:R.string()}),R.object({type:R.literal("INDEX"),index:R.coerce.string()})]),wa=re.merge(Dr).extend({type:R.literal("SELECT_OPTION"),target:$t,cache:Rr,choice:ch.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),uh=R.union([R.literal("MULTIMODAL"),R.literal("VISION_ONLY")]),il=re.merge(R.object({type:R.literal("AI_ASSERTION"),assertion:R.string(),disableCache:R.boolean().optional(),iframeUrl:R.string().optional(),contextChoice:uh.optional(),timeout:R.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:ya.optional()})).openapi({ref:"AIAssertionCommand"}),Tn=5,Ca=600,xa=re.merge(Dr).extend({type:R.literal("ELEMENT_CHECK"),target:$t,assertion:ou,cache:Rr.or(ya).optional(),timeout:R.number().int().min(0).max(Ca).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),jE=re.extend({type:R.literal("PAGE_CHECK"),assertion:IE,iframeUrl:R.string().optional().describe("url or url regex for the iframe"),timeout:R.number().int().min(0).max(Ca).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),VE=re.merge(R.object({type:R.literal("AI_EXTRACT"),goal:R.string(),schema:R.string().optional(),envKey:R.string().optional(),disableCache:R.boolean().optional(),iframeUrl:R.string().optional()})).openapi({ref:"AIExtractCommand"}),dD=R.object({clearContent:R.boolean().optional(),forceClearContent:R.boolean().optional(),delay:R.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:R.boolean().optional(),pressEnter:R.boolean().optional(),relativePosition:R.object({x:R.number(),y:R.number()}).optional()}),$E=25,_a=re.merge(Dr).merge(dD).extend({type:R.literal("TYPE"),target:$t.optional(),value:R.string(),cache:Rr}).openapi({ref:"TypeCommand"}),WE=re.merge(R.object({type:R.literal("PRESS"),value:R.string(),repeat:R.number().optional(),convertMeta:R.boolean().optional(),delayMs:R.number().optional()})).openapi({ref:"PressCommand"}),qE=re.merge(R.object({type:R.literal("KEY_DOWN"),value:R.string(),convertMeta:R.boolean().optional()})).openapi({ref:"KeyDownCommand"}),KE=re.merge(R.object({type:R.literal("KEY_UP"),value:R.string(),convertMeta:R.boolean().optional()})).openapi({ref:"KeyUpCommand"}),pD=R.object({type:R.literal("SUBSTRING"),substring:R.string()}),mD=R.object({type:R.literal("REGEX"),pattern:R.string()}),hD=R.object({type:R.literal("INDEX"),index:R.coerce.string()}),gD=R.discriminatedUnion("type",[pD,mD,hD]),fD=re.merge(su).merge(R.object({type:R.literal("TAB"),action:gD})).openapi({ref:"TabCommand"}),YE=re.merge(su).merge(R.object({type:R.literal("NEW_TAB"),url:R.string()})).openapi({ref:"NewTabCommand"}),SD=re.merge(R.object({type:R.literal("COOKIE"),value:R.string()})).openapi({ref:"CookieCommand"}),XE=re.merge(R.object({type:R.literal("LOCAL_STORAGE"),key:R.string(),value:R.string()})).openapi({ref:"LocalStorageCommand"}),JE=re.extend({type:R.literal("REQUEST")}).merge(gi).openapi({ref:"RequestCommand"}),al=R.object({status:R.number().optional(),headers:R.record(R.string(),R.string()),json:R.unknown().optional(),text:R.string().optional(),cookies:R.record(R.string(),R.unknown()).array().optional(),request:R.object({url:R.string(),method:R.string(),headers:R.record(R.string(),R.string()),json:R.unknown().optional()})}),QE=re.extend({type:R.literal("GRAPHQL_REQUEST")}).merge(OE).openapi({ref:"GraphQLRequestCommand"}),ZE=re.merge(R.object({type:R.literal("SUCCESS"),condition:il.optional()})).openapi({ref:"SuccessCommand"}),eb=re.merge(R.object({type:R.literal("FAILURE")})).openapi({ref:"FailureCommand"}),yD=R.object({data:R.string().describe("location at which to find a jpg"),width:R.number(),height:R.number()}),sl=re.merge(Dr).merge(R.object({type:R.literal("VISUAL_DIFF"),threshold:R.number().optional().describe("default 0.1"),target:$t.optional(),screenshot:yD.optional(),cache:Rr})).openapi({ref:"VisualDiffCommand"}),ED=re.merge(R.object({type:R.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:rl,key:R.string()})).openapi({ref:"RegisterRequestListenerCommand"}),bD=re.merge(R.object({type:R.literal("AWAIT_LISTENER"),key:R.string(),timeout:R.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),TD=re.merge(R.object({type:R.literal("RECORD_REQUESTS"),requestMatcher:rl,key:R.string()})).openapi({ref:"RecordRequestsCommand"}),vD=re.merge(R.object({type:R.literal("GET_RECORDED_REQUESTS"),key:R.string()})).openapi({ref:"GetRecordedRequestsCommand"}),RD=re.merge(R.object({type:R.literal("SET_HEADER"),name:R.string(),value:R.string(),requestMatcher:rl.optional()})).openapi({ref:"SetHeaderCommand"}),AD=re.merge(R.object({type:R.literal("MOCK_ROUTE"),requestMatcher:rl,responseGenerator:R.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:R.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:R.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),wD=re.merge(R.object({type:R.literal("REMOVE_ROUTE_MOCK"),key:R.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),CD=re.merge(R.object({type:R.literal("OFFLINE_MODE"),enable:R.boolean()})).openapi({ref:"OfflineModeCommand"}),xD=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],aX=[...xD,"DRAG"],_D=R.discriminatedUnion("type",[Ta,_a,WE,qE,KE,wa,NE,yi,Si,il,UE,Aa,DE]),MD=R.discriminatedUnion("type",[..._D.options,va]),PD=R.discriminatedUnion("type",[...MD.options]),tb=R.discriminatedUnion("type",[...PD.options,ZE]),dh=R.discriminatedUnion("type",[ZE,Ta,_a,WE,qE,KE,wa,NE,yi,Si,il,UE,Aa,DE,GE,xa,jE,YE,kE,VE,zE,BE,XE,va,Ra,HE,FE,JE,QE]),ID=R.discriminatedUnion("type",[VE,sD,aD,sh,SD,zE,oD,xa,uD,BE,GE,XE,Ra,YE,jE,HE,FE,JE,QE,Ea,ba,fD,sl,nl,ol,kE,ED,bD,TD,vD,RD,AD,wD,CD]),Ma=R.discriminatedUnion("type",[...tb.options,...ID.options]).openapi({ref:"Command"}),cu=R.discriminatedUnion("type",[...tb.options,eb]),sX=R.discriminatedUnion("type",[...dh.options,eb]);function Qn(t){let e;switch(t){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:ke(),type:t};break;case"AUTH_LOAD":{e={id:ke(),type:t,storageState:""};break}case"AI_EXTRACT":e={id:ke(),type:t,goal:""};break;case"DIALOG":e={id:ke(),type:t,action:"DISMISS"};break;case"DRAG":e={id:ke(),type:t,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ke(),type:t,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ke(),type:t,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ke(),type:t,delay:1};break;case"BLUR":e={id:ke(),type:t};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ke(),type:t,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ke(),type:t,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ke(),type:t,value:""};break;case"SELECT_OPTION":e={id:ke(),type:t,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ke(),type:t,url:""};case"TAB":e={id:ke(),type:t,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ke(),type:t,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ke(),type:t,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ke(),type:t,key:"",value:""};break;case"JAVASCRIPT":e={id:ke(),type:t,code:""};break;case"AI_ASSERTION":e={id:ke(),type:t,assertion:""};break;case"FILE_UPLOAD":{e={id:ke(),type:t,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ke(),type:t,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ke(),type:t,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ke(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ke(),type:t,key:""};break}case"RECORD_REQUESTS":{e={id:ke(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ke(),type:t,key:""};break}case"SET_HEADER":{e={id:ke(),type:t,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ke(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ke(),type:t};break}case"OFFLINE_MODE":{e={id:ke(),type:t,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function rb(t){switch(t.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{z as OD}from"zod";var pX=OD.discriminatedUnion("type",[ol,sh,Ta,va,nl,Aa,Ra,Si,yi,Ea,ba,wa,_a,sl,xa]);function nb(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as LD}from"zod";import{z as wo}from"zod";function ll(t){return wo.object({key:wo.string(),testId:wo.string().optional(),moduleId:wo.string().optional(),organizationId:wo.string(),value:t})}function cl(t){return ll(t).extend({uniqueKey:wo.string()})}function uu(t){return wo.record(wo.string(),cl(t))}var ir={type:!0,cache:!0},Zn=LD.discriminatedUnion("type",[il.pick(ir),ol.pick(ir),Ta.pick(ir),va.pick(ir),xa.pick(ir),nl.pick(ir),Aa.pick(ir),Ra.pick(ir),Si.pick(ir),yi.pick(ir),Ea.pick(ir),ba.pick(ir),wa.pick(ir),_a.pick(ir),sl.pick(ir)]),du=Object.values(Qe).filter(t=>Zn.options.some(e=>e.shape.type.safeParse(t).success));Ma.options.forEach(t=>{if("target"in t.shape&&!du.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function pu(t){return du.includes(t.type)}var ob=ll(Zn),ib=cl(Zn),bX=uu(Zn);import{v4 as Ye}from"uuid";import{z as x}from"zod";var sb=Symbol("Let zodToJsonSchema decide on which parser to use");var ab={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},lb=t=>typeof t=="string"?{...ab,name:t}:{...ab,...t};var cb=t=>{let e=lb(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ph(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Ce(t,e,r,n,o){t[e]=r,ph(t,e,n,o)}var mu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};import{ZodFirstPartyTypeKind as Ae}from"zod";function lt(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?mu(e,t.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as ND}from"zod";function ub(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ND.ZodAny&&(r.items=ne(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),Ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function db(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Ce(r,"minimum",n.value,n.message,e):Ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Ce(r,"maximum",n.value,n.message,e):Ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":Ce(r,"multipleOf",n.value,n.message,e);break}return r}function pb(){return{type:"boolean"}}function hu(t,e){return ne(t.type._def,e)}var mb=(t,e)=>ne(t.innerType._def,e);function mh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>mh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return DD(t,e)}}var DD=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Ce(r,"minimum",n.value,n.message,e);break;case"max":Ce(r,"maximum",n.value,n.message,e);break}return r};function hb(t,e){return{...ne(t.innerType._def,e),default:t.defaultValue()}}function gb(t,e){return e.effectStrategy==="input"?ne(t.schema._def,e):lt(e)}function fb(t){return{type:"string",enum:Array.from(t.values)}}var kD=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Sb(t,e){let r=[ne(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ne(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(i=>{if(kD(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function yb(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}import{ZodFirstPartyTypeKind as ul}from"zod";var hh,on={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(hh===void 0&&(hh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hh),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":an(r,"email",n.message,e);break;case"format:idn-email":an(r,"idn-email",n.message,e);break;case"pattern:zod":ar(r,on.email,n.message,e);break}break;case"url":an(r,"uri",n.message,e);break;case"uuid":an(r,"uuid",n.message,e);break;case"regex":ar(r,n.regex,n.message,e);break;case"cuid":ar(r,on.cuid,n.message,e);break;case"cuid2":ar(r,on.cuid2,n.message,e);break;case"startsWith":ar(r,RegExp(`^${gh(n.value,e)}`),n.message,e);break;case"endsWith":ar(r,RegExp(`${gh(n.value,e)}$`),n.message,e);break;case"datetime":an(r,"date-time",n.message,e);break;case"date":an(r,"date",n.message,e);break;case"time":an(r,"time",n.message,e);break;case"duration":an(r,"duration",n.message,e);break;case"length":Ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ar(r,RegExp(gh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&an(r,"ipv4",n.message,e),n.version!=="v4"&&an(r,"ipv6",n.message,e);break}case"base64url":ar(r,on.base64url,n.message,e);break;case"jwt":ar(r,on.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ar(r,on.ipv4Cidr,n.message,e),n.version!=="v4"&&ar(r,on.ipv6Cidr,n.message,e);break}case"emoji":ar(r,on.emoji(),n.message,e);break;case"ulid":{ar(r,on.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{an(r,"binary",n.message,e);break}case"contentEncoding:base64":{Ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ar(r,on.base64,n.message,e);break}}break}case"nanoid":ar(r,on.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function gh(t,e){return e.patternStrategy==="escape"?UD(t):t}var FD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function UD(t){let e="";for(let r=0;r<t.length;r++)FD.has(t[r])||(e+="\\"),e+=t[r];return e}function an(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Ce(t,"format",e,r,n)}function ar(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Eb(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ce(t,"pattern",Eb(e,n),r,n)}function Eb(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",i=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){s?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],s=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
5
5
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
6
6
  ]))`;continue}}if(r.s&&n[c]==="."){o+=a?`${n[c]}\r
7
7
  `:`[${n[c]}\r
8
- ]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function fu(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===ul.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??lt(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===ul.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=gu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===ul.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===ul.ZodBranded&&t.keyType._def.type._def.typeName===ul.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=hu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function bb(t,e){if(e.mapStrategy==="record")return fu(t,e);let r=re(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||lt(e),n=re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||lt(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Tb(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function vb(t){return t.target==="openAi"?void 0:{not:lt({...t,currentPath:[...t.currentPath,"not"]})}}function Rb(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var dl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function wb(t,e){if(e.target==="openApi3")return Ab(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in dl&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=dl[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Ab(t,e)}var Ab=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>re(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Cb(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:dl[t.innerType._def.typeName],nullable:!0}:{type:[dl[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=re(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function xb(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ph(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Ce(r,"minimum",n.value,n.message,e):Ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Ce(r,"maximum",n.value,n.message,e):Ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":Ce(r,"multipleOf",n.value,n.message,e);break}return r}function _b(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let l=zD(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=re(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||o.push(s))}o.length&&(n.required=o);let a=BD(t,e);return a!==void 0&&(n.additionalProperties=a),n}function BD(t,e){if(t.catchall._def.typeName!=="ZodNever")return re(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function zD(t){try{return t.isOptional()}catch{return!0}}var Mb=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return re(t.innerType._def,e);let r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:lt(e)},r]}:lt(e)};var Pb=(t,e)=>{if(e.pipeStrategy==="input")return re(t.in._def,e);if(e.pipeStrategy==="output")return re(t.out._def,e);let r=re(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=re(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Ib(t,e){return re(t.type._def,e)}function Ob(t,e){let n={type:"array",uniqueItems:!0,items:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Lb(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:re(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Nb(t){return{not:lt(t)}}function Db(t){return lt(t)}var kb=(t,e)=>re(t.innerType._def,e);var Fb=(t,e,r)=>{switch(e){case Ae.ZodString:return gu(t,r);case Ae.ZodNumber:return xb(t,r);case Ae.ZodObject:return _b(t,r);case Ae.ZodBigInt:return db(t,r);case Ae.ZodBoolean:return pb();case Ae.ZodDate:return mh(t,r);case Ae.ZodUndefined:return Nb(r);case Ae.ZodNull:return Rb(r);case Ae.ZodArray:return ub(t,r);case Ae.ZodUnion:case Ae.ZodDiscriminatedUnion:return wb(t,r);case Ae.ZodIntersection:return Sb(t,r);case Ae.ZodTuple:return Lb(t,r);case Ae.ZodRecord:return fu(t,r);case Ae.ZodLiteral:return yb(t,r);case Ae.ZodEnum:return fb(t);case Ae.ZodNativeEnum:return Tb(t);case Ae.ZodNullable:return Cb(t,r);case Ae.ZodOptional:return Mb(t,r);case Ae.ZodMap:return bb(t,r);case Ae.ZodSet:return Ob(t,r);case Ae.ZodLazy:return()=>t.getter()._def;case Ae.ZodPromise:return Ib(t,r);case Ae.ZodNaN:case Ae.ZodNever:return vb(r);case Ae.ZodEffects:return gb(t,r);case Ae.ZodAny:return lt(r);case Ae.ZodUnknown:return Db(r);case Ae.ZodDefault:return hb(t,r);case Ae.ZodBranded:return hu(t,r);case Ae.ZodReadonly:return kb(t,r);case Ae.ZodCatch:return mb(t,r);case Ae.ZodPipeline:return Pb(t,r);case Ae.ZodFunction:case Ae.ZodVoid:case Ae.ZodSymbol:return;default:return(n=>{})(e)}};function re(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==sb)return s}if(n&&!r){let s=HD(n,e);if(s!==void 0)return s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=Fb(t,t.typeName,e),a=typeof i=="function"?re(i(),e):i;if(a&&GD(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var HD=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:mu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),lt(e)):e.$refStrategy==="seen"?lt(e):void 0}},GD=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var pl=(t,e)=>{let r=cb(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:re(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??lt(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=re(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??lt(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};import{z as vn}from"zod";import{extendZodWithOpenApi as jD}from"zod-openapi";jD(vn);var Re=(p=>(p.AI_PROVIDER="AIProviderError",p.USER_INFRA="UserInfrastructureError",p.ACTION_FAILURE="ActionFailureError",p.ASSERTION_FAILURE="AssertionFailureError",p.CONFIG_ERROR="UserConfigurationError",p.SETUP_FAILURE="SetupFailureError",p.TEARDOWN_FAILURE="TeardownFailureError",p.WEB_AGENT_PLATFORM="InternalWebAgentError",p.UNKNOWN_PLATFORM="InternalPlatformError",p.JOB_TIMEOUT="JobTimeoutError",p.CONCURRENCY_ERROR="ConcurrencyError",p.UNKNOWN="UnknownError",p))(Re||{});var Ub=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Su={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",SetupFailureError:"Setup failure",TeardownFailureError:"Teardown failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",ConcurrencyError:"Concurrency error"},Pa={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",SetupFailureError:"A setup step failed to execute, preventing the main test from running. This indicates an issue with test preparation, prerequisite steps, or initial state. This can only apply to failures that occur before teardown.",TeardownFailureError:"A teardown step failed to execute after the main test completed. This indicates an issue with cleanup or post-test operations or an uncaught error in the test. This can only apply to failures that occur after setup.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},fh=vn.object({reason:vn.nativeEnum(Re),previousStepsDescription:vn.array(vn.string()).optional(),summary:vn.string(),rootCause:vn.string().optional()}).openapi({ref:"TestResultClassification"}),yu=vn.object({errorMessage:vn.string(),errorStack:vn.string().optional(),classification:fh.optional()}).openapi({ref:"TestFailureDetails"});var ot=class extends Error{constructor(e,r={}){super(e,r),this.name="ValidationError"}};var Co=class extends Error{zodIssues;constructor(e,r,n,o={}){super(`The ${n} with id ${r} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function Bb(t){for(let e of Object.values(Re))if(t.includes(e))return e}var M=class extends Error{reason;constructor(e,r,n){let o=!1;for(let i of Object.values(Re))if(r.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?r:`${e}: ${r}`,n?.errOptions);else{let i=o?r:`${e}${r?`: ${r}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},Ia=class extends Error{updatedLocatorMemory;constructor(e,r,n={}){super(e,n),this.updatedLocatorMemory=r,this.name="NoElementsFoundUsingAIError"}};var kr=class extends Error{decisions;cacheMissReason;constructor(e,r,n,o={}){super(e,o),this.decisions=r,this.name="NoElementsFoundUsingCacheError",this.cacheMissReason=n}toString(){return`${this.message}
8
+ ]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function fu(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===ul.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??lt(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===ul.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=gu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===ul.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===ul.ZodBranded&&t.keyType._def.type._def.typeName===ul.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=hu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function bb(t,e){if(e.mapStrategy==="record")return fu(t,e);let r=ne(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||lt(e),n=ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||lt(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Tb(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function vb(t){return t.target==="openAi"?void 0:{not:lt({...t,currentPath:[...t.currentPath,"not"]})}}function Rb(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var dl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function wb(t,e){if(e.target==="openApi3")return Ab(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in dl&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=dl[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Ab(t,e)}var Ab=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ne(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Cb(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:dl[t.innerType._def.typeName],nullable:!0}:{type:[dl[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ne(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function xb(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ph(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Ce(r,"minimum",n.value,n.message,e):Ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Ce(r,"maximum",n.value,n.message,e):Ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":Ce(r,"multipleOf",n.value,n.message,e);break}return r}function _b(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let l=zD(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ne(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||o.push(s))}o.length&&(n.required=o);let a=BD(t,e);return a!==void 0&&(n.additionalProperties=a),n}function BD(t,e){if(t.catchall._def.typeName!=="ZodNever")return ne(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function zD(t){try{return t.isOptional()}catch{return!0}}var Mb=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ne(t.innerType._def,e);let r=ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:lt(e)},r]}:lt(e)};var Pb=(t,e)=>{if(e.pipeStrategy==="input")return ne(t.in._def,e);if(e.pipeStrategy==="output")return ne(t.out._def,e);let r=ne(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ne(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Ib(t,e){return ne(t.type._def,e)}function Ob(t,e){let n={type:"array",uniqueItems:!0,items:ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Lb(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ne(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Nb(t){return{not:lt(t)}}function Db(t){return lt(t)}var kb=(t,e)=>ne(t.innerType._def,e);var Fb=(t,e,r)=>{switch(e){case Ae.ZodString:return gu(t,r);case Ae.ZodNumber:return xb(t,r);case Ae.ZodObject:return _b(t,r);case Ae.ZodBigInt:return db(t,r);case Ae.ZodBoolean:return pb();case Ae.ZodDate:return mh(t,r);case Ae.ZodUndefined:return Nb(r);case Ae.ZodNull:return Rb(r);case Ae.ZodArray:return ub(t,r);case Ae.ZodUnion:case Ae.ZodDiscriminatedUnion:return wb(t,r);case Ae.ZodIntersection:return Sb(t,r);case Ae.ZodTuple:return Lb(t,r);case Ae.ZodRecord:return fu(t,r);case Ae.ZodLiteral:return yb(t,r);case Ae.ZodEnum:return fb(t);case Ae.ZodNativeEnum:return Tb(t);case Ae.ZodNullable:return Cb(t,r);case Ae.ZodOptional:return Mb(t,r);case Ae.ZodMap:return bb(t,r);case Ae.ZodSet:return Ob(t,r);case Ae.ZodLazy:return()=>t.getter()._def;case Ae.ZodPromise:return Ib(t,r);case Ae.ZodNaN:case Ae.ZodNever:return vb(r);case Ae.ZodEffects:return gb(t,r);case Ae.ZodAny:return lt(r);case Ae.ZodUnknown:return Db(r);case Ae.ZodDefault:return hb(t,r);case Ae.ZodBranded:return hu(t,r);case Ae.ZodReadonly:return kb(t,r);case Ae.ZodCatch:return mb(t,r);case Ae.ZodPipeline:return Pb(t,r);case Ae.ZodFunction:case Ae.ZodVoid:case Ae.ZodSymbol:return;default:return(n=>{})(e)}};function ne(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==sb)return s}if(n&&!r){let s=HD(n,e);if(s!==void 0)return s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=Fb(t,t.typeName,e),a=typeof i=="function"?ne(i(),e):i;if(a&&GD(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var HD=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:mu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),lt(e)):e.$refStrategy==="seen"?lt(e):void 0}},GD=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var pl=(t,e)=>{let r=cb(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ne(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??lt(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=ne(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??lt(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};import{z as vn}from"zod";import{extendZodWithOpenApi as jD}from"zod-openapi";jD(vn);var Re=(p=>(p.AI_PROVIDER="AIProviderError",p.USER_INFRA="UserInfrastructureError",p.ACTION_FAILURE="ActionFailureError",p.ASSERTION_FAILURE="AssertionFailureError",p.CONFIG_ERROR="UserConfigurationError",p.SETUP_FAILURE="SetupFailureError",p.TEARDOWN_FAILURE="TeardownFailureError",p.WEB_AGENT_PLATFORM="InternalWebAgentError",p.UNKNOWN_PLATFORM="InternalPlatformError",p.JOB_TIMEOUT="JobTimeoutError",p.CONCURRENCY_ERROR="ConcurrencyError",p.UNKNOWN="UnknownError",p))(Re||{});var Ub=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Su={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",SetupFailureError:"Setup failure",TeardownFailureError:"Teardown failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",ConcurrencyError:"Concurrency error"},Pa={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",SetupFailureError:"A setup step failed to execute, preventing the main test from running. This indicates an issue with test preparation, prerequisite steps, or initial state. This can only apply to failures that occur before teardown.",TeardownFailureError:"A teardown step failed to execute after the main test completed. This indicates an issue with cleanup or post-test operations or an uncaught error in the test. This can only apply to failures that occur after setup.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},fh=vn.object({reason:vn.nativeEnum(Re),previousStepsDescription:vn.array(vn.string()).optional(),summary:vn.string(),rootCause:vn.string().optional()}).openapi({ref:"TestResultClassification"}),yu=vn.object({errorMessage:vn.string(),errorStack:vn.string().optional(),classification:fh.optional()}).openapi({ref:"TestFailureDetails"});var ot=class extends Error{constructor(e,r={}){super(e,r),this.name="ValidationError"}};var Co=class extends Error{zodIssues;constructor(e,r,n,o={}){super(`The ${n} with id ${r} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function Bb(t){for(let e of Object.values(Re))if(t.includes(e))return e}var M=class extends Error{reason;constructor(e,r,n){let o=!1;for(let i of Object.values(Re))if(r.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?r:`${e}: ${r}`,n?.errOptions);else{let i=o?r:`${e}${r?`: ${r}`:""}`;super(i,n?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},Ia=class extends Error{updatedLocatorMemory;constructor(e,r,n={}){super(e,n),this.updatedLocatorMemory=r,this.name="NoElementsFoundUsingAIError"}};var kr=class extends Error{decisions;cacheMissReason;constructor(e,r,n,o={}){super(e,o),this.decisions=r,this.name="NoElementsFoundUsingCacheError",this.cacheMissReason=n}toString(){return`${this.message}
9
9
  Decisions:
10
10
  ${this.decisions.map(e=>e.toString()).join(`
11
- `)}`}};function zb(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator"):!1}function Sh(t){return!(t instanceof Error)||t.message.includes("locator resolved to visible")?!1:!!(t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("body >")||t.message.includes("Element is not attached to the DOM"))}var Rn=class extends Error{retryableWithAI;constructor(e,r,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=r}},Eu=class extends Rn{constructor(e,r={}){super(e,!0,r),this.name="BoundingBoxMovedError"}},bu=class extends Rn{constructor(e,r={}){super(e,!1,r),this.name="ZeroOpacityError"}};function yh(t){return t instanceof Error?t.message.includes("Could not find attribute data-momentic-id for object"):!1}var Eh="Element to be clicked has no bounding box";function Hb(t){return t instanceof Error?t.message.startsWith(Eh):!1}function bh(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator")&&t.message.includes("data-momentic-id")&&!t.message.includes("locator resolved")&&!t.message.includes("waiting for element to be"):!1}function Th(t){return t instanceof Error?t.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||t.message.includes("Could not resolve backend node"):!1}var ml=class extends Error{constructor(e,r={}){super(e,r),this.name="InsufficientCacheDataError"}};var vh={CLICK:"Click on an element on the page.",TYPE:"Focus the element then type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds.",DRAG:"Drag an element from one location and drop it onto another element.",JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual case sensitive assertion on the page's html.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable.",COPY:"Copy the specified text value to the browser clipboard.",GO_FORWARD:"Navigate forward to the next page in the browser history (if available). Only use this after having navigated back with GO_BACK. Do not use this to navigate to a different page - use NAVIGATE instead.",LOCAL_STORAGE:"Set or get a value in the browser's localStorage. Use this to store data that persists across page reloads or to read stored values.",MOUSE_DRAG:"Drag the mouse from a starting point (or element) in a specific direction by pixel amounts. Prefer using DRAG (drag and drop between elements) instead unless the user explicitly requests dragging in a direction or by pixels. Use this when dragging needs to move a specific distance rather than to a target element.",PASTE:"Paste the contents of the browser clipboard into the currently focused element. Use this after copying text with COPY or when pasting content that was previously copied.",REFRESH:"Reload the current page. Use this to refresh the page content or retry a failed operation.",REQUEST:"Make an HTTP API request to a specified URL. Use this to interact with REST APIs, send data to a server, or retrieve data from an endpoint. Supports GET, POST, PUT, DELETE, and PATCH methods with custom headers, query parameters, and request body.",GRAPHQL_REQUEST:"Make a GraphQL request to a specified URL. Provide the GraphQL query (or mutation), optional variables JSON, and any required headers. Use this for GraphQL APIs instead of REQUEST."};dh.options.forEach(t=>{let e=t.shape.type.value;if(e!=="SUCCESS"&&!vh[e])throw new Error(`Command type ${e} is missing a description`)});var Gb=x.object({type:x.literal("CLICK"),description:x.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:x.boolean().or(x.null()),rightClick:x.boolean().or(x.null())}),jb=x.object({type:x.literal("TYPE"),description:x.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:x.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:x.boolean().or(x.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:x.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),Vb=x.object({type:x.literal("GO_BACK")}),VD=x.object({type:x.literal("GO_FORWARD")}),$D=x.object({type:x.literal("LOCAL_STORAGE"),key:x.string().describe("The localStorage key to set or get."),value:x.string().describe("The value to store in localStorage. If reading, this can be empty.")}),$b=x.object({type:x.literal("PRESS"),keys:x.array(x.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),Wb=x.object({type:x.literal("SELECT_OPTION"),description:x.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:x.discriminatedUnion("type",[x.object({type:x.literal("VALUE"),value:x.string()}),x.object({type:x.literal("LABEL"),label:x.string()}),x.object({type:x.literal("INDEX"),index:x.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),qb=x.object({type:x.literal("NAVIGATE"),url:x.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),Kb=x.object({type:x.literal("SCROLL"),y:x.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),Yb=x.object({type:x.literal("WAIT"),timeout:x.number().describe("The number of seconds to wait.")}),Xb=x.object({type:x.literal("AI_ASSERTION"),assertion:x.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:x.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),Jb=x.object({type:x.literal("HOVER"),description:x.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),WD=x.object({type:x.literal("COPY"),value:x.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),qD=x.object({type:x.literal("PASTE")}),KD=x.object({type:x.literal("REFRESH")}),YD=x.object({type:x.literal("REQUEST"),url:x.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:x.enum(["GET","POST","PUT","DELETE","PATCH"]).describe("The HTTP method to use. GET for retrieving data, POST for creating resources, PUT for updating resources, DELETE for removing resources, PATCH for partial updates."),headers:x.record(x.string(),x.string()).or(x.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:x.record(x.string(),x.string()).or(x.null()).describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:x.string().or(x.null()).describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:x.number().int().or(x.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),XD=x.object({type:x.literal("GRAPHQL_REQUEST"),url:x.string().describe("The URL of the GraphQL endpoint. Can be a full URL or relative path."),headers:x.record(x.string(),x.string()).or(x.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),query:x.string().describe("The GraphQL query or mutation string. Include any required fields and arguments."),variables:x.string().or(x.null()).describe("Optional JSON string of variables to pass with the GraphQL request."),timeout:x.number().int().or(x.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),Qb=x.object({type:x.literal("DRAG"),fromDescription:x.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:x.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:x.number().int().positive().or(x.null()).describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:x.number().positive().or(x.null()).describe("Optional seconds to hover over the destination before releasing the drag.")}),JD=x.object({type:x.literal("MOUSE_DRAG"),description:x.string().or(x.null()).describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:x.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:x.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:x.number().int().positive().or(x.null()).describe("Optional number of intermediate mouse move steps during the drag.")}),QD=x.object({type:x.literal("JAVASCRIPT"),code:x.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:x.union([x.literal("NODE"),x.literal("BROWSER")]).or(x.null()).describe("Execution environment. Default is NODE."),timeout:x.number().or(x.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),ZD=x.object({type:x.literal("AI_EXTRACT"),goal:x.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:x.string().or(x.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:x.string().or(x.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:x.string().or(x.null()).describe("URL or URL regex for the iframe to extract data from.")}),ek=x.object({type:x.literal("ELEMENT_CHECK"),description:x.string().describe("Description of the element to check."),assertionType:x.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:x.string().or(x.null()).describe("The value to check against (required for CONTENT assertions)."),negated:x.boolean().or(x.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:x.number().or(x.null()).describe("Max seconds to wait for the assertion to be true.")}),tk=x.object({type:x.literal("PAGE_CHECK"),value:x.string().describe("The text content to check for on the page."),negated:x.boolean().or(x.null()).describe("If true, checks that the content is NOT present."),timeout:x.number().or(x.null()).describe("Max seconds to wait for the assertion to be true.")}),rk=x.object({type:x.literal("NEW_TAB"),url:x.string().describe("The URL to open in the new tab.")}),nk=x.object({type:x.literal("WAIT_FOR_URL"),matcher:x.discriminatedUnion("type",[x.object({type:x.literal("SUBSTRING"),url:x.string()}),x.object({type:x.literal("GLOB"),glob:x.string()}),x.object({type:x.literal("REGEX"),regex:x.string()}),x.object({type:x.literal("DOMAIN"),domain:x.string()})]).describe("How to match the URL."),caseInsensitive:x.boolean().or(x.null()),negated:x.boolean().or(x.null()).describe("Wait for the URL to NOT match instead."),timeout:x.number().or(x.null()).describe("Max seconds to wait for the URL.")}),Rh=x.object({type:x.literal("SUCCESS")}),Ah=x.object({type:x.literal("FAILURE")}),Zb=x.discriminatedUnion("type",[Gb,jb,$b,Wb,qb,Kb,Yb,Xb,Jb,Vb]),ok=x.discriminatedUnion("type",[...Zb.options,Qb]),Oa=x.discriminatedUnion("type",[Gb,jb,$b,Wb,qb,Kb,Yb,Xb,Jb,Vb,Qb,QD,ek,tk,rk,nk,ZD,WD,VD,$D,JD,qD,KD,YD,XD]),_J=pl(Oa),ik=x.discriminatedUnion("type",[...Oa.options,Rh,Ah]),MJ=pl(x.discriminatedUnion("type",[...Zb.options,Rh,Ah])),PJ=pl(x.discriminatedUnion("type",[...ok.options,Rh,Ah])),IJ=x.object({command:x.unknown(),thoughts:x.string()});var vu=t=>{let e=ik.parse(t);switch(e.type){case"CLICK":return{id:Ke(),type:"CLICK",doubleClick:e.doubleClick??void 0,rightClick:e.rightClick??void 0,target:{type:"description",elementDescriptor:e.description}};case"TYPE":return{id:Ke(),type:"TYPE",value:e.text,target:{type:"description",elementDescriptor:e.description},pressEnter:e.pressEnter??void 0,clearContent:e.clearContent};case"PRESS":return{id:Ke(),type:"PRESS",value:e.keys.join("+")};case"SELECT_OPTION":return{id:Ke(),type:"SELECT_OPTION",target:{type:"description",elementDescriptor:`<select> element matching description: ${e.description}`},choice:ch.parse(e.option)};case"NAVIGATE":return{id:Ke(),type:"NAVIGATE",url:e.url};case"SCROLL":return e.y>0?{id:Ke(),type:"SCROLL_DOWN",deltaY:e.y}:{id:Ke(),type:"SCROLL_UP",deltaY:-e.y};case"WAIT":return{id:Ke(),type:"WAIT",delay:e.timeout};case"AI_ASSERTION":return{id:Ke(),type:"AI_ASSERTION",assertion:e.assertion,timeout:e.timeout};case"HOVER":return{id:Ke(),type:"HOVER",target:{type:"description",elementDescriptor:e.description}};case"DRAG":return{id:Ke(),type:"DRAG",fromTarget:{type:"description",elementDescriptor:e.fromDescription},toTarget:{type:"description",elementDescriptor:e.toDescription},steps:e.steps??void 0,hoverSeconds:e.hoverSeconds??void 0};case"JAVASCRIPT":return{id:Ke(),type:"JAVASCRIPT",code:e.code,environment:e.environment??void 0,timeout:e.timeout??void 0};case"AI_EXTRACT":return{id:Ke(),type:"AI_EXTRACT",goal:e.goal,schema:e.schema??void 0,envKey:e.envKey??void 0,iframeUrl:e.iframeUrl??void 0};case"COPY":return{id:Ke(),type:"COPY",value:e.value};case"PASTE":return{id:Ke(),type:"PASTE"};case"REFRESH":return{id:Ke(),type:"REFRESH"};case"GO_FORWARD":return{id:Ke(),type:"GO_FORWARD"};case"LOCAL_STORAGE":return{id:Ke(),type:"LOCAL_STORAGE",key:e.key,value:e.value};case"MOUSE_DRAG":return{id:Ke(),type:"MOUSE_DRAG",target:e.description?{type:"description",elementDescriptor:e.description}:void 0,deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),steps:e.steps??void 0};case"ELEMENT_CHECK":{let r;switch(e.assertionType){case"EXISTS":r={type:"ELEMENT_EXISTENCE",condition:"EXISTS",negated:e.negated??void 0};break;case"VISIBLE":r={type:"ELEMENT_EXISTENCE",condition:"VISIBLE",negated:e.negated??void 0};break;case"CONTENT_CONTAINS":r={type:"ELEMENT_CONTENT",operation:"CONTAINS",value:e.value??"",negated:e.negated??void 0};break;case"CONTENT_EQUALS":r={type:"ELEMENT_CONTENT",operation:"EQUALS",value:e.value??"",negated:e.negated??void 0};break;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.assertionType)}return{id:Ke(),type:"ELEMENT_CHECK",target:{type:"description",elementDescriptor:e.description},assertion:r,timeout:e.timeout??void 0}}case"PAGE_CHECK":return{id:Ke(),type:"PAGE_CHECK",assertion:{type:"CONTENT",value:e.value??void 0,negated:e.negated??void 0},timeout:e.timeout??void 0};case"NEW_TAB":return{id:Ke(),type:"NEW_TAB",url:e.url};case"WAIT_FOR_URL":return{id:Ke(),type:"WAIT_FOR_URL",matcher:e.matcher,caseInsensitive:e.caseInsensitive??void 0,negated:e.negated??void 0,timeout:e.timeout??void 0};case"GO_BACK":return{id:Ke(),type:"GO_BACK"};case"REQUEST":return{id:Ke(),type:"REQUEST",url:e.url,method:e.method,headers:e.headers??void 0,params:e.params??void 0,body:e.body?{type:"json",content:e.body}:void 0,timeout:e.timeout??void 0};case"GRAPHQL_REQUEST":return{id:Ke(),type:"GRAPHQL_REQUEST",url:e.url,headers:e.headers??void 0,query:e.query,variables:e.variables??void 0,timeout:e.timeout??void 0};case"SUCCESS":case"FAILURE":return{id:Ke(),type:e.type};default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}};import{z as wh}from"zod";import{extendZodWithOpenApi as lk}from"zod-openapi";import{z as eT}from"zod";import{extendZodWithOpenApi as ak}from"zod-openapi";import{z as xo}from"zod";var Fr=xo.object({index:xo.number().optional().describe("global index within a test (in-order traversal)"),id:xo.string(),skipped:xo.boolean().optional(),comment:xo.string().optional(),envKey:xo.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:xo.boolean().optional(),retries:xo.number().optional()});ak(eT);var sk=Fr.extend({type:eT.literal("PRESET_ACTION")}),Ar=sk.extend({command:Ma}).openapi({ref:"PresetAction"});lk(wh);var Ei=Fr.extend({type:wh.literal("AI_ACTION"),text:wh.string(),steps:Ar.array().optional()}).openapi({ref:"AIAction"});import{z as sr}from"zod";import{z as Ru}from"zod";import{extendZodWithOpenApi as ck}from"zod-openapi";ck(Ru);var La=Fr.extend({type:Ru.literal("AI_ACTION_DYNAMIC"),text:Ru.string(),retries:Ru.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as tT}from"zod";var Ch=Fr.extend({type:tT.literal("CONDITIONAL"),skipped:tT.boolean().optional()});import{z as xe}from"zod";var uk=xe.object({cacheKey:xe.string(),cacheExpiryMs:xe.number()}),xh=Fr.extend({id:xe.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:xe.record(xe.string()).optional(),cacheConfig:uk.optional()}),sn=xh.extend({type:xe.literal("MODULE"),moduleId:xe.string().uuid()}),dk=xe.union([sn.pick({type:!0,moduleId:!0}),xe.record(xe.unknown())]),pk=xe.object({type:xe.literal("URL_REGEX"),regex:xe.string()}),mk=xe.object({type:xe.literal("PAGE_CHECK"),substring:xe.string()}),_h=xe.object({cacheInvalidation:xe.discriminatedUnion("type",[mk,pk]).optional()}),fr=xe.object({moduleId:xe.string().uuid(),name:xe.string(),description:xe.string().nullish(),enabled:xe.boolean().nullish(),parameters:xe.string().array().nullish(),defaultParameters:xe.record(xe.string(),xe.string()).nullish(),parameterEnums:xe.record(xe.string(),xe.string().array()).nullish(),defaultCacheKey:xe.string().nullish(),defaultCacheTtl:xe.number().nullish(),defaultCacheAllInvocations:xe.boolean().nullish(),autoAuth:xe.boolean().nullish(),advanced:_h.nullish()});var Mh=t=>t.type==="AI_ACTION"||t.type==="AI_ACTION_DYNAMIC"||t.type==="CONDITIONAL"||t.type==="PRESET_ACTION";import{z as Ur}from"zod";var Ph=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Ph||{});var hk=Ur.discriminatedUnion("type",[Ur.object({type:Ur.literal("NAVIGATE_URL"),url:Ur.string().url()}),Ur.object({type:Ur.literal("GO_TO_SECTION_START")})]),gk=Ur.object({trigger:Ur.nativeEnum(Ph).optional(),attempts:Ur.number().int().optional(),restartBehavior:hk}),hl=Fr.extend({type:Ur.literal("SECTION"),description:Ur.string().describe("user provided goal of what the section should accomplish"),plan:Ur.string().array().optional(),autohealingConfig:gk.optional()});var rT=fr.merge(xh).extend({type:sr.literal("RESOLVED_MODULE"),steps:sr.lazy(()=>ft.array())}),Ih=fr.extend({steps:sr.lazy(()=>ft.array())}),Oh=hl.extend({steps:sr.lazy(()=>Qe.array())}),fk=hl.extend({steps:sr.lazy(()=>ft.array())}),bi=Ch.extend({blocks:sr.object({assertion:sr.lazy(()=>Ar),steps:sr.lazy(()=>Qe.array())}).array(),elseSteps:sr.lazy(()=>Qe.array().optional())}),Sk=Ch.extend({blocks:sr.object({assertion:sr.lazy(()=>Ar),steps:sr.lazy(()=>ft.array())}).array(),elseSteps:sr.lazy(()=>ft.array().optional())}),Qe=sr.discriminatedUnion("type",[Ar,Ei,La,sn,bi,Oh]),ft=sr.discriminatedUnion("type",[Ar,Ei,La,rT,Sk,fk]);import{z as Br}from"zod";var yk=Br.object({steps:Qe.array(),beforeSteps:Qe.array().nullish(),afterSteps:Qe.array().nullish()}),_o=Br.object({steps:ft.array(),beforeSteps:ft.array().nullish(),afterSteps:ft.array().nullish()}),Ti=Br.object({steps:Br.record(Br.string(),Br.unknown()).array(),beforeSteps:Br.record(Br.string(),Br.unknown()).array().nullish(),afterSteps:Br.record(Br.string(),Br.unknown()).array().nullish()});var _e="1.0.22",Lh="0.0.2";import{z as qt}from"zod";import{z as vi}from"zod";var Ek=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,ze=t=>{let e=t.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var eo=vi.string().min(1).max(255).superRefine((t,e)=>{try{Mo(t)}catch(r){return e.addIssue({code:vi.ZodIssueCode.custom,message:r.message,fatal:!0}),vi.NEVER}});function Mo(t){if(t=t.toLowerCase().trim(),t.length===0||t.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(t))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(t.endsWith("-")||t.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(t.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(t))throw new Error(`"${t}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(t)||/^\s|\s$/.test(t))throw new Error("Name cannot start or end with a space or dot.");if(t.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(t==="none")throw new Error("Name cannot be 'none'.");if(t.match(Ek))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Au=vi.preprocess(t=>t===null?"":t,vi.union([vi.string().url(),vi.literal("")])).optional();var Nh=["AI_EXTRACT","JAVASCRIPT","REQUEST","GRAPHQL_REQUEST","AUTH_SAVE","COPY"],Po=qt.object({id:qt.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:eo.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:qt.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(t=>[t.id,t.name,t.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided."),bk=qt.object({selector:Po,inputs:qt.record(qt.string()).or(qt.null())}),Dh=qt.object({type:qt.literal("PRESET_ACTION"),action:Oa,envKey:qt.string().or(qt.null()).describe(`key in the environment to save the result of this step to. Only use this for ${Nh.join(" or ")} steps.`)}),kh=qt.object({type:qt.literal("MODULE"),module:bk}),nT=qt.object({type:qt.literal("AI_ACTION_DYNAMIC"),text:qt.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});function oT(t,e){let r=e.parameters??[],n=e.defaultParameters??{},o=e.parameterEnums??{},i=t??{},a=new Set([...r,...Object.keys(n)]),s=Object.keys(i).filter(u=>!a.has(u));if(s.length>0){let u=a.size>0?Array.from(a).join(", "):"none";throw new Error(`Module "${e.name}" received unknown parameters: ${s.join(", ")}. Valid parameters are: ${u}`)}let l=r.filter(u=>!(u in n)).filter(u=>!(u in i));if(l.length>0)throw new Error(`Module "${e.name}" is missing required parameters: ${l.join(", ")}. Please call momentic_module_get to inspect the module's parameter requirements.`);for(let[u,d]of Object.entries(i))if(u in o){let p=o[u];if(p&&!p.includes(d))throw new Error(`Module "${e.name}" parameter "${u}" must be one of: ${p.join(", ")}. Received: "${d}"`)}}var iT=P.object({phrase:P.string()}),Fh=P.object({thoughts:P.string().optional(),result:P.union([P.literal("NOT_FOUND"),P.string(),P.number(),P.array(P.unknown()),P.record(P.unknown(),P.unknown()),P.unknown()])}),C6=P.object({text:P.string()}),Tk=P.boolean().or(P.nativeEnum(gr)).transform(t=>!(!t||t==="irrelevant")),aT=P.object({attributes:P.array(P.string()).nullish(),text:Tk.nullish(),position:P.nativeEnum(gr).nullish(),shape:P.nativeEnum(gr).nullish()}),vk=P.object({id:P.number().int(),requirements:aT}),Rk=vk.array(),sT=P.object({thoughts:P.string(),review:P.string().optional(),id:P.number().int(),updatedMemory:Js.optional(),requirements:aT.nullish().transform(t=>{if(t!==null)return t}),additionalElements:Rk.nullish().transform(t=>{if(t!==null)return t})});var wu=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(wu||{}),Uh=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(Uh||{});var lT=P.object({thoughts:P.string(),category:P.nativeEnum(wu)}),cT=P.object({thoughts:P.string(),category:P.nativeEnum(Uh)}),uT=P.object({anyUntestedSteps:P.boolean().describe("True if any steps (especially new/edited) were not fully run (preview + add) or if their immediately following step, if any, was not run."),possibleErrors:P.object({error:P.string(),solutionFound:P.object({description:P.string(),passedSuccessfully:P.boolean().describe("Whether the solution passed successfully")})}).array().describe("Information about any errors we encountered and how we solved them"),safeToContinue:P.boolean().describe("Whether it is safe to continue or if we are stuck and need intervention"),finalReport:P.string().describe("A final summary report of the session, are we stuck, can we go forward, do we need help, or are we good to go?")}),dT=P.object({summary:P.string().describe("Single large block of text summary of the full chat thread; high-signal only."),errorsRanInto:P.array(P.object({error:P.string(),workAround:P.string()})).default([]).describe("List of encountered errors and mitigations."),untestedSteps:P.array(P.string()).default([]).describe("Steps added/discussed but not validated.")}),Ak=P.discriminatedUnion("op",[P.object({op:P.literal("replace"),path:P.string(),value:P.string()}),P.object({op:P.literal("add"),path:P.string(),value:P.string()}),P.object({op:P.literal("remove"),path:P.string()})]),x6=P.object({thoughts:P.string(),patches:Ak.array()}),wk=[P.literal("add"),P.literal("replace"),P.literal("remove")],Ck=P.object({op:P.union(wk),path:P.string(),value:ft.optional()}),pT=P.object({patches:Ck.array(),thoughts:P.string()}),Bh=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Bh||{}),mT=P.object({thoughts:P.string(),scenario:P.nativeEnum(Bh),instructions:P.string().nullish()}),hT=P.object({reasoning:P.string(),scenario:P.string(),patch:P.null().optional()}),_6=P.object({thoughts:P.string(),evaluation:P.number().min(0).max(10)}),M6=P.object({observations:P.string(),reasoning:P.string(),command:cu});var zh=P.object({summary:P.string(),reasoning:P.string(),evaluation:P.discriminatedUnion("type",[P.object({type:P.literal("DONE")}),P.object({type:P.literal("RIGHT_TRACK")}),P.object({type:P.literal("WRONG_TRACK"),feedback:P.string()}),P.object({type:P.literal("IMPOSSIBLE")})])}),xk=P.object({startId:P.number().int(),endId:P.number().int()}),gT=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(gT||{}),fT=P.object({categoryThoughts:P.string(),category:P.nativeEnum(gT),relevantSections:xk.array()}),to=P.boolean().nullish().transform(t=>t??!1),ST=P.object({thoughts:P.string().optional(),isPageReady:to,descriptionLabels:P.object({usesTextContent:to,usesAppearance:to,usesPosition:to,usesRelativeElements:to,usesSingleQuotes:to,isAmbiguous:to,targetDoesNotExist:to,usesIcon:to}).optional()});import{z as L}from"zod";import*as he from"zod";var D6=he.object({thoughts:he.string().optional().describe("only provided if a description was provided"),target:Ro.optional().describe("only provided if a description was provided"),pageState:he.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:he.object({label:he.string(),value:he.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:he.object({data:he.string(),height:he.number().int(),width:he.number().int()}).optional().describe("only provided if returnScreenshot is true")}),yT=he.union([he.literal("ELEMENT_CHECK"),he.literal("NEGATED_CHECK"),he.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),he.literal("SELECT_OPTION"),he.literal("TYPE")]);function Ri(t){if(!("useSelector"in t&&t.useSelector)){if(t.type==="SELECT_OPTION")return"SELECT_OPTION";if(t.type==="TYPE")return"TYPE";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="EXISTS"&&t.assertion.negated)return"NEGATED_CHECK";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="VISIBLE"&&t.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(t.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var gl=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(gl||{}),Na=he.object({matched:he.boolean(),reason:he.string().optional().describe("Human understandable description"),logs:he.string().array().optional().describe("Logs for debugging")}),_k=Na.extend({type:he.literal("USER_SELECTOR")}),Mk=Na.extend({type:he.literal("CSS_SELECTOR"),selectors:he.string().array()}),Pk=Na.extend({type:he.literal("HYBRID_SELECTOR")}),Ik=Na.extend({type:he.literal("HTML_DISTANCE"),distance:he.number().optional(),closestElement:he.string().optional(),savedElement:he.string().optional()}),Ok=Na.extend({type:he.literal("TEMPLATE_MATCHING"),elementImageUrl:he.string().url()}),Lk=Na.extend({type:he.literal("AUTO_FRAME"),logs:he.string().array().optional()}),ET=he.discriminatedUnion("type",[_k,Mk,Pk,Ik,Ok,Lk]);import{z as bl}from"zod";import{z as qk}from"zod";import*as Q from"zod";import{extendZodWithOpenApi as Bk}from"zod-openapi";import{cloneDeep as fl}from"lodash-es";import CT from"truncate-json";import*as Ci from"zod";import{extendZodWithOpenApi as kk}from"zod-openapi";import{z as Yt}from"zod";import{z as pe}from"zod";import{z as Hh}from"zod";var An=(o=>(o.CHROMIUM="Chromium",o.GOOGLE_CHROME="Google Chrome",o.CHROME_FOR_TESTING="Chrome for Testing",o.ORG_DEFAULT="Org Default",o))(An||{});var Cu=Hh.object({width:Hh.number().min(200).max(1e4),height:Hh.number().min(200).max(1e4)}),bT={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},U6=Object.keys(bT);var Kt=bT["Desktop Large"],Io="en-us",Oo="America/Los_Angeles",Nk="Chromium",Lo={latitude:37.7749,longitude:-122.4194};function xu({browserType:t,orgDefaultBrowserType:e}){return t==="Org Default"&&e?e:t??Nk}var _u=(a=>(a.ClipboardRead="clipboard-read",a.ClipboardWrite="clipboard-write",a.Microphone="microphone",a.Camera="camera",a.Geolocation="geolocation",a.LocalNetworkAccess="local-network-access",a))(_u||{});var Gh=pe.object({autoFollowNewTabs:pe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:pe.union([pe.boolean(),pe.literal("inputs-only")]).optional(),ignoreHrefForCaching:pe.boolean().optional(),disableSecondaryCacheResolution:pe.boolean().optional(),hybridSelectorMode:pe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:pe.union([pe.boolean(),pe.literal("always")]).optional(),visualActions:pe.boolean().optional(),autoExpandIframes:pe.boolean().optional(),disableHtmlSnapshots:pe.boolean().optional(),defaultBrowserType:pe.nativeEnum(An).optional(),importantAttributes:pe.string().array().optional(),importantClasses:pe.string().array().optional(),importantStyles:pe.string().array().optional()});var TT=1e4,vT=6e4,Dk=pe.object({server:pe.string(),username:pe.string().optional(),password:pe.string().optional()}),Ai=Gh.extend({pageLoadTimeoutMs:pe.number().optional().refine(t=>t===void 0||t<=vT&&t>=-1,{message:`Page load timeout must be between 0 and ${vT/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:pe.number().optional().refine(t=>t===void 0||t<=TT&&t>=-1,{message:`Smart waiting timeout must be between 0 and ${TT/1e3} seconds`}),localChromeExtensionPaths:pe.string().array().optional(),extraHeaders:pe.record(pe.string(),pe.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:pe.record(pe.string(),pe.record(pe.string(),pe.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:pe.string().optional(),disableGpu:pe.boolean().optional(),disableBrowserMonitoring:pe.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),disableConsoleLogs:pe.boolean().optional().describe("Disable console log recording in the run viewer."),disableNetworkLogs:pe.boolean().optional().describe("Disable network request recording in the run viewer."),bustCacheOnBoundingBoxChange:pe.boolean().optional().describe("This setting is deprecated. Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:pe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:pe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors."),proxy:Dk.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency."),disableFullStory:pe.boolean().optional().describe("Disable FullStory, a third-party analytics tool that can significantly impact browser performance. This can be useful for testing sites that use FullStory."),grantedPermissions:pe.nativeEnum(_u).array().optional().describe("List of permissions to grant to sites. If not provided, all permissions are granted.")});var Rt="BASE_URL",Mu="CURRENT_URL",wi="ENV_NAME",Da="TEST_NAME",q6={[Rt]:"https://www.google.com"},RT=Yt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),AT=Yt.object({name:Yt.string(),variables:Yt.record(Yt.string().describe("variable name"),Yt.string().describe("variable value"))}),wT=Yt.object({name:Yt.string(),variables:Yt.record(Yt.string().describe("variable name"),Yt.unknown().describe("variable value")),browser:Ai.optional()});var K6=Yt.object({name:Yt.string(),variables:Yt.record(Yt.string().describe("variable name"),Yt.unknown().describe("variable value"))});kk(Ci);var jh=Ci.object({env:Ci.record(Ci.unknown())}).openapi({ref:"TestContextSnapshot"}),Fk="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",Uk=[Rt,wi,Da],xT=[Mu,Rt,wi,Da],lr=class t{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,r=void 0,n={}){return new t({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:r,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:r}){let n=e.env[Rt]??"about:blank",o=e.env[Mu]??"about:blank",i=e.env[wi],a=e.env[Da],s={};for(let[l,u]of Object.entries(e.env))xT.includes(l)||(r??{})[l]===void 0&&(s[l]=u);return new t({baseUrl:n,currentUrl:o,dynamicVariables:s,envName:i,testName:a,variablesFromEnvironment:r??{}})}setEnvVariables(e){let r=fl(e);this.env=Object.assign(this.env,r)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,r){this.varsFromMomenticEnvironment[e]=r}getVariable(e){return this.env[e]}setVariable(e,r){Uk.includes(e)||(this.env[e]=r)}getEnvName(){return this.env[wi]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return fl(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>xT.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,Fk]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=CT(JSON.stringify(o),5e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:r}=CT(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(r)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Mu]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=fl(e.variablesFromEnvironment),this.setMomenticSystemVariable(Rt,e.baseUrl),e.envName&&this.setMomenticSystemVariable(wi,e.envName),e.testName&&this.setMomenticSystemVariable(Da,e.testName)}getDynamicVariablesCopy(){return fl(this.env)}getVariablesFromEnvironmentCopy(){return fl(this.varsFromMomenticEnvironment)}};var Fe=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Fe||{}),Pu=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Pu||{});Bk(Q);var Vh=Q.object({beforeUrl:Q.string().optional(),afterUrl:Q.string().optional(),message:Q.string().optional(),beforeSnapshot:Q.string().optional(),afterSnapshot:Q.string().optional(),startedAt:Q.coerce.date(),finishedAt:Q.coerce.date()}),zk=Vh.extend({viewport:Q.object({height:Q.number(),width:Q.number()}).nullish(),status:Q.nativeEnum(Pu),message:Q.string().optional(),elementInteracted:Q.string().optional()}),xi=Vh.extend({status:Q.nativeEnum(Fe),message:Q.string().optional(),data:Q.unknown().optional(),beforeTestContext:jh.optional(),afterTestContext:jh.optional(),failureReason:Q.nativeEnum(Re).optional(),details:Q.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),$h=(r=>(r.NOT_ELIGIBLE="NOT_ELIGIBLE",r.ATTEMPTED="ATTEMPTED",r))($h||{}),Iu=xi.merge(Ar).extend({results:zk.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:Q.lazy(()=>It.array()).optional(),failureRecoveryStatus:Q.object({type:Q.nativeEnum($h),message:Q.string()}).optional()}),Hk=xi.merge(Ei).extend({results:Q.lazy(()=>Iu.array()),previousAttempts:Q.lazy(()=>It.array()).optional()}),Gk=xi.merge(La).extend({results:Q.lazy(()=>Iu.array()),previousAttempts:Q.lazy(()=>It.array()).optional()}),jk=xi.merge(sn).extend({moduleName:Q.string().optional(),results:Q.lazy(()=>It.array()),previousAttempts:Q.lazy(()=>It.array()).optional()}),Vk=xi.merge(bi).extend({assertionResult:Iu.optional(),results:Q.lazy(()=>It.array()).describe("results for the block actually executed"),previousAttempts:Q.lazy(()=>It.array()).optional()}),$k=xi.merge(hl).extend({results:Q.lazy(()=>It.array()),healingAttempts:Q.lazy(()=>It.array().array()).optional(),previousAttempts:Q.lazy(()=>It.array()).optional()}),It=Q.discriminatedUnion("type",[Hk,Gk,Iu,jk,Vk,$k]),Ou=xi.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Wk=Vh.extend({index:Q.number().optional(),userFacingStepReference:Q.string().optional(),description:Q.string(),pageState:Q.string().optional(),elementInteracted:Q.string().optional(),startedAt:Q.coerce.date().or(Q.string()).optional().catch(void 0),finishedAt:Q.coerce.date().or(Q.string()).optional().catch(void 0)}),Lu=Wk.extend({beforeScreenshot:Q.string().optional(),afterScreenshot:Q.string().optional()});var Wh=qk.object({results:It.array().describe("main results"),beforeResults:It.array().optional(),afterResults:It.array().optional()}),Sl=Wh.partial();import{z as V}from"zod";import{extendZodWithOpenApi as Zk}from"zod-openapi";var ka=(r=>(r.WEB="WEB",r.ANDROID="ANDROID",r))(ka||{});import{isValidCron as Kk}from"cron-validator";import{z as fe}from"zod";var _T=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var MT=1e4,Nu=Ai.extend({browserType:fe.nativeEnum(An).optional(),slowMoMs:fe.number().optional().refine(t=>t===void 0||t<=MT&&t>=-1,{message:`Slow motion must be between 0 and ${MT} milliseconds`}),basicAuthorization:fe.object({username:fe.string().optional(),password:fe.string().optional()}).optional(),geolocation:fe.object({latitude:fe.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:fe.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:fe.boolean().optional(),locale:fe.string().optional(),timezone:fe.enum(_T).optional(),colorScheme:fe.enum(["light","dark"]).optional()}),PT=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],yl=fe.object({useMemory:fe.boolean().optional(),failureRecovery:fe.boolean().optional().describe("undefined means inherit org settings")}),Yk=yl.extend({disableAICaching:fe.boolean().optional(),failureRecoveryInstructions:fe.string().optional()}),Xk=fe.object({viewport:Cu.optional()}),_i=Xk.merge(Yk).merge(Nu),Fa=fe.object({cron:fe.string().refine(t=>Kk(t),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:fe.boolean().default(!1),env:fe.string().optional(),timeZone:fe.string().default("America/Los_Angeles"),jobKey:fe.string().optional()}),Ua=fe.object({onSuccess:fe.boolean().default(!1),failureMessage:fe.string().optional(),onFailure:fe.boolean().default(!0),successMessage:fe.string().optional()}),Jk=fe.object({name:fe.string(),required:fe.boolean().optional(),defaultValue:fe.string().describe("this is not optional because we need a value when the editor is first loaded")}),Du=Jk.array(),Qk=fe.object({name:fe.string(),value:fe.string()}),IT=Qk.array(),ku=fe.object({name:fe.string(),default:fe.boolean().optional(),fixtures:RT.array().optional()});Zk(V);var zr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Me=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(Me||{}),Fu=(r=>(r.BEFORE_ALL="BEFORE_ALL",r.AFTER_ALL="AFTER_ALL",r))(Fu||{});var At=V.string().pipe(V.coerce.date()).or(V.date()),El=V.object({id:V.string(),runKey:V.string(),organizationId:V.string(),executionType:V.nativeEnum(ka).optional().default("WEB"),createdAt:At,createdBy:V.string(),flake:V.boolean().nullish(),scheduledAt:At.or(V.null()),startedAt:At.or(V.null()),updatedAt:At.nullish(),finishedAt:At.or(V.null()),resolvedBaseUrl:V.string().nullish(),environmentName:V.string().nullish(),gitBranchName:V.string().nullish(),githubRepository:V.string().nullish(),gitlabProjectPath:V.string().nullish(),labels:V.array(V.string()).optional(),gitOriginUrl:V.string().nullish(),gitCommitSha:V.string().nullish(),gitCommitShaShort:V.string().nullish(),gitCommitAuthorName:V.string().nullish(),cliVersion:V.string().nullish(),section:V.nativeEnum(Fu).nullish(),status:V.nativeEnum(Me),trigger:V.nativeEnum(zr),attempts:V.number(),runAttempts:V.array(V.object({id:V.string(),status:V.nativeEnum(Me),startedAt:At.or(V.null()),finishedAt:At.or(V.null())})).optional(),videos:V.array(V.string()).optional(),failureReason:V.nativeEnum(Re).nullish(),failureDetails:yu.nullish(),failureRecoveryDetails:V.object({attempts:V.number()}).nullish(),pipelineId:V.string().nullish(),resolvedInputs:V.record(V.string(),V.string()).nullish(),quarantined:V.boolean().nullish().default(!1),quarantinedReason:V.string().nullish(),localTestId:V.string().nullish(),testId:V.string().nullish(),testName:V.string().nullish(),description:V.string().nullish(),test:V.object({name:V.string(),id:V.string()}).nullish().default(null),suiteId:V.string().nullish()}).openapi({ref:"RunMetadata"}),e0={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Uu=El.pick({...e0,test:!0}),OT=El.omit({failureReason:!0,failureDetails:!0,test:!0}),qh=El.extend({stepsSnapshot:V.array(V.record(V.unknown())).nullish(),resolvedInputs:V.record(V.string(),V.string()).nullish(),test:V.object({name:V.string(),id:V.string(),description:V.string().nullish(),baseUrl:V.string().nullish(),advanced:_i.nullish()}).nullish()}).merge(Wh),LT=t=>t.includes("PASSED")&&t.includes("FAILED");var t0=bl.object({id:bl.string().uuid(),startedAt:At.or(bl.null()),finishedAt:At.or(bl.null()),status:bl.nativeEnum(Me)}).merge(Sl),U9=t0.array();var Bu=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(Bu||{});import{z as wt}from"zod";var r0=wt.object({id:wt.string(),status:wt.nativeEnum(Me),trigger:wt.nativeEnum(zr),createdAt:At,startedAt:At.nullish(),finishedAt:At.nullish(),gitCommitSha:wt.string().nullish(),gitCommitShaShort:wt.string().nullish(),gitCommitTimestamp:At.nullish(),gitBranchName:wt.string().nullish(),gitOriginUrl:wt.string().nullish(),gitCommitMessage:wt.string().nullish(),gitCommitAuthorName:wt.string().nullish(),githubRepository:wt.string().nullish(),gitlabProjectPath:wt.string().nullish(),pipelineId:wt.string().nullish(),cliVersion:wt.string().nullish(),labels:wt.string().array().optional(),suite:wt.object({id:wt.string(),name:wt.string()}).nullish(),runs:wt.object({status:wt.nativeEnum(Me)}).array()}).openapi({ref:"RunGroup"}),NT=r0.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Uu.array()});import{z as Nt}from"zod";var n0=Nt.object({type:Nt.literal("TARGETING"),name:Nt.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:ET.array(),pageState:Nt.string().optional(),targetSource:Nt.nativeEnum(vo).optional(),targetUpdateTime:Nt.string().optional()}),o0=Nt.object({type:Nt.literal("AI_LOCATION"),matched:Nt.boolean(),pageState:Nt.string().optional(),ragUsed:Nt.boolean().optional(),thoughts:Nt.string().optional()}),i0=Nt.object({type:Nt.literal("ASSERTION"),relevantElementsSerialized:Nt.string().array().optional(),pageState:Nt.string().optional(),ragUsed:Nt.boolean().optional()}),DT=Nt.discriminatedUnion("type",[n0,o0,i0]);function zu(){return{details:[]}}import{z as Et}from"zod";var a0=Et.object({id:Et.string(),name:Et.string()}),Q9=a0.merge(Et.object({createdAt:At,createdBy:Et.string(),schedule:Fa,notification:Ua,environment:Et.object({name:Et.string()}).nullish(),beforeTests:Et.object({id:Et.string()}).array().nullish(),afterTests:Et.object({id:Et.string()}).array().nullish()})),kT=Et.object({id:Et.string().uuid(),orgId:Et.string(),createdAt:At,startedAt:At.or(Et.null()),finishedAt:At.or(Et.null()),status:Et.nativeEnum(Me),trigger:Et.nativeEnum(zr),suite:Et.object({id:Et.string(),name:Et.string()}).nullish(),runs:El.array()}),Z9=kT.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),FT=kT.extend({runs:Uu.array()});import{z as Hr}from"zod";import{cloneDeep as rQ}from"lodash-es";import{z as Ue}from"zod";var lQ=Ue.object({thoughts:Ue.string(),subGoals:Ue.object({instruction:Ue.string()}).array()}),cQ=Ue.object({thoughts:Ue.string(),newPlanMarkdown:Ue.string()}),uQ=Ue.object({thoughts:Ue.string(),correct:Ue.boolean(),failedActionIndex:Ue.number().optional()}),s0=Ue.object({type:Ue.literal("PLANNING"),beforePlan:Ue.string(),goalDecision:Ue.string(),thoughts:Ue.string()}),l0=Ue.object({type:Ue.literal("RUNNING"),stepDisplayName:Ue.string(),status:Ue.nativeEnum(Fe),results:It.array()}),c0=Ue.object({type:Ue.literal("REVISING"),beforePlan:Ue.string(),afterPlan:Ue.string(),errString:Ue.string(),diffs:Ue.string(),thoughts:Ue.string()}),u0=Ue.object({type:Ue.literal("SYSTEM"),message:Ue.string()}),d0=Ue.discriminatedUnion("type",[s0,l0,c0,u0]),UT=d0.array();var gQ=Hr.object({id:Hr.string(),scheduledAt:Hr.coerce.date().nullable(),startedAt:Hr.coerce.date().nullable(),finishedAt:Hr.coerce.date().nullable(),status:Hr.nativeEnum(Me),history:UT.nullable(),testPlan:Hr.object({id:Hr.string(),name:Hr.string()}).nullable(),test:Hr.object({id:Hr.string(),name:Hr.string()}).nullable()});import{z as cr}from"zod";var Kh=cr.object({content:cr.string(),ids:cr.string().array(),tokenLength:cr.number()}),p0=cr.object({chunks:Kh.array()}),OQ=cr.object({ids:cr.string().array(),score:cr.number(),tokenLength:cr.number()}),LQ=p0.extend({description:cr.string().describe("Input to pass to RAG engine"),tokenLimit:cr.number()}),BT=cr.object({ids:cr.number().array()}),zT=cr.object({indices:cr.number().array()});var Ct=L.object({disableCache:L.boolean().optional(),useMemory:L.boolean().optional(),clientMode:L.enum(["interactive","runner"]).optional(),loggerTags:L.record(L.string(),L.string()).optional(),langfuseSessionId:L.string().optional(),agentConfigVersion:L.string().optional()}),HQ=Ct.extend({chunks:Kh.array(),description:L.string().describe("Input to pass to AI"),type:L.union([L.literal("locator"),L.literal("assertion"),L.literal("ai-action")]),softTokenLimit:L.number(),hardTokenLimit:L.number(),callId:L.string().optional()}),m0=L.object({screenshotBase64AfterCommand:L.string(),urlAfterCommand:L.string(),serializedCommand:L.string(),elementInteracted:L.string().optional(),thoughts:L.string().optional()}),HT=L.object({goal:L.string(),browserState:L.string(),screenshot:L.string(),source:yT.optional().catch(void 0),memory:L.discriminatedUnion("type",[Xn,L.object({type:L.literal("RESOLVED_TRACES"),traces:L.unknown().array()})]).optional()}),GT=L.object({target:L.string().or(L.number()),browserState:L.string().optional(),screenshot:L.string().optional(),boundingBox:L.object({x:L.number(),y:L.number(),height:L.number(),width:L.number()}).optional()}),jT=L.object({goal:L.string(),browserState:L.string(),screenshot:L.string().optional(),returnSchema:L.string().optional()}),h0=L.literal("NEGATED_CHECK"),VT=L.object({goal:L.string(),browserState:L.string(),screenshot:L.string(),url:L.string(),contextChoice:uh.optional(),memory:L.discriminatedUnion("type",[tl,L.object({type:L.literal("RESOLVED_TRACES"),traces:L.unknown().array()})]).optional(),source:h0.optional()}),$T=L.object({command:Ma}),WT=L.object({message:L.string()}),qT=L.object({messagesAndToolCalls:L.array(L.string())}),KT=L.object({messagesAndToolCalls:L.array(L.string()).describe("Chat history to condense for summarization")}),Yh=L.object({goal:L.string(),browserState:L.string(),startingScreenshot:L.string().optional(),screenshot:L.string(),url:L.string(),history:m0.array(),actionHint:L.string().optional(),lastError:L.string().optional()}),YT=L.object({results:Lu.array(),errorMessage:L.string(),errorStack:L.string().optional()}),XT=L.object({results:Lu.array(),goal:L.string(),errorMessage:L.string()}),JT=L.object({failedResults:Lu.array(),nextStepsSerialized:L.string().array(),currentUrl:L.string(),currentPageState:L.string(),currentScreenshot:L.string(),customInstructions:L.string().optional(),testDescription:L.string().optional()}),GQ=L.object({description:L.string(),type:L.union([L.literal("locator"),L.literal("assertion"),L.literal("ai-action")]),excerpt:L.string()}),QT=L.object({type:L.string(),browserContext:L.string(),currentStep:L.string(),screenshot:L.string()}),ZT=L.object({description:L.string(),browserState:L.string(),screenshot:L.string()});import{z as Tl}from"zod";var $Q=Tl.object({goal:Tl.string()}),ev=Tl.object({keywords:Tl.array(Tl.string())});import{z as Xh}from"zod";var Hu=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Hu||{}),KQ=Xh.nativeEnum(Hu),g0=Xh.enum(["v1","v2","v3"]),YQ=g0.or(Xh.string().describe("for people with special configurations"));var Gu={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v3"};import{z as ue}from"zod";import{v4 as pZ}from"uuid";import Te from"zod";import{v4 as tZ}from"uuid";import{z as G}from"zod";import*as H from"zod";var tv=H.discriminatedUnion("type",[H.object({type:H.literal("SCREEN")}),H.object({type:H.literal("OPEN_APP")}),H.object({type:H.literal("OPEN_WEBVIEW")})]),Mi=H.object({type:H.literal("description"),description:H.string()}),rv=H.object({type:H.literal("CUSTOM_COORDINATES"),startX:H.number().describe("Starting X coordinate in pixels"),startY:H.number().describe("Starting Y coordinate in pixels"),deltaPixels:H.number().describe("Number of pixels to scroll in the specified direction")}),Jh=H.discriminatedUnion("type",[...tv.options,H.object({type:H.literal("CUSTOM"),target:Mi}),rv]);var f0=H.object({type:H.literal("coordinates"),xPercent:H.number(),yPercent:H.number()}),ju=H.discriminatedUnion("type",[Mi,f0]),nv=H.object({requiredText:H.string().optional(),requiredAttributes:H.record(H.string(),H.string()).optional(),requiredBounds:H.boolean().optional(),position:H.object({x1:H.number(),y1:H.number(),x2:H.number(),y2:H.number(),tolerance:H.nativeEnum(gr),preciseTolerance:H.boolean().optional()}).optional(),shape:H.object({width:H.number(),height:H.number(),tolerance:H.nativeEnum(gr),preciseTolerance:H.boolean().optional()}).optional()}),S0=H.object({xPath:H.string(),requirements:nv.optional()}),y0=H.object({type:H.literal("CUSTOM"),target:Mi,cache:H.lazy(()=>ov).optional()}),E0=H.object({pixelDelta:H.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:H.union([tv,y0,rv]),direction:H.enum(["up","down"])}),ov=H.object({type:H.literal("NATIVE"),bounds:H.number().array(),resolvedDescription:H.string(),xPath:H.string(),elementOnlySerializedXml:H.string(),scrollDetails:E0.optional(),requirements:nv.optional(),requiredRelatedElements:S0.array().optional(),memory:Xn.optional()}),b0=H.object({type:H.literal("WEBVIEW"),resolvedDescription:H.string(),xPath:H.string(),browserCache:Ro.optional(),memory:Xn.optional()}),Vu=H.union([ov,b0]);var No=(w=>(w.AI_CHECK="AI_CHECK",w.TAP="TAP",w.TYPE="TYPE",w.PRESS="PRESS",w.PRESS_KEYBOARD="PRESS_KEYBOARD",w.OPEN_APP="OPEN_APP",w.KILL_APP="KILL_APP",w.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",w.SWIPE="SWIPE",w.SCROLL_TO="SCROLL_TO",w.SCREEN_CHECK="SCREEN_CHECK",w.ELEMENT_CHECK="ELEMENT_CHECK",w.DRAG_AND_DROP="DRAG_AND_DROP",w.JAVASCRIPT="JAVASCRIPT",w.REQUEST="REQUEST",w.WAIT="WAIT",w.ADD_FILE="ADD_FILE",w.INSTALL_APP="INSTALL_APP",w.UNINSTALL_APP="UNINSTALL_APP",w.TOGGLE_SETTINGS="TOGGLE_SETTINGS",w.ADB="ADB",w.STATE="STATE",w))(No||{}),$u=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))($u||{}),iv=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(iv||{}),Qh=(o=>(o.AIRPLANE_MODE="AIRPLANE_MODE",o.DATA="DATA",o.WIFI="WIFI",o.LOCATION="LOCATION",o))(Qh||{}),av=G.object({updatedAt:G.coerce.date().optional()}),St=G.object({id:G.string().uuid(),disableCache:G.boolean().optional()}),v0=St.extend({type:G.literal("STATE")}),R0=St.extend({type:G.literal("KILL_APP")}),Ba=av.extend({target:Vu}),sv=av.extend({fromTarget:Vu,toTarget:Vu}),Zh=St.extend({type:G.literal("AI_CHECK"),assertion:G.string(),timeoutSecs:G.number().optional(),cache:ya.optional()}),eg=St.extend({type:G.literal("TAP"),target:ju,cache:Ba.optional(),longPress:G.boolean().optional(),longPressDurationMs:G.number().optional(),doubleTap:G.boolean().optional(),doubleTapDelayMs:G.number().optional(),relativePosition:G.object({x:G.number(),y:G.number()}).optional()}),tg=St.extend({type:G.literal("TYPE"),target:ju.optional(),cache:Ba.optional(),keyPressDelayMs:G.number().optional(),text:G.string(),clearContent:G.boolean().optional(),forceClearContent:G.boolean().optional()});var A0=St.extend({type:G.literal("PRESS"),key:G.nativeEnum($u),longPress:G.boolean().optional()}),w0=St.extend({type:G.literal("PRESS_KEYBOARD"),key:G.nativeEnum(iv)}),C0=St.extend({type:G.literal("OPEN_APP"),packageName:G.string(),activityName:G.string().optional(),intentExtras:G.string().optional()}),x0=St.extend({type:G.literal("OPEN_NOTIFICATION_DRAWER")}),rg=St.extend({type:G.literal("SWIPE"),direction:G.enum(["up","down","left","right"]),scrollableElement:Jh,cache:Ba.optional(),viewportPercent:G.number().optional(),durationMs:G.number().optional()}),ng=St.extend({type:G.literal("SCROLL_TO"),target:Mi,direction:G.enum(["down","up"]),scrollableElement:Jh,scrollStepPercent:G.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.8 (80%)."),cache:Ba.optional()});var _0=G.object({type:G.literal("CONTENT"),negated:G.boolean().optional(),value:G.string()}),M0=St.extend({type:G.literal("SCREEN_CHECK"),assertion:_0,timeout:G.number().int().min(0).max(Ca).optional().describe("max seconds to wait for the assertion to be true")}),og=St.extend({type:G.literal("ELEMENT_CHECK"),target:ju,cache:Ba.optional(),assertion:ou,timeout:G.number().int().min(0).max(Ca).optional().describe("max seconds to wait for the assertion to be true")}),ig=St.extend({type:G.literal("DRAG_AND_DROP"),fromTarget:Mi,toTarget:Mi,cache:sv.optional(),hoverDuration:G.number().optional(),dragDuration:G.number().optional()}),P0=St.extend({type:G.literal("JAVASCRIPT"),code:G.string(),timeout:G.number().int().max(60).optional().describe("Max seconds for the code to complete")}),I0=St.extend({type:G.literal("REQUEST")}).merge(gi),O0=St.extend({type:G.literal("WAIT"),timeoutSecs:G.number()}),L0=St.extend({type:G.literal("ADB"),command:G.string(),jsonArgs:G.string().optional()}),N0=St.extend({type:G.literal("ADD_FILE"),file:G.string(),storageLocation:G.string()}),D0=G.string().trim(),k0=St.extend({type:G.literal("INSTALL_APP"),uri:D0}),F0=St.extend({type:G.literal("UNINSTALL_APP"),packageName:G.string()}),U0=St.extend({type:G.literal("TOGGLE_SETTINGS"),settingsType:G.nativeEnum(Qh)}),lv=G.discriminatedUnion("type",[Zh,eg,tg,A0,C0,x0,w0,rg,ng,M0,og,ig,P0,I0,O0,N0,k0,F0,U0,R0,L0,v0]);var B0=["SCREEN","OPEN_APP","OPEN_WEBVIEW","CUSTOM"],cv=Te.object({type:Te.enum(B0).describe("Where to interact. SCREEN = entire device (use for system surfaces like the notification bar or quick settings), OPEN_APP = current foreground app, OPEN_WEBVIEW = active webview (only if a webview is present and there is high confidence that the element is inside it), CUSTOM = explicitly describe the container if and only if NONE of the above fit."),description:Te.string().or(Te.null()).describe("Description of the container to interact with. This is only used if the container type is CUSTOM.")}),z0=Te.object({type:Te.literal("TAP"),description:Te.string().describe("Description of the element to tap."),longPress:Te.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),doubleTap:Te.boolean().describe("Whether to tap twice in quick succession."),relativePosition:Te.null().or(Te.object({x:Te.number(),y:Te.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner.")}).describe(`
11
+ `)}`}};function zb(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator"):!1}function Sh(t){return!(t instanceof Error)||t.message.includes("locator resolved to visible")?!1:!!(t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("body >")||t.message.includes("Element is not attached to the DOM"))}var Rn=class extends Error{retryableWithAI;constructor(e,r,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=r}},Eu=class extends Rn{constructor(e,r={}){super(e,!0,r),this.name="BoundingBoxMovedError"}},bu=class extends Rn{constructor(e,r={}){super(e,!1,r),this.name="ZeroOpacityError"}};function yh(t){return t instanceof Error?t.message.includes("Could not find attribute data-momentic-id for object"):!1}var Eh="Element to be clicked has no bounding box";function Hb(t){return t instanceof Error?t.message.startsWith(Eh):!1}function bh(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator")&&t.message.includes("data-momentic-id")&&!t.message.includes("locator resolved")&&!t.message.includes("waiting for element to be"):!1}function Th(t){return t instanceof Error?t.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||t.message.includes("Could not resolve backend node"):!1}var ml=class extends Error{constructor(e,r={}){super(e,r),this.name="InsufficientCacheDataError"}};var vh={CLICK:"Click on an element on the page.",TYPE:"Focus the element then type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds.",DRAG:"Drag an element from one location and drop it onto another element.",JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual case sensitive assertion on the page's html.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable.",COPY:"Copy the specified text value to the browser clipboard.",GO_FORWARD:"Navigate forward to the next page in the browser history (if available). Only use this after having navigated back with GO_BACK. Do not use this to navigate to a different page - use NAVIGATE instead.",LOCAL_STORAGE:"Set or get a value in the browser's localStorage. Use this to store data that persists across page reloads or to read stored values.",MOUSE_DRAG:"Drag the mouse from a starting point (or element) in a specific direction by pixel amounts. Prefer using DRAG (drag and drop between elements) instead unless the user explicitly requests dragging in a direction or by pixels. Use this when dragging needs to move a specific distance rather than to a target element.",PASTE:"Paste the contents of the browser clipboard into the currently focused element. Use this after copying text with COPY or when pasting content that was previously copied.",REFRESH:"Reload the current page. Use this to refresh the page content or retry a failed operation.",REQUEST:"Make an HTTP API request to a specified URL. Use this to interact with REST APIs, send data to a server, or retrieve data from an endpoint. Supports GET, POST, PUT, DELETE, and PATCH methods with custom headers, query parameters, and request body.",GRAPHQL_REQUEST:"Make a GraphQL request to a specified URL. Provide the GraphQL query (or mutation), optional variables JSON, and any required headers. Use this for GraphQL APIs instead of REQUEST."};dh.options.forEach(t=>{let e=t.shape.type.value;if(e!=="SUCCESS"&&!vh[e])throw new Error(`Command type ${e} is missing a description`)});var Gb=x.object({type:x.literal("CLICK"),description:x.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:x.boolean().or(x.null()),rightClick:x.boolean().or(x.null())}),jb=x.object({type:x.literal("TYPE"),description:x.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:x.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:x.boolean().or(x.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:x.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),Vb=x.object({type:x.literal("GO_BACK")}),VD=x.object({type:x.literal("GO_FORWARD")}),$D=x.object({type:x.literal("LOCAL_STORAGE"),key:x.string().describe("The localStorage key to set or get."),value:x.string().describe("The value to store in localStorage. If reading, this can be empty.")}),$b=x.object({type:x.literal("PRESS"),keys:x.array(x.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),Wb=x.object({type:x.literal("SELECT_OPTION"),description:x.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:x.discriminatedUnion("type",[x.object({type:x.literal("VALUE"),value:x.string()}),x.object({type:x.literal("LABEL"),label:x.string()}),x.object({type:x.literal("INDEX"),index:x.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),qb=x.object({type:x.literal("NAVIGATE"),url:x.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),Kb=x.object({type:x.literal("SCROLL"),y:x.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),Yb=x.object({type:x.literal("WAIT"),timeout:x.number().describe("The number of seconds to wait.")}),Xb=x.object({type:x.literal("AI_ASSERTION"),assertion:x.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:x.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),Jb=x.object({type:x.literal("HOVER"),description:x.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),WD=x.object({type:x.literal("COPY"),value:x.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),qD=x.object({type:x.literal("PASTE")}),KD=x.object({type:x.literal("REFRESH")}),YD=x.object({type:x.literal("REQUEST"),url:x.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:x.enum(["GET","POST","PUT","DELETE","PATCH"]).describe("The HTTP method to use. GET for retrieving data, POST for creating resources, PUT for updating resources, DELETE for removing resources, PATCH for partial updates."),headers:x.record(x.string(),x.string()).or(x.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:x.record(x.string(),x.string()).or(x.null()).describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:x.string().or(x.null()).describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:x.number().int().or(x.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),XD=x.object({type:x.literal("GRAPHQL_REQUEST"),url:x.string().describe("The URL of the GraphQL endpoint. Can be a full URL or relative path."),headers:x.record(x.string(),x.string()).or(x.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),query:x.string().describe("The GraphQL query or mutation string. Include any required fields and arguments."),variables:x.string().or(x.null()).describe("Optional JSON string of variables to pass with the GraphQL request."),timeout:x.number().int().or(x.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),Qb=x.object({type:x.literal("DRAG"),fromDescription:x.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:x.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:x.number().int().positive().or(x.null()).describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:x.number().positive().or(x.null()).describe("Optional seconds to hover over the destination before releasing the drag.")}),JD=x.object({type:x.literal("MOUSE_DRAG"),description:x.string().or(x.null()).describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:x.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:x.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:x.number().int().positive().or(x.null()).describe("Optional number of intermediate mouse move steps during the drag.")}),QD=x.object({type:x.literal("JAVASCRIPT"),code:x.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:x.union([x.literal("NODE"),x.literal("BROWSER")]).or(x.null()).describe("Execution environment. Default is NODE."),timeout:x.number().or(x.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),ZD=x.object({type:x.literal("AI_EXTRACT"),goal:x.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:x.string().or(x.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:x.string().or(x.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:x.string().or(x.null()).describe("URL or URL regex for the iframe to extract data from.")}),ek=x.object({type:x.literal("ELEMENT_CHECK"),description:x.string().describe("Description of the element to check."),assertionType:x.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:x.string().or(x.null()).describe("The value to check against (required for CONTENT assertions)."),negated:x.boolean().or(x.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:x.number().or(x.null()).describe("Max seconds to wait for the assertion to be true.")}),tk=x.object({type:x.literal("PAGE_CHECK"),value:x.string().describe("The text content to check for on the page."),negated:x.boolean().or(x.null()).describe("If true, checks that the content is NOT present."),timeout:x.number().or(x.null()).describe("Max seconds to wait for the assertion to be true.")}),rk=x.object({type:x.literal("NEW_TAB"),url:x.string().describe("The URL to open in the new tab.")}),nk=x.object({type:x.literal("WAIT_FOR_URL"),matcher:x.discriminatedUnion("type",[x.object({type:x.literal("SUBSTRING"),url:x.string()}),x.object({type:x.literal("GLOB"),glob:x.string()}),x.object({type:x.literal("REGEX"),regex:x.string()}),x.object({type:x.literal("DOMAIN"),domain:x.string()})]).describe("How to match the URL."),caseInsensitive:x.boolean().or(x.null()),negated:x.boolean().or(x.null()).describe("Wait for the URL to NOT match instead."),timeout:x.number().or(x.null()).describe("Max seconds to wait for the URL.")}),Rh=x.object({type:x.literal("SUCCESS")}),Ah=x.object({type:x.literal("FAILURE")}),Zb=x.discriminatedUnion("type",[Gb,jb,$b,Wb,qb,Kb,Yb,Xb,Jb,Vb]),ok=x.discriminatedUnion("type",[...Zb.options,Qb]),Oa=x.discriminatedUnion("type",[Gb,jb,$b,Wb,qb,Kb,Yb,Xb,Jb,Vb,Qb,QD,ek,tk,rk,nk,ZD,WD,VD,$D,JD,qD,KD,YD,XD]),_J=pl(Oa),ik=x.discriminatedUnion("type",[...Oa.options,Rh,Ah]),MJ=pl(x.discriminatedUnion("type",[...Zb.options,Rh,Ah])),PJ=pl(x.discriminatedUnion("type",[...ok.options,Rh,Ah])),IJ=x.object({command:x.unknown(),thoughts:x.string()});var vu=t=>{let e=ik.parse(t);switch(e.type){case"CLICK":return{id:Ye(),type:"CLICK",doubleClick:e.doubleClick??void 0,rightClick:e.rightClick??void 0,target:{type:"description",elementDescriptor:e.description}};case"TYPE":return{id:Ye(),type:"TYPE",value:e.text,target:{type:"description",elementDescriptor:e.description},pressEnter:e.pressEnter??void 0,clearContent:e.clearContent};case"PRESS":return{id:Ye(),type:"PRESS",value:e.keys.join("+")};case"SELECT_OPTION":return{id:Ye(),type:"SELECT_OPTION",target:{type:"description",elementDescriptor:`<select> element matching description: ${e.description}`},choice:ch.parse(e.option)};case"NAVIGATE":return{id:Ye(),type:"NAVIGATE",url:e.url};case"SCROLL":return e.y>0?{id:Ye(),type:"SCROLL_DOWN",deltaY:e.y}:{id:Ye(),type:"SCROLL_UP",deltaY:-e.y};case"WAIT":return{id:Ye(),type:"WAIT",delay:e.timeout};case"AI_ASSERTION":return{id:Ye(),type:"AI_ASSERTION",assertion:e.assertion,timeout:e.timeout};case"HOVER":return{id:Ye(),type:"HOVER",target:{type:"description",elementDescriptor:e.description}};case"DRAG":return{id:Ye(),type:"DRAG",fromTarget:{type:"description",elementDescriptor:e.fromDescription},toTarget:{type:"description",elementDescriptor:e.toDescription},steps:e.steps??void 0,hoverSeconds:e.hoverSeconds??void 0};case"JAVASCRIPT":return{id:Ye(),type:"JAVASCRIPT",code:e.code,environment:e.environment??void 0,timeout:e.timeout??void 0};case"AI_EXTRACT":return{id:Ye(),type:"AI_EXTRACT",goal:e.goal,schema:e.schema??void 0,envKey:e.envKey??void 0,iframeUrl:e.iframeUrl??void 0};case"COPY":return{id:Ye(),type:"COPY",value:e.value};case"PASTE":return{id:Ye(),type:"PASTE"};case"REFRESH":return{id:Ye(),type:"REFRESH"};case"GO_FORWARD":return{id:Ye(),type:"GO_FORWARD"};case"LOCAL_STORAGE":return{id:Ye(),type:"LOCAL_STORAGE",key:e.key,value:e.value};case"MOUSE_DRAG":return{id:Ye(),type:"MOUSE_DRAG",target:e.description?{type:"description",elementDescriptor:e.description}:void 0,deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),steps:e.steps??void 0};case"ELEMENT_CHECK":{let r;switch(e.assertionType){case"EXISTS":r={type:"ELEMENT_EXISTENCE",condition:"EXISTS",negated:e.negated??void 0};break;case"VISIBLE":r={type:"ELEMENT_EXISTENCE",condition:"VISIBLE",negated:e.negated??void 0};break;case"CONTENT_CONTAINS":r={type:"ELEMENT_CONTENT",operation:"CONTAINS",value:e.value??"",negated:e.negated??void 0};break;case"CONTENT_EQUALS":r={type:"ELEMENT_CONTENT",operation:"EQUALS",value:e.value??"",negated:e.negated??void 0};break;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.assertionType)}return{id:Ye(),type:"ELEMENT_CHECK",target:{type:"description",elementDescriptor:e.description},assertion:r,timeout:e.timeout??void 0}}case"PAGE_CHECK":return{id:Ye(),type:"PAGE_CHECK",assertion:{type:"CONTENT",value:e.value??void 0,negated:e.negated??void 0},timeout:e.timeout??void 0};case"NEW_TAB":return{id:Ye(),type:"NEW_TAB",url:e.url};case"WAIT_FOR_URL":return{id:Ye(),type:"WAIT_FOR_URL",matcher:e.matcher,caseInsensitive:e.caseInsensitive??void 0,negated:e.negated??void 0,timeout:e.timeout??void 0};case"GO_BACK":return{id:Ye(),type:"GO_BACK"};case"REQUEST":return{id:Ye(),type:"REQUEST",url:e.url,method:e.method,headers:e.headers??void 0,params:e.params??void 0,body:e.body?{type:"json",content:e.body}:void 0,timeout:e.timeout??void 0};case"GRAPHQL_REQUEST":return{id:Ye(),type:"GRAPHQL_REQUEST",url:e.url,headers:e.headers??void 0,query:e.query,variables:e.variables??void 0,timeout:e.timeout??void 0};case"SUCCESS":case"FAILURE":return{id:Ye(),type:e.type};default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}};import{z as wh}from"zod";import{extendZodWithOpenApi as lk}from"zod-openapi";import{z as eT}from"zod";import{extendZodWithOpenApi as ak}from"zod-openapi";import{z as xo}from"zod";var Fr=xo.object({index:xo.number().optional().describe("global index within a test (in-order traversal)"),id:xo.string(),skipped:xo.boolean().optional(),comment:xo.string().optional(),envKey:xo.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:xo.boolean().optional(),retries:xo.number().optional()});ak(eT);var sk=Fr.extend({type:eT.literal("PRESET_ACTION")}),Ar=sk.extend({command:Ma}).openapi({ref:"PresetAction"});lk(wh);var Ei=Fr.extend({type:wh.literal("AI_ACTION"),text:wh.string(),steps:Ar.array().optional()}).openapi({ref:"AIAction"});import{z as sr}from"zod";import{z as Ru}from"zod";import{extendZodWithOpenApi as ck}from"zod-openapi";ck(Ru);var La=Fr.extend({type:Ru.literal("AI_ACTION_DYNAMIC"),text:Ru.string(),retries:Ru.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as tT}from"zod";var Ch=Fr.extend({type:tT.literal("CONDITIONAL"),skipped:tT.boolean().optional()});import{z as xe}from"zod";var uk=xe.object({cacheKey:xe.string(),cacheExpiryMs:xe.number()}),xh=Fr.extend({id:xe.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:xe.record(xe.string()).optional(),cacheConfig:uk.optional()}),sn=xh.extend({type:xe.literal("MODULE"),moduleId:xe.string().uuid()}),dk=xe.union([sn.pick({type:!0,moduleId:!0}),xe.record(xe.unknown())]),pk=xe.object({type:xe.literal("URL_REGEX"),regex:xe.string()}),mk=xe.object({type:xe.literal("PAGE_CHECK"),substring:xe.string()}),_h=xe.object({cacheInvalidation:xe.discriminatedUnion("type",[mk,pk]).optional()}),fr=xe.object({moduleId:xe.string().uuid(),name:xe.string(),description:xe.string().nullish(),enabled:xe.boolean().nullish(),parameters:xe.string().array().nullish(),defaultParameters:xe.record(xe.string(),xe.string()).nullish(),parameterEnums:xe.record(xe.string(),xe.string().array()).nullish(),defaultCacheKey:xe.string().nullish(),defaultCacheTtl:xe.number().nullish(),defaultCacheAllInvocations:xe.boolean().nullish(),autoAuth:xe.boolean().nullish(),advanced:_h.nullish()});var Mh=t=>t.type==="AI_ACTION"||t.type==="AI_ACTION_DYNAMIC"||t.type==="CONDITIONAL"||t.type==="PRESET_ACTION";import{z as Ur}from"zod";var Ph=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Ph||{});var hk=Ur.discriminatedUnion("type",[Ur.object({type:Ur.literal("NAVIGATE_URL"),url:Ur.string().url()}),Ur.object({type:Ur.literal("GO_TO_SECTION_START")})]),gk=Ur.object({trigger:Ur.nativeEnum(Ph).optional(),attempts:Ur.number().int().optional(),restartBehavior:hk}),hl=Fr.extend({type:Ur.literal("SECTION"),description:Ur.string().describe("user provided goal of what the section should accomplish"),plan:Ur.string().array().optional(),autohealingConfig:gk.optional()});var rT=fr.merge(xh).extend({type:sr.literal("RESOLVED_MODULE"),steps:sr.lazy(()=>ft.array())}),Ih=fr.extend({steps:sr.lazy(()=>ft.array())}),Oh=hl.extend({steps:sr.lazy(()=>Ze.array())}),fk=hl.extend({steps:sr.lazy(()=>ft.array())}),bi=Ch.extend({blocks:sr.object({assertion:sr.lazy(()=>Ar),steps:sr.lazy(()=>Ze.array())}).array(),elseSteps:sr.lazy(()=>Ze.array().optional())}),Sk=Ch.extend({blocks:sr.object({assertion:sr.lazy(()=>Ar),steps:sr.lazy(()=>ft.array())}).array(),elseSteps:sr.lazy(()=>ft.array().optional())}),Ze=sr.discriminatedUnion("type",[Ar,Ei,La,sn,bi,Oh]),ft=sr.discriminatedUnion("type",[Ar,Ei,La,rT,Sk,fk]);import{z as Br}from"zod";var yk=Br.object({steps:Ze.array(),beforeSteps:Ze.array().nullish(),afterSteps:Ze.array().nullish()}),_o=Br.object({steps:ft.array(),beforeSteps:ft.array().nullish(),afterSteps:ft.array().nullish()}),Ti=Br.object({steps:Br.record(Br.string(),Br.unknown()).array(),beforeSteps:Br.record(Br.string(),Br.unknown()).array().nullish(),afterSteps:Br.record(Br.string(),Br.unknown()).array().nullish()});var _e="1.0.22",Lh="0.0.2";import{z as qt}from"zod";import{z as vi}from"zod";var Ek=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,ze=t=>{let e=t.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var eo=vi.string().min(1).max(255).superRefine((t,e)=>{try{Mo(t)}catch(r){return e.addIssue({code:vi.ZodIssueCode.custom,message:r.message,fatal:!0}),vi.NEVER}});function Mo(t){if(t=t.toLowerCase().trim(),t.length===0||t.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(t))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(t.endsWith("-")||t.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(t.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(t))throw new Error(`"${t}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(t)||/^\s|\s$/.test(t))throw new Error("Name cannot start or end with a space or dot.");if(t.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(t==="none")throw new Error("Name cannot be 'none'.");if(t.match(Ek))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Au=vi.preprocess(t=>t===null?"":t,vi.union([vi.string().url(),vi.literal("")])).optional();var Nh=["AI_EXTRACT","JAVASCRIPT","REQUEST","GRAPHQL_REQUEST","AUTH_SAVE","COPY"],Po=qt.object({id:qt.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:eo.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:qt.string().optional().describe("The path of the entity to resolve.")}).describe("A selector for a single entity. Exactly one of id, name, or path must be provided. Id is recommended.").refine(t=>[t.id,t.name,t.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided."),bk=qt.object({selector:Po,inputs:qt.record(qt.string()).or(qt.null())}),Dh=qt.object({type:qt.literal("PRESET_ACTION"),action:Oa,envKey:qt.string().or(qt.null()).describe(`key in the environment to save the result of this step to. Only use this for ${Nh.join(" or ")} steps.`)}),kh=qt.object({type:qt.literal("MODULE"),module:bk}),nT=qt.object({type:qt.literal("AI_ACTION_DYNAMIC"),text:qt.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});function oT(t,e){let r=e.parameters??[],n=e.defaultParameters??{},o=e.parameterEnums??{},i=t??{},a=new Set([...r,...Object.keys(n)]),s=Object.keys(i).filter(u=>!a.has(u));if(s.length>0){let u=a.size>0?Array.from(a).join(", "):"none";throw new Error(`Module "${e.name}" received unknown parameters: ${s.join(", ")}. Valid parameters are: ${u}`)}let l=r.filter(u=>!(u in n)).filter(u=>!(u in i));if(l.length>0)throw new Error(`Module "${e.name}" is missing required parameters: ${l.join(", ")}. Please call momentic_module_get to inspect the module's parameter requirements.`);for(let[u,d]of Object.entries(i))if(u in o){let p=o[u];if(p&&!p.includes(d))throw new Error(`Module "${e.name}" parameter "${u}" must be one of: ${p.join(", ")}. Received: "${d}"`)}}var iT=P.object({phrase:P.string()}),Fh=P.object({thoughts:P.string().optional(),result:P.union([P.literal("NOT_FOUND"),P.string(),P.number(),P.array(P.unknown()),P.record(P.unknown(),P.unknown()),P.unknown()])}),C6=P.object({text:P.string()}),Tk=P.boolean().or(P.nativeEnum(gr)).transform(t=>!(!t||t==="irrelevant")),aT=P.object({attributes:P.array(P.string()).nullish(),text:Tk.nullish(),position:P.nativeEnum(gr).nullish(),shape:P.nativeEnum(gr).nullish()}),vk=P.object({id:P.number().int(),requirements:aT}),Rk=vk.array(),sT=P.object({thoughts:P.string(),review:P.string().optional(),id:P.number().int(),updatedMemory:Js.optional(),requirements:aT.nullish().transform(t=>{if(t!==null)return t}),additionalElements:Rk.nullish().transform(t=>{if(t!==null)return t})});var wu=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",m))(wu||{}),Uh=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(Uh||{});var lT=P.object({thoughts:P.string(),category:P.nativeEnum(wu)}),cT=P.object({thoughts:P.string(),category:P.nativeEnum(Uh)}),uT=P.object({anyUntestedSteps:P.boolean().describe("True if any steps (especially new/edited) were not fully run (preview + add) or if their immediately following step, if any, was not run."),possibleErrors:P.object({error:P.string(),solutionFound:P.object({description:P.string(),passedSuccessfully:P.boolean().describe("Whether the solution passed successfully")})}).array().describe("Information about any errors we encountered and how we solved them"),safeToContinue:P.boolean().describe("Whether it is safe to continue or if we are stuck and need intervention"),finalReport:P.string().describe("A final summary report of the session, are we stuck, can we go forward, do we need help, or are we good to go?")}),dT=P.object({summary:P.string().describe("Single large block of text summary of the full chat thread; high-signal only."),errorsRanInto:P.array(P.object({error:P.string(),workAround:P.string()})).default([]).describe("List of encountered errors and mitigations."),untestedSteps:P.array(P.string()).default([]).describe("Steps added/discussed but not validated.")}),Ak=P.discriminatedUnion("op",[P.object({op:P.literal("replace"),path:P.string(),value:P.string()}),P.object({op:P.literal("add"),path:P.string(),value:P.string()}),P.object({op:P.literal("remove"),path:P.string()})]),x6=P.object({thoughts:P.string(),patches:Ak.array()}),wk=[P.literal("add"),P.literal("replace"),P.literal("remove")],Ck=P.object({op:P.union(wk),path:P.string(),value:ft.optional()}),pT=P.object({patches:Ck.array(),thoughts:P.string()}),Bh=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Bh||{}),mT=P.object({thoughts:P.string(),scenario:P.nativeEnum(Bh),instructions:P.string().nullish()}),hT=P.object({reasoning:P.string(),scenario:P.string(),patch:P.null().optional()}),_6=P.object({thoughts:P.string(),evaluation:P.number().min(0).max(10)}),M6=P.object({observations:P.string(),reasoning:P.string(),command:cu});var zh=P.object({summary:P.string(),reasoning:P.string(),evaluation:P.discriminatedUnion("type",[P.object({type:P.literal("DONE")}),P.object({type:P.literal("RIGHT_TRACK")}),P.object({type:P.literal("WRONG_TRACK"),feedback:P.string()}),P.object({type:P.literal("IMPOSSIBLE")})])}),xk=P.object({startId:P.number().int(),endId:P.number().int()}),gT=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(gT||{}),fT=P.object({categoryThoughts:P.string(),category:P.nativeEnum(gT),relevantSections:xk.array()}),to=P.boolean().nullish().transform(t=>t??!1),ST=P.object({thoughts:P.string().optional(),isPageReady:to,descriptionLabels:P.object({usesTextContent:to,usesAppearance:to,usesPosition:to,usesRelativeElements:to,usesSingleQuotes:to,isAmbiguous:to,targetDoesNotExist:to,usesIcon:to}).optional()});import{z as L}from"zod";import*as he from"zod";var D6=he.object({thoughts:he.string().optional().describe("only provided if a description was provided"),target:Ro.optional().describe("only provided if a description was provided"),pageState:he.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:he.object({label:he.string(),value:he.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:he.object({data:he.string(),height:he.number().int(),width:he.number().int()}).optional().describe("only provided if returnScreenshot is true")}),yT=he.union([he.literal("ELEMENT_CHECK"),he.literal("NEGATED_CHECK"),he.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),he.literal("SELECT_OPTION"),he.literal("TYPE")]);function Ri(t){if(!("useSelector"in t&&t.useSelector)){if(t.type==="SELECT_OPTION")return"SELECT_OPTION";if(t.type==="TYPE")return"TYPE";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="EXISTS"&&t.assertion.negated)return"NEGATED_CHECK";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="VISIBLE"&&t.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(t.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var gl=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(gl||{}),Na=he.object({matched:he.boolean(),reason:he.string().optional().describe("Human understandable description"),logs:he.string().array().optional().describe("Logs for debugging")}),_k=Na.extend({type:he.literal("USER_SELECTOR")}),Mk=Na.extend({type:he.literal("CSS_SELECTOR"),selectors:he.string().array()}),Pk=Na.extend({type:he.literal("HYBRID_SELECTOR")}),Ik=Na.extend({type:he.literal("HTML_DISTANCE"),distance:he.number().optional(),closestElement:he.string().optional(),savedElement:he.string().optional()}),Ok=Na.extend({type:he.literal("TEMPLATE_MATCHING"),elementImageUrl:he.string().url()}),Lk=Na.extend({type:he.literal("AUTO_FRAME"),logs:he.string().array().optional()}),ET=he.discriminatedUnion("type",[_k,Mk,Pk,Ik,Ok,Lk]);import{z as bl}from"zod";import{z as qk}from"zod";import*as Q from"zod";import{extendZodWithOpenApi as Bk}from"zod-openapi";import{cloneDeep as fl}from"lodash-es";import CT from"truncate-json";import*as Ci from"zod";import{extendZodWithOpenApi as kk}from"zod-openapi";import{z as Yt}from"zod";import{z as pe}from"zod";import{z as Hh}from"zod";var An=(o=>(o.CHROMIUM="Chromium",o.GOOGLE_CHROME="Google Chrome",o.CHROME_FOR_TESTING="Chrome for Testing",o.ORG_DEFAULT="Org Default",o))(An||{});var Cu=Hh.object({width:Hh.number().min(200).max(1e4),height:Hh.number().min(200).max(1e4)}),bT={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},U6=Object.keys(bT);var Kt=bT["Desktop Large"],Io="en-us",Oo="America/Los_Angeles",Nk="Chromium",Lo={latitude:37.7749,longitude:-122.4194};function xu({browserType:t,orgDefaultBrowserType:e}){return t==="Org Default"&&e?e:t??Nk}var _u=(a=>(a.ClipboardRead="clipboard-read",a.ClipboardWrite="clipboard-write",a.Microphone="microphone",a.Camera="camera",a.Geolocation="geolocation",a.LocalNetworkAccess="local-network-access",a))(_u||{});var Gh=pe.object({autoFollowNewTabs:pe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:pe.union([pe.boolean(),pe.literal("inputs-only")]).optional(),ignoreHrefForCaching:pe.boolean().optional(),disableSecondaryCacheResolution:pe.boolean().optional(),hybridSelectorMode:pe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:pe.union([pe.boolean(),pe.literal("always")]).optional(),visualActions:pe.boolean().optional(),autoExpandIframes:pe.boolean().optional(),disableHtmlSnapshots:pe.boolean().optional(),defaultBrowserType:pe.nativeEnum(An).optional(),importantAttributes:pe.string().array().optional(),importantClasses:pe.string().array().optional(),importantStyles:pe.string().array().optional()});var TT=1e4,vT=6e4,Dk=pe.object({server:pe.string(),username:pe.string().optional(),password:pe.string().optional()}),Ai=Gh.extend({pageLoadTimeoutMs:pe.number().optional().refine(t=>t===void 0||t<=vT&&t>=-1,{message:`Page load timeout must be between 0 and ${vT/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:pe.number().optional().refine(t=>t===void 0||t<=TT&&t>=-1,{message:`Smart waiting timeout must be between 0 and ${TT/1e3} seconds`}),localChromeExtensionPaths:pe.string().array().optional(),extraHeaders:pe.record(pe.string(),pe.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:pe.record(pe.string(),pe.record(pe.string(),pe.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:pe.string().optional(),disableGpu:pe.boolean().optional(),disableBrowserMonitoring:pe.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),disableConsoleLogs:pe.boolean().optional().describe("Disable console log recording in the run viewer."),disableNetworkLogs:pe.boolean().optional().describe("Disable network request recording in the run viewer."),bustCacheOnBoundingBoxChange:pe.boolean().optional().describe("This setting is deprecated. Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:pe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:pe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors."),proxy:Dk.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency."),disableFullStory:pe.boolean().optional().describe("Disable FullStory, a third-party analytics tool that can significantly impact browser performance. This can be useful for testing sites that use FullStory."),grantedPermissions:pe.nativeEnum(_u).array().optional().describe("List of permissions to grant to sites. If not provided, all permissions are granted.")});var Rt="BASE_URL",Mu="CURRENT_URL",wi="ENV_NAME",Da="TEST_NAME",q6={[Rt]:"https://www.google.com"},RT=Yt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),AT=Yt.object({name:Yt.string(),variables:Yt.record(Yt.string().describe("variable name"),Yt.string().describe("variable value"))}),wT=Yt.object({name:Yt.string(),variables:Yt.record(Yt.string().describe("variable name"),Yt.unknown().describe("variable value")),browser:Ai.optional()});var K6=Yt.object({name:Yt.string(),variables:Yt.record(Yt.string().describe("variable name"),Yt.unknown().describe("variable value"))});kk(Ci);var jh=Ci.object({env:Ci.record(Ci.unknown())}).openapi({ref:"TestContextSnapshot"}),Fk="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",Uk=[Rt,wi,Da],xT=[Mu,Rt,wi,Da],lr=class t{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,r=void 0,n={}){return new t({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:r,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:r}){let n=e.env[Rt]??"about:blank",o=e.env[Mu]??"about:blank",i=e.env[wi],a=e.env[Da],s={};for(let[l,u]of Object.entries(e.env))xT.includes(l)||(r??{})[l]===void 0&&(s[l]=u);return new t({baseUrl:n,currentUrl:o,dynamicVariables:s,envName:i,testName:a,variablesFromEnvironment:r??{}})}setEnvVariables(e){let r=fl(e);this.env=Object.assign(this.env,r)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,r){this.varsFromMomenticEnvironment[e]=r}getVariable(e){return this.env[e]}setVariable(e,r){Uk.includes(e)||(this.env[e]=r)}getEnvName(){return this.env[wi]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return fl(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>xT.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,Fk]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=CT(JSON.stringify(o),5e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:r}=CT(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(r)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Mu]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=fl(e.variablesFromEnvironment),this.setMomenticSystemVariable(Rt,e.baseUrl),e.envName&&this.setMomenticSystemVariable(wi,e.envName),e.testName&&this.setMomenticSystemVariable(Da,e.testName)}getDynamicVariablesCopy(){return fl(this.env)}getVariablesFromEnvironmentCopy(){return fl(this.varsFromMomenticEnvironment)}};var Fe=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Fe||{}),Pu=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Pu||{});Bk(Q);var Vh=Q.object({beforeUrl:Q.string().optional(),afterUrl:Q.string().optional(),message:Q.string().optional(),beforeSnapshot:Q.string().optional(),afterSnapshot:Q.string().optional(),startedAt:Q.coerce.date(),finishedAt:Q.coerce.date()}),zk=Vh.extend({viewport:Q.object({height:Q.number(),width:Q.number()}).nullish(),status:Q.nativeEnum(Pu),message:Q.string().optional(),elementInteracted:Q.string().optional()}),xi=Vh.extend({status:Q.nativeEnum(Fe),message:Q.string().optional(),data:Q.unknown().optional(),beforeTestContext:jh.optional(),afterTestContext:jh.optional(),failureReason:Q.nativeEnum(Re).optional(),details:Q.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),$h=(r=>(r.NOT_ELIGIBLE="NOT_ELIGIBLE",r.ATTEMPTED="ATTEMPTED",r))($h||{}),Iu=xi.merge(Ar).extend({results:zk.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:Q.lazy(()=>It.array()).optional(),failureRecoveryStatus:Q.object({type:Q.nativeEnum($h),message:Q.string()}).optional()}),Hk=xi.merge(Ei).extend({results:Q.lazy(()=>Iu.array()),previousAttempts:Q.lazy(()=>It.array()).optional()}),Gk=xi.merge(La).extend({results:Q.lazy(()=>Iu.array()),previousAttempts:Q.lazy(()=>It.array()).optional()}),jk=xi.merge(sn).extend({moduleName:Q.string().optional(),results:Q.lazy(()=>It.array()),previousAttempts:Q.lazy(()=>It.array()).optional()}),Vk=xi.merge(bi).extend({assertionResult:Iu.optional(),results:Q.lazy(()=>It.array()).describe("results for the block actually executed"),previousAttempts:Q.lazy(()=>It.array()).optional()}),$k=xi.merge(hl).extend({results:Q.lazy(()=>It.array()),healingAttempts:Q.lazy(()=>It.array().array()).optional(),previousAttempts:Q.lazy(()=>It.array()).optional()}),It=Q.discriminatedUnion("type",[Hk,Gk,Iu,jk,Vk,$k]),Ou=xi.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Wk=Vh.extend({index:Q.number().optional(),userFacingStepReference:Q.string().optional(),description:Q.string(),pageState:Q.string().optional(),elementInteracted:Q.string().optional(),startedAt:Q.coerce.date().or(Q.string()).optional().catch(void 0),finishedAt:Q.coerce.date().or(Q.string()).optional().catch(void 0)}),Lu=Wk.extend({beforeScreenshot:Q.string().optional(),afterScreenshot:Q.string().optional()});var Wh=qk.object({results:It.array().describe("main results"),beforeResults:It.array().optional(),afterResults:It.array().optional()}),Sl=Wh.partial();import{z as V}from"zod";import{extendZodWithOpenApi as Zk}from"zod-openapi";var ka=(r=>(r.WEB="WEB",r.ANDROID="ANDROID",r))(ka||{});import{isValidCron as Kk}from"cron-validator";import{z as fe}from"zod";var _T=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var MT=1e4,Nu=Ai.extend({browserType:fe.nativeEnum(An).optional(),slowMoMs:fe.number().optional().refine(t=>t===void 0||t<=MT&&t>=-1,{message:`Slow motion must be between 0 and ${MT} milliseconds`}),basicAuthorization:fe.object({username:fe.string().optional(),password:fe.string().optional()}).optional(),geolocation:fe.object({latitude:fe.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:fe.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:fe.boolean().optional(),locale:fe.string().optional(),timezone:fe.enum(_T).optional(),colorScheme:fe.enum(["light","dark"]).optional()}),PT=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],yl=fe.object({useMemory:fe.boolean().optional(),failureRecovery:fe.boolean().optional().describe("undefined means inherit org settings")}),Yk=yl.extend({disableAICaching:fe.boolean().optional(),failureRecoveryInstructions:fe.string().optional()}),Xk=fe.object({viewport:Cu.optional()}),_i=Xk.merge(Yk).merge(Nu),Fa=fe.object({cron:fe.string().refine(t=>Kk(t),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:fe.boolean().default(!1),env:fe.string().optional(),timeZone:fe.string().default("America/Los_Angeles"),jobKey:fe.string().optional()}),Ua=fe.object({onSuccess:fe.boolean().default(!1),failureMessage:fe.string().optional(),onFailure:fe.boolean().default(!0),successMessage:fe.string().optional()}),Jk=fe.object({name:fe.string(),required:fe.boolean().optional(),defaultValue:fe.string().describe("this is not optional because we need a value when the editor is first loaded")}),Du=Jk.array(),Qk=fe.object({name:fe.string(),value:fe.string()}),IT=Qk.array(),ku=fe.object({name:fe.string(),default:fe.boolean().optional(),fixtures:RT.array().optional()});Zk(V);var zr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Me=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(Me||{}),Fu=(r=>(r.BEFORE_ALL="BEFORE_ALL",r.AFTER_ALL="AFTER_ALL",r))(Fu||{});var At=V.string().pipe(V.coerce.date()).or(V.date()),El=V.object({id:V.string(),runKey:V.string(),organizationId:V.string(),executionType:V.nativeEnum(ka).optional().default("WEB"),createdAt:At,createdBy:V.string(),flake:V.boolean().nullish(),scheduledAt:At.or(V.null()),startedAt:At.or(V.null()),updatedAt:At.nullish(),finishedAt:At.or(V.null()),resolvedBaseUrl:V.string().nullish(),environmentName:V.string().nullish(),gitBranchName:V.string().nullish(),githubRepository:V.string().nullish(),gitlabProjectPath:V.string().nullish(),labels:V.array(V.string()).optional(),gitOriginUrl:V.string().nullish(),gitCommitSha:V.string().nullish(),gitCommitShaShort:V.string().nullish(),gitCommitAuthorName:V.string().nullish(),cliVersion:V.string().nullish(),section:V.nativeEnum(Fu).nullish(),status:V.nativeEnum(Me),trigger:V.nativeEnum(zr),attempts:V.number(),runAttempts:V.array(V.object({id:V.string(),status:V.nativeEnum(Me),startedAt:At.or(V.null()),finishedAt:At.or(V.null())})).optional(),videos:V.array(V.string()).optional(),failureReason:V.nativeEnum(Re).nullish(),failureDetails:yu.nullish(),failureRecoveryDetails:V.object({attempts:V.number()}).nullish(),pipelineId:V.string().nullish(),resolvedInputs:V.record(V.string(),V.string()).nullish(),quarantined:V.boolean().nullish().default(!1),quarantinedReason:V.string().nullish(),localTestId:V.string().nullish(),testId:V.string().nullish(),testName:V.string().nullish(),description:V.string().nullish(),test:V.object({name:V.string(),id:V.string()}).nullish().default(null),suiteId:V.string().nullish()}).openapi({ref:"RunMetadata"}),e0={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Uu=El.pick({...e0,test:!0}),OT=El.omit({failureReason:!0,failureDetails:!0,test:!0}),qh=El.extend({stepsSnapshot:V.array(V.record(V.unknown())).nullish(),resolvedInputs:V.record(V.string(),V.string()).nullish(),test:V.object({name:V.string(),id:V.string(),description:V.string().nullish(),baseUrl:V.string().nullish(),advanced:_i.nullish()}).nullish()}).merge(Wh),LT=t=>t.includes("PASSED")&&t.includes("FAILED");var t0=bl.object({id:bl.string().uuid(),startedAt:At.or(bl.null()),finishedAt:At.or(bl.null()),status:bl.nativeEnum(Me)}).merge(Sl),U9=t0.array();var Bu=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(Bu||{});import{z as wt}from"zod";var r0=wt.object({id:wt.string(),status:wt.nativeEnum(Me),trigger:wt.nativeEnum(zr),createdAt:At,startedAt:At.nullish(),finishedAt:At.nullish(),gitCommitSha:wt.string().nullish(),gitCommitShaShort:wt.string().nullish(),gitCommitTimestamp:At.nullish(),gitBranchName:wt.string().nullish(),gitOriginUrl:wt.string().nullish(),gitCommitMessage:wt.string().nullish(),gitCommitAuthorName:wt.string().nullish(),githubRepository:wt.string().nullish(),gitlabProjectPath:wt.string().nullish(),pipelineId:wt.string().nullish(),cliVersion:wt.string().nullish(),labels:wt.string().array().optional(),suite:wt.object({id:wt.string(),name:wt.string()}).nullish(),runs:wt.object({status:wt.nativeEnum(Me)}).array()}).openapi({ref:"RunGroup"}),NT=r0.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Uu.array()});import{z as Nt}from"zod";var n0=Nt.object({type:Nt.literal("TARGETING"),name:Nt.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:ET.array(),pageState:Nt.string().optional(),targetSource:Nt.nativeEnum(vo).optional(),targetUpdateTime:Nt.string().optional()}),o0=Nt.object({type:Nt.literal("AI_LOCATION"),matched:Nt.boolean(),pageState:Nt.string().optional(),ragUsed:Nt.boolean().optional(),thoughts:Nt.string().optional()}),i0=Nt.object({type:Nt.literal("ASSERTION"),relevantElementsSerialized:Nt.string().array().optional(),pageState:Nt.string().optional(),ragUsed:Nt.boolean().optional()}),DT=Nt.discriminatedUnion("type",[n0,o0,i0]);function zu(){return{details:[]}}import{z as Et}from"zod";var a0=Et.object({id:Et.string(),name:Et.string()}),Q9=a0.merge(Et.object({createdAt:At,createdBy:Et.string(),schedule:Fa,notification:Ua,environment:Et.object({name:Et.string()}).nullish(),beforeTests:Et.object({id:Et.string()}).array().nullish(),afterTests:Et.object({id:Et.string()}).array().nullish()})),kT=Et.object({id:Et.string().uuid(),orgId:Et.string(),createdAt:At,startedAt:At.or(Et.null()),finishedAt:At.or(Et.null()),status:Et.nativeEnum(Me),trigger:Et.nativeEnum(zr),suite:Et.object({id:Et.string(),name:Et.string()}).nullish(),runs:El.array()}),Z9=kT.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),FT=kT.extend({runs:Uu.array()});import{z as Hr}from"zod";import{cloneDeep as rQ}from"lodash-es";import{z as Ue}from"zod";var lQ=Ue.object({thoughts:Ue.string(),subGoals:Ue.object({instruction:Ue.string()}).array()}),cQ=Ue.object({thoughts:Ue.string(),newPlanMarkdown:Ue.string()}),uQ=Ue.object({thoughts:Ue.string(),correct:Ue.boolean(),failedActionIndex:Ue.number().optional()}),s0=Ue.object({type:Ue.literal("PLANNING"),beforePlan:Ue.string(),goalDecision:Ue.string(),thoughts:Ue.string()}),l0=Ue.object({type:Ue.literal("RUNNING"),stepDisplayName:Ue.string(),status:Ue.nativeEnum(Fe),results:It.array()}),c0=Ue.object({type:Ue.literal("REVISING"),beforePlan:Ue.string(),afterPlan:Ue.string(),errString:Ue.string(),diffs:Ue.string(),thoughts:Ue.string()}),u0=Ue.object({type:Ue.literal("SYSTEM"),message:Ue.string()}),d0=Ue.discriminatedUnion("type",[s0,l0,c0,u0]),UT=d0.array();var gQ=Hr.object({id:Hr.string(),scheduledAt:Hr.coerce.date().nullable(),startedAt:Hr.coerce.date().nullable(),finishedAt:Hr.coerce.date().nullable(),status:Hr.nativeEnum(Me),history:UT.nullable(),testPlan:Hr.object({id:Hr.string(),name:Hr.string()}).nullable(),test:Hr.object({id:Hr.string(),name:Hr.string()}).nullable()});import{z as cr}from"zod";var Kh=cr.object({content:cr.string(),ids:cr.string().array(),tokenLength:cr.number()}),p0=cr.object({chunks:Kh.array()}),OQ=cr.object({ids:cr.string().array(),score:cr.number(),tokenLength:cr.number()}),LQ=p0.extend({description:cr.string().describe("Input to pass to RAG engine"),tokenLimit:cr.number()}),BT=cr.object({ids:cr.number().array()}),zT=cr.object({indices:cr.number().array()});var Ct=L.object({disableCache:L.boolean().optional(),useMemory:L.boolean().optional(),clientMode:L.enum(["interactive","runner"]).optional(),loggerTags:L.record(L.string(),L.string()).optional(),langfuseSessionId:L.string().optional(),agentConfigVersion:L.string().optional()}),HQ=Ct.extend({chunks:Kh.array(),description:L.string().describe("Input to pass to AI"),type:L.union([L.literal("locator"),L.literal("assertion"),L.literal("ai-action")]),softTokenLimit:L.number(),hardTokenLimit:L.number(),callId:L.string().optional()}),m0=L.object({screenshotBase64AfterCommand:L.string(),urlAfterCommand:L.string(),serializedCommand:L.string(),elementInteracted:L.string().optional(),thoughts:L.string().optional()}),HT=L.object({goal:L.string(),browserState:L.string(),screenshot:L.string(),source:yT.optional().catch(void 0),memory:L.discriminatedUnion("type",[Xn,L.object({type:L.literal("RESOLVED_TRACES"),traces:L.unknown().array()})]).optional()}),GT=L.object({target:L.string().or(L.number()),browserState:L.string().optional(),screenshot:L.string().optional(),boundingBox:L.object({x:L.number(),y:L.number(),height:L.number(),width:L.number()}).optional()}),jT=L.object({goal:L.string(),browserState:L.string(),screenshot:L.string().optional(),returnSchema:L.string().optional()}),h0=L.literal("NEGATED_CHECK"),VT=L.object({goal:L.string(),browserState:L.string(),screenshot:L.string(),url:L.string(),contextChoice:uh.optional(),memory:L.discriminatedUnion("type",[tl,L.object({type:L.literal("RESOLVED_TRACES"),traces:L.unknown().array()})]).optional(),source:h0.optional()}),$T=L.object({command:Ma}),WT=L.object({message:L.string()}),qT=L.object({messagesAndToolCalls:L.array(L.string())}),KT=L.object({messagesAndToolCalls:L.array(L.string()).describe("Chat history to condense for summarization")}),Yh=L.object({goal:L.string(),browserState:L.string(),startingScreenshot:L.string().optional(),screenshot:L.string(),url:L.string(),history:m0.array(),actionHint:L.string().optional(),lastError:L.string().optional()}),YT=L.object({results:Lu.array(),errorMessage:L.string(),errorStack:L.string().optional()}),XT=L.object({results:Lu.array(),goal:L.string(),errorMessage:L.string()}),JT=L.object({failedResults:Lu.array(),nextStepsSerialized:L.string().array(),currentUrl:L.string(),currentPageState:L.string(),currentScreenshot:L.string(),customInstructions:L.string().optional(),testDescription:L.string().optional()}),GQ=L.object({description:L.string(),type:L.union([L.literal("locator"),L.literal("assertion"),L.literal("ai-action")]),excerpt:L.string()}),QT=L.object({type:L.string(),browserContext:L.string(),currentStep:L.string(),screenshot:L.string()}),ZT=L.object({description:L.string(),browserState:L.string(),screenshot:L.string()});import{z as Tl}from"zod";var $Q=Tl.object({goal:Tl.string()}),ev=Tl.object({keywords:Tl.array(Tl.string())});import{z as Xh}from"zod";var Hu=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Hu||{}),KQ=Xh.nativeEnum(Hu),g0=Xh.enum(["v1","v2","v3"]),YQ=g0.or(Xh.string().describe("for people with special configurations"));var Gu={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v3"};import{z as ue}from"zod";import{v4 as pZ}from"uuid";import Te from"zod";import{v4 as tZ}from"uuid";import{z as G}from"zod";import*as H from"zod";var tv=H.discriminatedUnion("type",[H.object({type:H.literal("SCREEN")}),H.object({type:H.literal("OPEN_APP")}),H.object({type:H.literal("OPEN_WEBVIEW")})]),Mi=H.object({type:H.literal("description"),description:H.string()}),rv=H.object({type:H.literal("CUSTOM_COORDINATES"),startX:H.number().describe("Starting X coordinate in pixels"),startY:H.number().describe("Starting Y coordinate in pixels"),deltaPixels:H.number().describe("Number of pixels to scroll in the specified direction")}),Jh=H.discriminatedUnion("type",[...tv.options,H.object({type:H.literal("CUSTOM"),target:Mi}),rv]);var f0=H.object({type:H.literal("coordinates"),xPercent:H.number(),yPercent:H.number()}),ju=H.discriminatedUnion("type",[Mi,f0]),nv=H.object({requiredText:H.string().optional(),requiredAttributes:H.record(H.string(),H.string()).optional(),requiredBounds:H.boolean().optional(),position:H.object({x1:H.number(),y1:H.number(),x2:H.number(),y2:H.number(),tolerance:H.nativeEnum(gr),preciseTolerance:H.boolean().optional()}).optional(),shape:H.object({width:H.number(),height:H.number(),tolerance:H.nativeEnum(gr),preciseTolerance:H.boolean().optional()}).optional()}),S0=H.object({xPath:H.string(),requirements:nv.optional()}),y0=H.object({type:H.literal("CUSTOM"),target:Mi,cache:H.lazy(()=>ov).optional()}),E0=H.object({pixelDelta:H.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:H.union([tv,y0,rv]),direction:H.enum(["up","down"])}),ov=H.object({type:H.literal("NATIVE"),bounds:H.number().array(),resolvedDescription:H.string(),xPath:H.string(),elementOnlySerializedXml:H.string(),scrollDetails:E0.optional(),requirements:nv.optional(),requiredRelatedElements:S0.array().optional(),memory:Xn.optional()}),b0=H.object({type:H.literal("WEBVIEW"),resolvedDescription:H.string(),xPath:H.string(),browserCache:Ro.optional(),memory:Xn.optional()}),Vu=H.union([ov,b0]);var No=(w=>(w.AI_CHECK="AI_CHECK",w.TAP="TAP",w.TYPE="TYPE",w.PRESS="PRESS",w.PRESS_KEYBOARD="PRESS_KEYBOARD",w.OPEN_APP="OPEN_APP",w.KILL_APP="KILL_APP",w.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",w.SWIPE="SWIPE",w.SCROLL_TO="SCROLL_TO",w.SCREEN_CHECK="SCREEN_CHECK",w.ELEMENT_CHECK="ELEMENT_CHECK",w.DRAG_AND_DROP="DRAG_AND_DROP",w.JAVASCRIPT="JAVASCRIPT",w.REQUEST="REQUEST",w.WAIT="WAIT",w.ADD_FILE="ADD_FILE",w.INSTALL_APP="INSTALL_APP",w.UNINSTALL_APP="UNINSTALL_APP",w.TOGGLE_SETTINGS="TOGGLE_SETTINGS",w.ADB="ADB",w.STATE="STATE",w))(No||{}),$u=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))($u||{}),iv=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(iv||{}),Qh=(o=>(o.AIRPLANE_MODE="AIRPLANE_MODE",o.DATA="DATA",o.WIFI="WIFI",o.LOCATION="LOCATION",o))(Qh||{}),av=G.object({updatedAt:G.coerce.date().optional()}),St=G.object({id:G.string().uuid(),disableCache:G.boolean().optional()}),v0=St.extend({type:G.literal("STATE")}),R0=St.extend({type:G.literal("KILL_APP")}),Ba=av.extend({target:Vu}),sv=av.extend({fromTarget:Vu,toTarget:Vu}),Zh=St.extend({type:G.literal("AI_CHECK"),assertion:G.string(),timeoutSecs:G.number().optional(),cache:ya.optional()}),eg=St.extend({type:G.literal("TAP"),target:ju,cache:Ba.optional(),longPress:G.boolean().optional(),longPressDurationMs:G.number().optional(),doubleTap:G.boolean().optional(),doubleTapDelayMs:G.number().optional(),relativePosition:G.object({x:G.number(),y:G.number()}).optional()}),tg=St.extend({type:G.literal("TYPE"),target:ju.optional(),cache:Ba.optional(),keyPressDelayMs:G.number().optional(),text:G.string(),clearContent:G.boolean().optional(),forceClearContent:G.boolean().optional()});var A0=St.extend({type:G.literal("PRESS"),key:G.nativeEnum($u),longPress:G.boolean().optional()}),w0=St.extend({type:G.literal("PRESS_KEYBOARD"),key:G.nativeEnum(iv)}),C0=St.extend({type:G.literal("OPEN_APP"),packageName:G.string(),activityName:G.string().optional(),intentExtras:G.string().optional()}),x0=St.extend({type:G.literal("OPEN_NOTIFICATION_DRAWER")}),rg=St.extend({type:G.literal("SWIPE"),direction:G.enum(["up","down","left","right"]),scrollableElement:Jh,cache:Ba.optional(),viewportPercent:G.number().optional(),durationMs:G.number().optional()}),ng=St.extend({type:G.literal("SCROLL_TO"),target:Mi,direction:G.enum(["down","up"]),scrollableElement:Jh,scrollStepPercent:G.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.8 (80%)."),cache:Ba.optional()});var _0=G.object({type:G.literal("CONTENT"),negated:G.boolean().optional(),value:G.string()}),M0=St.extend({type:G.literal("SCREEN_CHECK"),assertion:_0,timeout:G.number().int().min(0).max(Ca).optional().describe("max seconds to wait for the assertion to be true")}),og=St.extend({type:G.literal("ELEMENT_CHECK"),target:ju,cache:Ba.optional(),assertion:ou,timeout:G.number().int().min(0).max(Ca).optional().describe("max seconds to wait for the assertion to be true")}),ig=St.extend({type:G.literal("DRAG_AND_DROP"),fromTarget:Mi,toTarget:Mi,cache:sv.optional(),hoverDuration:G.number().optional(),dragDuration:G.number().optional()}),P0=St.extend({type:G.literal("JAVASCRIPT"),code:G.string(),timeout:G.number().int().max(60).optional().describe("Max seconds for the code to complete")}),I0=St.extend({type:G.literal("REQUEST")}).merge(gi),O0=St.extend({type:G.literal("WAIT"),timeoutSecs:G.number()}),L0=St.extend({type:G.literal("ADB"),command:G.string(),jsonArgs:G.string().optional()}),N0=St.extend({type:G.literal("ADD_FILE"),file:G.string(),storageLocation:G.string()}),D0=G.string().trim(),k0=St.extend({type:G.literal("INSTALL_APP"),uri:D0}),F0=St.extend({type:G.literal("UNINSTALL_APP"),packageName:G.string()}),U0=St.extend({type:G.literal("TOGGLE_SETTINGS"),settingsType:G.nativeEnum(Qh)}),lv=G.discriminatedUnion("type",[Zh,eg,tg,A0,C0,x0,w0,rg,ng,M0,og,ig,P0,I0,O0,N0,k0,F0,U0,R0,L0,v0]);var B0=["SCREEN","OPEN_APP","OPEN_WEBVIEW","CUSTOM"],cv=Te.object({type:Te.enum(B0).describe("Where to interact. SCREEN = entire device (use for system surfaces like the notification bar or quick settings), OPEN_APP = current foreground app, OPEN_WEBVIEW = active webview (only if a webview is present and there is high confidence that the element is inside it), CUSTOM = explicitly describe the container if and only if NONE of the above fit."),description:Te.string().or(Te.null()).describe("Description of the container to interact with. This is only used if the container type is CUSTOM.")}),z0=Te.object({type:Te.literal("TAP"),description:Te.string().describe("Description of the element to tap."),longPress:Te.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),doubleTap:Te.boolean().describe("Whether to tap twice in quick succession."),relativePosition:Te.null().or(Te.object({x:Te.number(),y:Te.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner.")}).describe(`
12
12
  Tap on an element on the screen.
13
13
  `),H0=Te.object({type:Te.literal("PRESS"),key:Te.nativeEnum($u)}).describe(`
14
14
  Press a button on the device. Some buttons are physical (volume) while others are virtual (Back/Home/App Switcher).
@@ -18,18 +18,18 @@ ${this.decisions.map(e=>e.toString()).join(`
18
18
  Swipe in a direction within a container (screen/app/webview).
19
19
  `),$0=Te.object({type:Te.literal("SCROLL_TO"),targetDescription:Te.string().describe("Description of the element or text to scroll to inside the container. Scrolling up will bring you up in the page, and vice versa."),direction:Te.enum(["down","up"]).describe("Direction to scroll while searching for the target."),container:cv,scrollStepPercent:Te.number().min(.1).max(1).nullish().describe("How much of the container height to scroll at each step (0.1 - 1). Defaults to 0.8 when omitted.")}).describe(`
20
20
  Scroll within a container until the described target is visible. Scrolling up or down will scroll until it finds it or can't scroll anymore. There is no need to repeat the same scroll to command in the same direction multiple times in a row. If a scroll fails, we do not restore the position automatically.
21
- `),EZ=Te.discriminatedUnion("type",[z0,H0,G0,j0,V0,$0]);var bZ={TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a button on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",DRAG_AND_DROP:"Drag an element onto another element in the same context.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Kill an app on the device.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in the emulator.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install an app on the device.",UNINSTALL_APP:"Uninstall an app on the device.",TOGGLE_SETTINGS:"Toggle device settings.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",AI_CHECK:"Use AI to verify a statement about the current state of the emulator or wait until a statement is true."};var TZ=["TAP","TYPE","PRESS","PRESS_KEYBOARD","SWIPE","SCREEN_CHECK","SCROLL_TO","DRAG_AND_DROP","KILL_APP","OPEN_NOTIFICATION_DRAWER","WAIT","TOGGLE_SETTINGS","AI_CHECK"];import W0 from"zod";var Pi={type:!0,cache:!0},za=W0.discriminatedUnion("type",[Zh.pick(Pi),og.pick(Pi),eg.pick(Pi),tg.pick(Pi),rg.pick(Pi),ng.pick(Pi),ig.pick(Pi)]),xZ=Object.values(No).filter(t=>za.options.some(e=>e.shape.type.safeParse(t).success));var uv=ll(za),dv=cl(za),_Z=uu(za);import pv from"zod";var vl=(n=>(n.US_WEST_1="us-west1",n.EU_NORTH_1="eu-north1",n.AS_SOUTH_1="as-south1",n))(vl||{}),mv=(e=>(e.LOCAL="local",e))(mv||{}),hv=pv.nativeEnum(vl).or(pv.nativeEnum(mv)),Rl=(r=>(r.ANDROID_14="14",r.ANDROID_15="15",r))(Rl||{});var ag=(e=>(e.IOS_26="26",e))(ag||{});import{cloneDeep as LZ}from"lodash-es";import DZ from"truncate-json";import bt from"zod";import{z as ln}from"zod";import{z as ct}from"zod";var Xt=ct.object({id:ct.string(),name:eo,baseUrl:Au,description:ct.string().optional().nullish(),schemaVersion:ct.string(),advanced:_i,retries:ct.number(),envs:ct.array(ku).nullish(),parameters:Du.nullish(),disabled:ct.boolean().optional(),labels:ct.array(ct.string()).optional().catch([])}),GZ=ct.enum(["INHERIT","ENABLED","DISABLED"]);var q0=_i.extend({failureRecovery:ct.boolean().or(ct.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED"),useMemory:ct.boolean().or(ct.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED")});var jZ=Xt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:q0}),VZ=Xt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),K0=ct.object({labels:ct.array(ct.string()).optional(),outputs:IT.nullish()}),Gr=Xt.merge(K0),Y0=ct.object({createdAt:ct.coerce.date(),updatedAt:ct.coerce.date(),updatedBy:ct.string().nullable(),schedule:Fa,notification:Ua,createdBy:ct.string(),organizationId:ct.string(),folderId:ct.string().nullable().optional()}),X0=Xt.merge(Y0),$Z=X0.merge(_o),Wu=Xt.merge(_o),WZ=Xt.merge(Ti);var J0="test",Q0="module",Z0="mobile-test",eF="mobile-module";var Se=(o=>(o.TEST=`momentic/${J0}`,o.MODULE=`momentic/${Q0}`,o.MOBILE_TEST=`momentic/${Z0}`,o.MOBILE_MODULE=`momentic/${eF}`,o))(Se||{}),ZZ=Xt.merge(Ti),sg=fr.extend({steps:ln.array(ln.record(ln.string(),ln.unknown())),schemaVersion:ln.string()}),e7=sg.extend({fileType:ln.literal(Se.MODULE)}),t7=ln.object({test:ln.string().describe("YAML for the test, including metadata and steps"),modules:ln.record(ln.string(),ln.string()).describe("Map of module name to YAML for the module")});function qu(t){if(t===void 0)return"__undefined__";if(t===null)return null;if(typeof t!="object")return t;if(Array.isArray(t))return t.map(qu);let e={};for(let[r,n]of Object.entries(t))e[r]=qu(n);return e}import Ft from"zod";var wn=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(wn||{}),Al=Ft.object({id:Ft.string().uuid(),envKey:Ft.string().optional(),skipped:Ft.boolean().optional(),retries:Ft.number().optional()}),wl=Al.extend({type:Ft.literal("MOBILE_PRESET_STEP"),command:lv,keyPressDelayMs:Ft.number().optional()}),Ku=Ft.object({moduleId:Ft.string(),inputs:Ft.record(Ft.string(),Ft.string()).optional()}),Yu=Al.merge(Ku.extend({type:Ft.literal("MOBILE_MODULE_STEP")})),i7=Ku.extend({steps:Ft.lazy(()=>ro.array())}),Cl=Al.extend({type:Ft.literal("MOBILE_AI_ACTION_STEP"),text:Ft.string()}),ro=Ft.discriminatedUnion("type",[wl,Yu,Cl]);var lg=bt.object({parameterNames:bt.string().array(),defaultParameters:bt.record(bt.string(),bt.string()).optional(),parameterEnums:bt.record(bt.string(),bt.string().array()).optional()}),gv=bt.object({moduleId:bt.string().uuid(),name:bt.string(),description:bt.string().nullish(),parameters:lg.optional(),enabled:bt.boolean().nullish(),schemaVersion:bt.string()}),Xu=gv.omit({name:!0}),fv=Xu.extend({steps:bt.array(bt.record(bt.string(),bt.unknown()))}),tF=bt.object({fileType:bt.literal(Se.MOBILE_MODULE)}).merge(fv),rF=gv.omit({schemaVersion:!0}).extend({steps:bt.array(ro)});import Ze from"zod";import*as Ha from"zod";var p7=Ha.custom().refine(t=>t&&t.length>0).refine(t=>t&&t[0]instanceof File,{message:"Please upload a valid file."}),cg=Ha.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();return e.length===0?void 0:e},Ha.string().optional());import xl from"zod";var Do=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Do||{}),ug=Ku.extend({steps:xl.lazy(()=>Ga.array()),description:xl.string().optional(),name:xl.string().describe("name of the module"),parameters:lg.optional()}),nF=Al.merge(ug).extend({type:xl.literal("RESOLVED_MOBILE_MODULE")}),Ga=xl.discriminatedUnion("type",[nF,wl,Cl]);function Sv(t){return Object.values(Do).includes(t)||Object.values(wn).includes(t)}var oF=Ze.object({disableMomenticAccessibilityTree:Ze.boolean().optional(),autoGrantPermissions:Ze.boolean().optional()}),dg=oF.extend({region:hv.optional().describe("Do you want local or Limbar?"),remoteEmulatorSettings:Ze.object({androidVersion:Ze.nativeEnum(Rl).optional()}).optional(),localEmulatorSettings:Ze.object({avdId:cg}).optional(),geolocation:Ze.object({latitude:Ze.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Ze.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional()}),ja=Ze.object({retries:Ze.number().optional().describe("number of retries to run"),defaultChannel:Ze.string().optional().describe("default channel to use"),defaultTag:Ze.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Ze.string().optional(),defaultApkFilePath:cg.describe("APK to install when using the emulator in the local region."),emulator:dg.optional(),ai:yl.optional()}),Va=Ze.object({id:Ze.string().uuid(),description:Ze.string(),schemaVersion:Ze.string(),settings:ja.optional(),disabled:Ze.boolean().optional()}),yv=Ze.object({fileType:Ze.literal(Se.MOBILE_TEST)}).merge(Va),iF=Va.merge(Ze.object({steps:Ze.array(ro)})),I7=yv.merge(iF),O7=Ze.object({name:Ze.string(),steps:Ze.array(ro).optional(),settings:ja.optional()}),Ev=Va.extend({steps:Ga.array()});import ie from"zod";var Cn=ie.object({startTime:ie.number(),endTime:ie.number().optional(),durationMs:ie.number().optional(),error:ie.string().optional(),result:ie.unknown().optional(),attributes:ie.record(ie.string(),ie.unknown())});var aF=Cn.extend({type:ie.literal("SECTION"),name:ie.string(),subSpans:ie.lazy(()=>xn.array())}),sF=Cn.extend({type:ie.literal("AI_LOCATOR_CALL"),result:ie.object({id:ie.number(),thoughts:ie.string()}).optional(),subSpans:ie.lazy(()=>xn.array())}),lF=Cn.extend({type:ie.literal("AI_ASSERTION_CALL"),result:ie.object({thoughts:ie.string(),result:ie.boolean()}).optional(),subSpans:ie.lazy(()=>xn.array())}),cF=Cn.extend({type:ie.literal("TARGET_RESOLUTION"),result:ie.object({serializedElement:ie.string()}).optional(),subSpans:ie.lazy(()=>xn.array())}),uF=Cn.extend({type:ie.literal("EMULATOR_INTERACTION"),name:ie.string(),withinWebview:ie.boolean().optional(),subSpans:ie.lazy(()=>xn.array())}),dF=Cn.extend({type:ie.literal("EMULATOR_READ_STATE"),name:ie.string(),subSpans:ie.lazy(()=>xn.array())}),pF=Cn.extend({type:ie.literal("ELEMENT_ASSERTION"),name:ie.string(),result:ie.object({success:ie.boolean(),message:ie.string().optional()}).optional(),subSpans:ie.lazy(()=>xn.array())}),mF=Cn.extend({type:ie.literal("CACHE_RESOLUTION"),subSpans:ie.lazy(()=>xn.array())}),hF=Cn.extend({type:ie.literal("WAIT_FOR_SCREENSHOT_STABILITY"),subSpans:ie.lazy(()=>xn.array())}),gF=Cn.extend({type:ie.literal("GENERIC"),name:ie.string(),subSpans:ie.lazy(()=>xn.array())}),xn=ie.discriminatedUnion("type",[aF,sF,lF,cF,uF,dF,pF,mF,hF,gF]);import Jt from"zod";var _l=Jt.object({message:Jt.string().optional(),startTime:Jt.number(),endTime:Jt.number(),status:Jt.nativeEnum(Fe),trace:Jt.unknown(),beforeSnapshot:Jt.string().optional(),afterSnapshot:Jt.string().optional(),data:Jt.unknown().optional().describe("output data from the step")}),fF=_l.merge(wl).extend({previousAttempts:Jt.lazy(()=>cn.array()).optional()}),SF=_l.merge(Yu).extend({steps:Jt.lazy(()=>cn.array()),name:Jt.string().optional(),previousAttempts:Jt.lazy(()=>cn.array()).optional()}),yF=_l.merge(Cl).extend({steps:Jt.lazy(()=>cn.array()),previousAttempts:Jt.lazy(()=>cn.array()).optional()}),cn=Jt.discriminatedUnion("type",[fF,SF,yF]);import{parse as V7}from"date-fns";import{z as $a}from"zod";var W7=$a.object({testId:$a.string(),sessionId:$a.string()}),bv=$a.object({uploadUrl:$a.string(),id:$a.string()});import Ml from"zod";var EF=_l.extend({index:Ml.number().optional(),userFacingStepReference:Ml.string().optional(),description:Ml.string()}),Tv=EF.extend({beforeScreenshot:Ml.string().optional(),afterScreenshot:Ml.string().optional()});var vv=ue.object({attributesRequired:ue.array(ue.string()).optional(),textRequired:ue.boolean().optional(),boundsRequired:ue.boolean().optional(),positionSpecificity:ue.nativeEnum(gr).optional(),shapeSpecificity:ue.nativeEnum(gr).optional()}),bF=ue.object({thoughts:ue.string(),id:ue.number(),updatedMemory:Js.optional(),inWebview:ue.boolean().optional(),requirements:vv.optional(),additionalElements:ue.object({id:ue.number(),requirements:vv}).array().optional()}),Rv=ue.object({description:ue.string(),screenXml:ue.string(),screenshot:ue.string(),memory:ue.discriminatedUnion("type",[Xn,ue.object({type:ue.literal("RESOLVED_TRACES"),traces:ue.unknown().array()})]).optional()}),Av=ue.object({assertion:ue.string(),screenXml:ue.string(),screenshot:ue.string(),memory:ue.discriminatedUnion("type",[tl,ue.object({type:ue.literal("RESOLVED_TRACES"),traces:ue.unknown().array()})]).optional()}),TF=ue.object({thoughts:ue.string(),result:ue.boolean(),relevantElements:ue.array(ue.number()).optional(),updatedMemory:el.optional()}),wv=ue.object({failedResults:Tv.array(),nextStepsSerialized:ue.string().array(),currentScreenXml:ue.string(),currentScreenshot:ue.string(),customInstructions:ue.string().optional(),testDescription:ue.string()}),Cv=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Cv||{}),vF=ue.object({thoughts:ue.string(),scenario:ue.nativeEnum(Cv),instructions:ue.string().nullish()});var xv=t=>!(!t.org_id||!t.user_id||!t.platform);import{z as Ii}from"zod";var _v=Ii.object({id:Ii.string().uuid(),skipped:Ii.boolean().optional(),envKey:Ii.string().optional().describe("key in the environment to save the result of this step to")}),pg=_v.merge(gi).extend({type:Ii.literal("REQUEST")}),mg=_v.merge(iu).extend({type:Ii.literal("JAVASCRIPT")}),hg=Ii.discriminatedUnion("type",[mg,pg]);import{z as jr}from"zod";var Mv=jr.object({id:jr.string(),name:eo,description:jr.string().optional().nullish(),baseUrl:Au.nullish(),schemaVersion:jr.string(),advanced:jr.unknown().optional(),retries:jr.number(),envs:jr.array(ku).nullish(),parameters:Du.nullish()}),RF=jr.object({createdAt:jr.coerce.date(),updatedAt:jr.coerce.date(),schedule:Fa.nullish(),notification:Ua.nullish(),createdBy:jr.string(),organizationId:jr.string()}),AF=Mv.merge(RF),Fee=AF.extend({steps:hg.array()}),Uee=Mv.extend({steps:hg.array()});import{z as Sr}from"zod";var Pv=Sr.object({startedAt:Sr.coerce.date(),finishedAt:Sr.coerce.date(),status:Sr.nativeEnum(Fe),message:Sr.string().optional(),data:Sr.unknown().optional()}),wF=Pv.merge(mg).extend({type:Sr.literal("JAVASCRIPT")}),CF=Pv.merge(pg).extend({type:Sr.literal("REQUEST")}),xF=Sr.discriminatedUnion("type",[wF,CF]),Iv=Sr.object({startedAt:Sr.coerce.date(),finishedAt:Sr.coerce.date().nullish(),status:Sr.nativeEnum(Me),results:xF.array(),failureReason:Sr.string().nullish(),failureDetails:yu.nullish()});import{z as yr}from"zod";var _F=yr.object({id:yr.string(),organizationId:yr.string(),createdAt:yr.coerce.date(),updatedAt:yr.coerce.date(),createdBy:yr.string(),scheduledAt:yr.coerce.date().nullish(),startedAt:yr.coerce.date().nullish(),finishedAt:yr.coerce.date().nullish(),status:yr.nativeEnum(Me),trigger:yr.nativeEnum(zr),results:Iv.array().nullish(),apiTestName:yr.string().nullish(),apiTestPath:yr.string().nullish(),apiTestId:yr.string().nullish()}),Kee=_F.pick({status:!0,startedAt:!0,finishedAt:!0});var Pl=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Pl||{}),Ov=3;function MF(t){return t==="MODULE"||t==="CONDITIONAL"||t==="SECTION"||t==="RESOLVED_MODULE"}function gg(t){if(!MF(t))switch(t){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function fg(t){switch(t.type){case"AI_EXTRACT":case"AI_ASSERTION":return Ov;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return t.useSelector||!t.target||t.target.type!=="description"?0:1;case"DRAG":return t.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var Wa=class{trackStepExecution(){}async flush(){}};import{parseString as PF,splitCookiesString as IF}from"set-cookie-parser";import{z as He}from"zod";var Sg=He.object({name:He.string(),value:He.string(),url:He.string().optional(),domain:He.string().optional(),path:He.string().optional(),expires:He.number().default(Date.now()/1e3+60*60*24*365),httpOnly:He.boolean().optional(),secure:He.boolean().default(!0),sameSite:He.union([He.literal("Strict"),He.literal("Lax"),He.literal("None")]).default("None")});function Ju(t,e){let r=[],n=IF(t);for(let o of n){let i=PF(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=Sg.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});r.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||r.push({...s,name:d,value:p})}}return r}var OF=He.object({origin:He.string(),localStorage:He.array(He.object({name:He.string(),value:He.string()}))}),LF=He.object({entries:He.record(He.string(),He.array(He.tuple([He.unknown(),He.unknown()]))),version:He.number().optional()}),Qu=He.object({cookies:Sg.array().optional(),origins:OF.array().optional(),idb:He.record(He.string(),LF).optional().describe("key is db name")});function Lv(t,e){let r=[];return t.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Sg.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),r.push(i)}),r}var Ete=new Set(Object.values(Je));var NF={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",CONDITIONAL:"Conditional",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},bte={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],CONDITIONAL:["conditional","if","else","elif","branch"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},Tte={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of an AI Check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},vte={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",SCROLL_TO:"Scroll to",DRAG_AND_DROP:"Drag & drop",SCREEN_CHECK:"Screen check",ELEMENT_CHECK:"Element check",OPEN_APP:"Open app",KILL_APP:"Kill app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",INSTALL_APP:"Install app",UNINSTALL_APP:"Uninstall app",TOGGLE_SETTINGS:"Toggle settings",ADB:"ADB command",STATE:"Debug state"},Rte={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",DRAG_AND_DROP:"Drag an element onto another element in the same context.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Terminate the currently active app and remove it from recents.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install one or more APKs onto the connected emulator (local emulator only).",UNINSTALL_APP:"Uninstall an APK from the connected emulator (local emulator only).",TOGGLE_SETTINGS:"Toggle device settings.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",AI_CHECK:"Ask AI to verify whether something is true on the screen."};import DF from"semver";import{z as kF}from"zod";var xte=kF.string().refine(t=>DF.valid(t),{message:"must be a valid semver string"});import{Faker as Pte,en as Ite}from"@faker-js/faker";import{z as F}from"zod";var qa=55555,Lte=F.object({body:F.string(),to:F.string(),from:F.string()}),Nte=F.object({from:F.string().optional(),to:F.string(),timeout:F.number().optional(),beforeDate:F.string().pipe(F.coerce.date()).or(F.date()).optional(),afterDate:F.string().pipe(F.coerce.date()).or(F.date()).optional()}),Dte=F.object({to:F.string().email(),from:F.string(),subject:F.string(),body:F.string(),html:F.string().optional()}),kte=F.object({inbox:F.string().transform(t=>t.toLowerCase()),afterDate:F.string().pipe(F.coerce.date()).or(F.date()).optional(),timeout:F.number().optional(),trimWhitespace:F.boolean().optional()}),Fte=F.object({inbox:F.string(),limit:F.number().optional(),afterDate:F.string().pipe(F.coerce.date()).or(F.date()).optional(),trimWhitespace:F.boolean().optional()});var Zu=(r=>(r.RAW="RAW",r.RESPONSE="RESPONSE",r))(Zu||{}),Nv=F.object({body:F.string().nullish(),status:F.number().optional(),headers:F.array(F.tuple([F.string(),F.string()])).optional()}),FF=F.object({url:F.string(),options:F.object({method:F.string(),body:F.string().nullish(),headers:F.array(F.tuple([F.string(),F.string()])).optional()}).optional()}).optional(),UF=F.object({body:F.string().nullish(),options:F.object({status:F.number(),statusText:F.string().optional(),headers:F.array(F.tuple([F.string(),F.string()])).optional()}).optional()}).optional(),Dv=F.object({result:F.unknown(),variableUpdates:F.record(F.string(),F.unknown()).optional(),persistentVariableUpdates:F.record(F.string(),F.unknown()).optional(),error:F.string().optional(),success:F.boolean()}),Ute=F.object({id:F.string().optional(),orgId:F.string(),momenticLambdaAuthHash:F.string(),code:F.string(),fragment:F.boolean(),state:F.object({env:F.record(F.string(),F.unknown()),request:FF,response:UF,additionalBindings:F.record(F.string(),F.unknown()).optional()}),timeoutMs:F.number().optional(),disallowVariableUpdates:F.boolean().optional(),responseSerialization:F.nativeEnum(Zu).optional()}),ko=15e3;import*as Qt from"zod";import{extendZodWithOpenApi as BF}from"zod-openapi";BF(Qt);var zF=Qt.object({url:Qt.string(),lineNumber:Qt.number(),columnNumber:Qt.number()}).openapi({ref:"CodeLocation"}),ed=Qt.object({timestamp:Qt.number(),text:Qt.string(),type:Qt.string(),tabIndex:Qt.number(),args:Qt.unknown().array().optional(),url:Qt.string().optional(),location:zF.optional()}).openapi({ref:"ConsoleLog"}),kv=ed.array(),yg=kv.array();import*as Eg from"zod";import{extendZodWithOpenApi as HF}from"zod-openapi";HF(Eg);var GF=Eg.object({logsPerPage:ed.array().array()}).openapi({ref:"DebugData"});var Il=class{async getConsoleLogsForRunAttempt(e,r,n){}async getNetworkLogsForRunAttempt(e,r,n){}async getHtmlSnapshot(e,r){}async getA11yTreeSnapshot(e,r){}async getScreenshot(e,r){}async storeConsoleLogsForRunAttempt(e,r,n,o){}async storeNetworkLogsForRunAttempt(e,r,n,o){}listVideoAssetPaths(){return[]}close(){}async storeScreenshot(e,r,n){}async storeHtmlSnapshot(e,r,n){}};import{z as I}from"zod";var jF=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),VF=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),$F=I.object({onContentLoad:I.number().optional(),onLoad:I.number().optional(),comment:I.string().optional()}),Ol=I.object({startedDateTime:I.string(),id:I.string(),title:I.string().optional(),pageTimings:$F,comment:I.string().optional()}),WF=I.array(Ol),qF=I.object({name:I.string(),value:I.string(),path:I.string().optional(),domain:I.string().optional(),expires:I.string().optional(),httpOnly:I.boolean().optional(),secure:I.boolean().optional(),comment:I.string().optional()}),Uv=I.array(qF),KF=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),Bv=I.array(KF),YF=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),XF=I.array(YF),JF=I.object({name:I.string(),value:I.string().optional(),fileName:I.string().optional(),contentType:I.string().optional(),comment:I.string().optional()}),QF=I.array(JF),ZF=I.object({mimeType:I.string(),params:QF,text:I.string(),comment:I.string().optional(),_redactedReason:I.string().optional()}),eU=I.object({method:I.string(),url:I.string(),httpVersion:I.string().optional(),cookies:Uv,headers:Bv,queryString:XF,postData:ZF.optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),tU=I.object({size:I.number().optional(),compression:I.number().optional(),mimeType:I.string().optional(),text:I.string().optional(),encoding:I.string().optional(),comment:I.string().optional(),_redactedReason:I.string().optional()}),rU=I.object({status:I.number(),statusText:I.string(),httpVersion:I.string().optional(),cookies:Uv,headers:Bv,content:tU,redirectURL:I.string().optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional(),_mocked:I.boolean().optional()}),Fv=I.object({expires:I.string().optional(),lastAccess:I.string(),eTag:I.string(),hitCount:I.number(),comment:I.string().optional()}),nU=I.object({beforeRequest:Fv.optional(),afterRequest:Fv.optional(),comment:I.string().optional()}),oU=I.object({blocked:I.number().optional(),dns:I.number().optional(),connect:I.number().optional(),send:I.number(),wait:I.number(),receive:I.number(),ssl:I.number().optional(),comment:I.string().optional()}),Ll=I.object({pageref:I.string().optional(),startedDateTime:I.string(),time:I.number().optional(),request:eU,response:rU.optional(),cache:nU.optional(),timings:oU,serverIPAddress:I.string().optional(),connection:I.string().optional(),comment:I.string().optional(),_resourceType:I.string().optional()}),iU=I.array(Ll),aU=I.object({version:I.string().default("1.1"),creator:jF.optional(),browser:VF.optional(),pages:WF.optional(),entries:iU,comment:I.string().optional()}),sU=I.object({log:aU}),Jte=I.record(I.string(),Ol),Qte=I.record(I.string(),Ll);function bg(t,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(t).sort((r,n)=>new Date(r.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((r,n)=>new Date(r.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}import{cloneDeep as lU}from"lodash-es";import{z as _n}from"zod";var Tg=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(Tg||{});var zv=_n.union([_n.string(),_n.number(),_n.boolean(),_n.null(),_n.record(_n.string(),_n.lazy(()=>zv)),_n.array(_n.lazy(()=>zv))]),Nl=class{flags;payloads;constructor(e,r){this.flags=e,this.payloads=r}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=lU(this.flags);return Object.entries(e).forEach(([r,n])=>{typeof n=="boolean"&&Object.values(Tg).includes(r)&&(e[r]=this.isBooleanFlagEnabled(r))}),e}getFlagPayload(e){let r=this.payloads[e];if(r!==void 0){if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r}}refresh(){throw new Error("Not implemented")}},lre=new Nl({},{});var vg={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Hv=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],ure=Object.keys(vg);import{z as Fo}from"zod";var mre=Fo.object({id:Fo.string(),name:Fo.string(),createdAt:Fo.coerce.date(),createdBy:Fo.string(),updatedAt:Fo.coerce.date(),updatedBy:Fo.string().nullable(),organizationId:Fo.string()});import{z as D}from"zod";import Uo from"zod";var Ka=Uo.object({platformSep:Uo.string(),fullPathSegments:Uo.string().array(),relativePathSegments:Uo.string().array(),relativePath:Uo.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Uo.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Uo.coerce.date(),createdAt:Uo.coerce.date()});var cU=D.array(Ka.extend({id:D.string(),name:D.string(),description:D.string().optional(),labels:D.string().array().optional()})),uU=Ka.extend({id:D.string(),name:D.string(),description:D.string().optional(),content:Ih}),dU=D.array(uU),Cre=D.object({tests:cU,modules:dU,labels:D.string().array()}),xre=Wu.merge(Gr),Gv=D.object({schemaVersion:D.string(),stepLists:_o}),jv=Gr.partial().merge(Xt.pick({id:!0})),Rg={name:D.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:D.string().optional(),baseUrl:D.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:D.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:D.nativeEnum(An).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Cu.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:D.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},Vv=D.object(Rg),_re=Wu.merge(D.object({relativeFilePath:D.string().describe("relative to project root")})),$v=D.object({name:D.string()}),Mre=D.object({relativeFilePath:D.string()}),Wv=D.object({name:D.string()}),Pre=D.object({relativeFilePath:D.string()}),qv=D.object({name:D.string(),description:D.string(),enabled:D.boolean(),steps:D.lazy(()=>ft.array()),testFilePath:D.string().describe("relative to the project root"),folderPath:D.string().optional().describe("user selected folder path")}),Kv=D.object({name:D.string(),description:D.string(),enabled:D.boolean()}).partial();var Ire=D.array(wT),Yv=D.object({defaultEnv:D.string().optional().describe("name of the default env, or undefined to unset")}),Xv=D.object({configFilePath:D.string().describe("full path on disk")}),Ore=D.string().array(),Lre=D.object({message:D.string(),newRelativeTestPath:D.string().optional()}),Ag=D.object({name:D.string(),absolutePath:D.string(),relativePath:D.string(),pathSegments:D.array(D.string()),isDirectory:D.boolean(),size:D.number(),createdAt:D.coerce.date(),modifiedAt:D.coerce.date(),accessedAt:D.coerce.date()}),Jv=D.object({pathSegments:D.array(D.string())}),Nre=D.object({absolutePath:D.string(),pathSegments:D.array(D.string()),contents:D.array(Ag)}),Qv=D.object({pathSegments:D.array(D.string())}),Zv=D.object({pathSegments:D.array(D.string()),newPathSegments:D.array(D.string())}),eR=D.object({pathSegments:D.array(D.string()),recursive:D.boolean().optional()}),Dre=D.object({success:D.boolean(),message:D.string(),pathSegments:D.array(D.string()).optional()}),kre=D.object({gitBranch:D.string(),fileMtime:D.coerce.date(),gitCommitSha:D.string()});var td=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],rd=td.map(t=>`**/${t}/**`),tR=!0,wr=!1,rR=15e4;import Mn from"chalk";import pU from"safe-stable-stringify";import mU from"truncate-json";import hU from"zod";var Oi=pU.configure({deterministic:!1});function nR(t){let e=Oi(t),{jsonString:r}=mU(e,5e4);return r}var gU=["app","version","env","namespace","host"];function je(t){let e=t.bindings()??{},r={};for(let n of Object.keys(e)){let o=e[n];!gU.includes(n)&&typeof o=="string"&&(r[n]=o)}return r}var wg=hU.enum(["debug","info","warn","error"]);var Dl={debug:20,info:30,warn:40,error:50},oR={20:"debug",30:"info",40:"warn",50:"error"},Li=class t{minLogLevel;logBindings;constructor(e,r){typeof e=="string"?this.minLogLevel=Dl[e]:this.minLogLevel=e,this.logBindings=r}logWithLevel(e,r,...n){try{this.logWithLevelHelper(e,r,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}indentMultiline(e,r=" "){return e.split(`
21
+ `),EZ=Te.discriminatedUnion("type",[z0,H0,G0,j0,V0,$0]);var bZ={TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a button on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",DRAG_AND_DROP:"Drag an element onto another element in the same context.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Kill an app on the device.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in the emulator.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install an app on the device.",UNINSTALL_APP:"Uninstall an app on the device.",TOGGLE_SETTINGS:"Toggle device settings.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",AI_CHECK:"Use AI to verify a statement about the current state of the emulator or wait until a statement is true."};var TZ=["TAP","TYPE","PRESS","PRESS_KEYBOARD","SWIPE","SCREEN_CHECK","SCROLL_TO","DRAG_AND_DROP","KILL_APP","OPEN_NOTIFICATION_DRAWER","WAIT","TOGGLE_SETTINGS","AI_CHECK"];import W0 from"zod";var Pi={type:!0,cache:!0},za=W0.discriminatedUnion("type",[Zh.pick(Pi),og.pick(Pi),eg.pick(Pi),tg.pick(Pi),rg.pick(Pi),ng.pick(Pi),ig.pick(Pi)]),xZ=Object.values(No).filter(t=>za.options.some(e=>e.shape.type.safeParse(t).success));var uv=ll(za),dv=cl(za),_Z=uu(za);import pv from"zod";var vl=(n=>(n.US_WEST_1="us-west1",n.EU_NORTH_1="eu-north1",n.AS_SOUTH_1="as-south1",n))(vl||{}),mv=(e=>(e.LOCAL="local",e))(mv||{}),hv=pv.nativeEnum(vl).or(pv.nativeEnum(mv)),Rl=(r=>(r.ANDROID_14="14",r.ANDROID_15="15",r))(Rl||{});var ag=(e=>(e.IOS_26="26",e))(ag||{});import{cloneDeep as LZ}from"lodash-es";import DZ from"truncate-json";import bt from"zod";import{z as ln}from"zod";import{z as ct}from"zod";var Xt=ct.object({id:ct.string(),name:eo,baseUrl:Au,description:ct.string().optional().nullish(),schemaVersion:ct.string(),advanced:_i,retries:ct.number(),envs:ct.array(ku).nullish(),parameters:Du.nullish(),disabled:ct.boolean().optional(),labels:ct.array(ct.string()).optional().catch([])}),GZ=ct.enum(["INHERIT","ENABLED","DISABLED"]);var q0=_i.extend({failureRecovery:ct.boolean().or(ct.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED"),useMemory:ct.boolean().or(ct.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED")});var jZ=Xt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:q0}),VZ=Xt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),K0=ct.object({labels:ct.array(ct.string()).optional(),outputs:IT.nullish()}),Gr=Xt.merge(K0),Y0=ct.object({createdAt:ct.coerce.date(),updatedAt:ct.coerce.date(),updatedBy:ct.string().nullable(),schedule:Fa,notification:Ua,createdBy:ct.string(),organizationId:ct.string(),folderId:ct.string().nullable().optional()}),X0=Xt.merge(Y0),$Z=X0.merge(_o),Wu=Xt.merge(_o),WZ=Xt.merge(Ti);var J0="test",Q0="module",Z0="mobile-test",eF="mobile-module";var Se=(o=>(o.TEST=`momentic/${J0}`,o.MODULE=`momentic/${Q0}`,o.MOBILE_TEST=`momentic/${Z0}`,o.MOBILE_MODULE=`momentic/${eF}`,o))(Se||{}),ZZ=Xt.merge(Ti),sg=fr.extend({steps:ln.array(ln.record(ln.string(),ln.unknown())),schemaVersion:ln.string()}),e7=sg.extend({fileType:ln.literal(Se.MODULE)}),t7=ln.object({test:ln.string().describe("YAML for the test, including metadata and steps"),modules:ln.record(ln.string(),ln.string()).describe("Map of module name to YAML for the module")});function qu(t){if(t===void 0)return"__undefined__";if(t===null)return null;if(typeof t!="object")return t;if(Array.isArray(t))return t.map(qu);let e={};for(let[r,n]of Object.entries(t))e[r]=qu(n);return e}import Ft from"zod";var wn=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(wn||{}),Al=Ft.object({id:Ft.string().uuid(),envKey:Ft.string().optional(),skipped:Ft.boolean().optional(),retries:Ft.number().optional()}),wl=Al.extend({type:Ft.literal("MOBILE_PRESET_STEP"),command:lv,keyPressDelayMs:Ft.number().optional()}),Ku=Ft.object({moduleId:Ft.string(),inputs:Ft.record(Ft.string(),Ft.string()).optional()}),Yu=Al.merge(Ku.extend({type:Ft.literal("MOBILE_MODULE_STEP")})),i7=Ku.extend({steps:Ft.lazy(()=>ro.array())}),Cl=Al.extend({type:Ft.literal("MOBILE_AI_ACTION_STEP"),text:Ft.string()}),ro=Ft.discriminatedUnion("type",[wl,Yu,Cl]);var lg=bt.object({parameterNames:bt.string().array(),defaultParameters:bt.record(bt.string(),bt.string()).optional(),parameterEnums:bt.record(bt.string(),bt.string().array()).optional()}),gv=bt.object({moduleId:bt.string().uuid(),name:bt.string(),description:bt.string().nullish(),parameters:lg.optional(),enabled:bt.boolean().nullish(),schemaVersion:bt.string()}),Xu=gv.omit({name:!0}),fv=Xu.extend({steps:bt.array(bt.record(bt.string(),bt.unknown()))}),tF=bt.object({fileType:bt.literal(Se.MOBILE_MODULE)}).merge(fv),rF=gv.omit({schemaVersion:!0}).extend({steps:bt.array(ro)});import $e from"zod";import*as Ha from"zod";var p7=Ha.custom().refine(t=>t&&t.length>0).refine(t=>t&&t[0]instanceof File,{message:"Please upload a valid file."}),cg=Ha.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();return e.length===0?void 0:e},Ha.string().optional());import xl from"zod";var Do=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Do||{}),ug=Ku.extend({steps:xl.lazy(()=>Ga.array()),description:xl.string().optional(),name:xl.string().describe("name of the module"),parameters:lg.optional()}),nF=Al.merge(ug).extend({type:xl.literal("RESOLVED_MOBILE_MODULE")}),Ga=xl.discriminatedUnion("type",[nF,wl,Cl]);function Sv(t){return Object.values(Do).includes(t)||Object.values(wn).includes(t)}var oF=$e.object({disableMomenticAccessibilityTree:$e.boolean().optional(),autoGrantPermissions:$e.boolean().optional()}),dg=oF.extend({region:hv.optional().describe("Do you want local or Limbar?"),remoteEmulatorSettings:$e.object({androidVersion:$e.nativeEnum(Rl).optional()}).optional(),localEmulatorSettings:$e.object({avdId:cg}).optional(),geolocation:$e.object({latitude:$e.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:$e.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional()}),ja=$e.object({retries:$e.number().optional().describe("number of retries to run"),defaultChannel:$e.string().optional().describe("default channel to use"),defaultTag:$e.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:$e.string().optional(),defaultApkFilePath:cg.describe("APK to install when using the emulator in the local region."),emulator:dg.optional(),ai:yl.optional()}),Va=$e.object({id:$e.string().uuid(),description:$e.string(),schemaVersion:$e.string(),settings:ja.optional(),disabled:$e.boolean().optional(),labels:$e.array($e.string()).optional()}),yv=$e.object({fileType:$e.literal(Se.MOBILE_TEST)}).merge(Va),iF=Va.merge($e.object({steps:$e.array(ro)})),I7=yv.merge(iF),O7=$e.object({name:$e.string(),steps:$e.array(ro).optional(),settings:ja.optional()}),Ev=Va.extend({steps:Ga.array()});import ie from"zod";var Cn=ie.object({startTime:ie.number(),endTime:ie.number().optional(),durationMs:ie.number().optional(),error:ie.string().optional(),result:ie.unknown().optional(),attributes:ie.record(ie.string(),ie.unknown())});var aF=Cn.extend({type:ie.literal("SECTION"),name:ie.string(),subSpans:ie.lazy(()=>xn.array())}),sF=Cn.extend({type:ie.literal("AI_LOCATOR_CALL"),result:ie.object({id:ie.number(),thoughts:ie.string()}).optional(),subSpans:ie.lazy(()=>xn.array())}),lF=Cn.extend({type:ie.literal("AI_ASSERTION_CALL"),result:ie.object({thoughts:ie.string(),result:ie.boolean()}).optional(),subSpans:ie.lazy(()=>xn.array())}),cF=Cn.extend({type:ie.literal("TARGET_RESOLUTION"),result:ie.object({serializedElement:ie.string()}).optional(),subSpans:ie.lazy(()=>xn.array())}),uF=Cn.extend({type:ie.literal("EMULATOR_INTERACTION"),name:ie.string(),withinWebview:ie.boolean().optional(),subSpans:ie.lazy(()=>xn.array())}),dF=Cn.extend({type:ie.literal("EMULATOR_READ_STATE"),name:ie.string(),subSpans:ie.lazy(()=>xn.array())}),pF=Cn.extend({type:ie.literal("ELEMENT_ASSERTION"),name:ie.string(),result:ie.object({success:ie.boolean(),message:ie.string().optional()}).optional(),subSpans:ie.lazy(()=>xn.array())}),mF=Cn.extend({type:ie.literal("CACHE_RESOLUTION"),subSpans:ie.lazy(()=>xn.array())}),hF=Cn.extend({type:ie.literal("WAIT_FOR_SCREENSHOT_STABILITY"),subSpans:ie.lazy(()=>xn.array())}),gF=Cn.extend({type:ie.literal("GENERIC"),name:ie.string(),subSpans:ie.lazy(()=>xn.array())}),xn=ie.discriminatedUnion("type",[aF,sF,lF,cF,uF,dF,pF,mF,hF,gF]);import Jt from"zod";var _l=Jt.object({message:Jt.string().optional(),startTime:Jt.number(),endTime:Jt.number(),status:Jt.nativeEnum(Fe),trace:Jt.unknown(),beforeSnapshot:Jt.string().optional(),afterSnapshot:Jt.string().optional(),data:Jt.unknown().optional().describe("output data from the step")}),fF=_l.merge(wl).extend({previousAttempts:Jt.lazy(()=>cn.array()).optional()}),SF=_l.merge(Yu).extend({steps:Jt.lazy(()=>cn.array()),name:Jt.string().optional(),previousAttempts:Jt.lazy(()=>cn.array()).optional()}),yF=_l.merge(Cl).extend({steps:Jt.lazy(()=>cn.array()),previousAttempts:Jt.lazy(()=>cn.array()).optional()}),cn=Jt.discriminatedUnion("type",[fF,SF,yF]);import{parse as V7}from"date-fns";import{z as $a}from"zod";var W7=$a.object({testId:$a.string(),sessionId:$a.string()}),bv=$a.object({uploadUrl:$a.string(),id:$a.string()});import Ml from"zod";var EF=_l.extend({index:Ml.number().optional(),userFacingStepReference:Ml.string().optional(),description:Ml.string()}),Tv=EF.extend({beforeScreenshot:Ml.string().optional(),afterScreenshot:Ml.string().optional()});var vv=ue.object({attributesRequired:ue.array(ue.string()).optional(),textRequired:ue.boolean().optional(),boundsRequired:ue.boolean().optional(),positionSpecificity:ue.nativeEnum(gr).optional(),shapeSpecificity:ue.nativeEnum(gr).optional()}),bF=ue.object({thoughts:ue.string(),id:ue.number(),updatedMemory:Js.optional(),inWebview:ue.boolean().optional(),requirements:vv.optional(),additionalElements:ue.object({id:ue.number(),requirements:vv}).array().optional()}),Rv=ue.object({description:ue.string(),screenXml:ue.string(),screenshot:ue.string(),memory:ue.discriminatedUnion("type",[Xn,ue.object({type:ue.literal("RESOLVED_TRACES"),traces:ue.unknown().array()})]).optional()}),Av=ue.object({assertion:ue.string(),screenXml:ue.string(),screenshot:ue.string(),memory:ue.discriminatedUnion("type",[tl,ue.object({type:ue.literal("RESOLVED_TRACES"),traces:ue.unknown().array()})]).optional()}),TF=ue.object({thoughts:ue.string(),result:ue.boolean(),relevantElements:ue.array(ue.number()).optional(),updatedMemory:el.optional()}),wv=ue.object({failedResults:Tv.array(),nextStepsSerialized:ue.string().array(),currentScreenXml:ue.string(),currentScreenshot:ue.string(),customInstructions:ue.string().optional(),testDescription:ue.string()}),Cv=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Cv||{}),vF=ue.object({thoughts:ue.string(),scenario:ue.nativeEnum(Cv),instructions:ue.string().nullish()});var xv=t=>!(!t.org_id||!t.user_id||!t.platform);import{z as Ii}from"zod";var _v=Ii.object({id:Ii.string().uuid(),skipped:Ii.boolean().optional(),envKey:Ii.string().optional().describe("key in the environment to save the result of this step to")}),pg=_v.merge(gi).extend({type:Ii.literal("REQUEST")}),mg=_v.merge(iu).extend({type:Ii.literal("JAVASCRIPT")}),hg=Ii.discriminatedUnion("type",[mg,pg]);import{z as jr}from"zod";var Mv=jr.object({id:jr.string(),name:eo,description:jr.string().optional().nullish(),baseUrl:Au.nullish(),schemaVersion:jr.string(),advanced:jr.unknown().optional(),retries:jr.number(),envs:jr.array(ku).nullish(),parameters:Du.nullish()}),RF=jr.object({createdAt:jr.coerce.date(),updatedAt:jr.coerce.date(),schedule:Fa.nullish(),notification:Ua.nullish(),createdBy:jr.string(),organizationId:jr.string()}),AF=Mv.merge(RF),Fee=AF.extend({steps:hg.array()}),Uee=Mv.extend({steps:hg.array()});import{z as Sr}from"zod";var Pv=Sr.object({startedAt:Sr.coerce.date(),finishedAt:Sr.coerce.date(),status:Sr.nativeEnum(Fe),message:Sr.string().optional(),data:Sr.unknown().optional()}),wF=Pv.merge(mg).extend({type:Sr.literal("JAVASCRIPT")}),CF=Pv.merge(pg).extend({type:Sr.literal("REQUEST")}),xF=Sr.discriminatedUnion("type",[wF,CF]),Iv=Sr.object({startedAt:Sr.coerce.date(),finishedAt:Sr.coerce.date().nullish(),status:Sr.nativeEnum(Me),results:xF.array(),failureReason:Sr.string().nullish(),failureDetails:yu.nullish()});import{z as yr}from"zod";var _F=yr.object({id:yr.string(),organizationId:yr.string(),createdAt:yr.coerce.date(),updatedAt:yr.coerce.date(),createdBy:yr.string(),scheduledAt:yr.coerce.date().nullish(),startedAt:yr.coerce.date().nullish(),finishedAt:yr.coerce.date().nullish(),status:yr.nativeEnum(Me),trigger:yr.nativeEnum(zr),results:Iv.array().nullish(),apiTestName:yr.string().nullish(),apiTestPath:yr.string().nullish(),apiTestId:yr.string().nullish()}),Kee=_F.pick({status:!0,startedAt:!0,finishedAt:!0});var Pl=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Pl||{}),Ov=3;function MF(t){return t==="MODULE"||t==="CONDITIONAL"||t==="SECTION"||t==="RESOLVED_MODULE"}function gg(t){if(!MF(t))switch(t){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function fg(t){switch(t.type){case"AI_EXTRACT":case"AI_ASSERTION":return Ov;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return t.useSelector||!t.target||t.target.type!=="description"?0:1;case"DRAG":return t.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var Wa=class{trackStepExecution(){}async flush(){}};import{parseString as PF,splitCookiesString as IF}from"set-cookie-parser";import{z as He}from"zod";var Sg=He.object({name:He.string(),value:He.string(),url:He.string().optional(),domain:He.string().optional(),path:He.string().optional(),expires:He.number().default(Date.now()/1e3+60*60*24*365),httpOnly:He.boolean().optional(),secure:He.boolean().default(!0),sameSite:He.union([He.literal("Strict"),He.literal("Lax"),He.literal("None")]).default("None")});function Ju(t,e){let r=[],n=IF(t);for(let o of n){let i=PF(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=Sg.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});r.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||r.push({...s,name:d,value:p})}}return r}var OF=He.object({origin:He.string(),localStorage:He.array(He.object({name:He.string(),value:He.string()}))}),LF=He.object({entries:He.record(He.string(),He.array(He.tuple([He.unknown(),He.unknown()]))),version:He.number().optional()}),Qu=He.object({cookies:Sg.array().optional(),origins:OF.array().optional(),idb:He.record(He.string(),LF).optional().describe("key is db name")});function Lv(t,e){let r=[];return t.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Sg.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),r.push(i)}),r}var Ete=new Set(Object.values(Qe));var NF={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",CONDITIONAL:"Conditional",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},bte={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],CONDITIONAL:["conditional","if","else","elif","branch"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},Tte={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of an AI Check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},vte={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",SCROLL_TO:"Scroll to",DRAG_AND_DROP:"Drag & drop",SCREEN_CHECK:"Screen check",ELEMENT_CHECK:"Element check",OPEN_APP:"Open app",KILL_APP:"Kill app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",INSTALL_APP:"Install app",UNINSTALL_APP:"Uninstall app",TOGGLE_SETTINGS:"Toggle settings",ADB:"ADB command",STATE:"Debug state"},Rte={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",DRAG_AND_DROP:"Drag an element onto another element in the same context.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Terminate the currently active app and remove it from recents.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install one or more APKs onto the connected emulator (local emulator only).",UNINSTALL_APP:"Uninstall an APK from the connected emulator (local emulator only).",TOGGLE_SETTINGS:"Toggle device settings.",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",AI_CHECK:"Ask AI to verify whether something is true on the screen."};import DF from"semver";import{z as kF}from"zod";var xte=kF.string().refine(t=>DF.valid(t),{message:"must be a valid semver string"});import{Faker as Pte,en as Ite}from"@faker-js/faker";import{z as F}from"zod";var qa=55555,Lte=F.object({body:F.string(),to:F.string(),from:F.string()}),Nte=F.object({from:F.string().optional(),to:F.string(),timeout:F.number().optional(),beforeDate:F.string().pipe(F.coerce.date()).or(F.date()).optional(),afterDate:F.string().pipe(F.coerce.date()).or(F.date()).optional()}),Dte=F.object({to:F.string().email(),from:F.string(),subject:F.string(),body:F.string(),html:F.string().optional()}),kte=F.object({inbox:F.string().transform(t=>t.toLowerCase()),afterDate:F.string().pipe(F.coerce.date()).or(F.date()).optional(),timeout:F.number().optional(),trimWhitespace:F.boolean().optional()}),Fte=F.object({inbox:F.string(),limit:F.number().optional(),afterDate:F.string().pipe(F.coerce.date()).or(F.date()).optional(),trimWhitespace:F.boolean().optional()});var Zu=(r=>(r.RAW="RAW",r.RESPONSE="RESPONSE",r))(Zu||{}),Nv=F.object({body:F.string().nullish(),status:F.number().optional(),headers:F.array(F.tuple([F.string(),F.string()])).optional()}),FF=F.object({url:F.string(),options:F.object({method:F.string(),body:F.string().nullish(),headers:F.array(F.tuple([F.string(),F.string()])).optional()}).optional()}).optional(),UF=F.object({body:F.string().nullish(),options:F.object({status:F.number(),statusText:F.string().optional(),headers:F.array(F.tuple([F.string(),F.string()])).optional()}).optional()}).optional(),Dv=F.object({result:F.unknown(),variableUpdates:F.record(F.string(),F.unknown()).optional(),persistentVariableUpdates:F.record(F.string(),F.unknown()).optional(),error:F.string().optional(),success:F.boolean()}),Ute=F.object({id:F.string().optional(),orgId:F.string(),momenticLambdaAuthHash:F.string(),code:F.string(),fragment:F.boolean(),state:F.object({env:F.record(F.string(),F.unknown()),request:FF,response:UF,additionalBindings:F.record(F.string(),F.unknown()).optional()}),timeoutMs:F.number().optional(),disallowVariableUpdates:F.boolean().optional(),responseSerialization:F.nativeEnum(Zu).optional()}),ko=15e3;import*as Qt from"zod";import{extendZodWithOpenApi as BF}from"zod-openapi";BF(Qt);var zF=Qt.object({url:Qt.string(),lineNumber:Qt.number(),columnNumber:Qt.number()}).openapi({ref:"CodeLocation"}),ed=Qt.object({timestamp:Qt.number(),text:Qt.string(),type:Qt.string(),tabIndex:Qt.number(),args:Qt.unknown().array().optional(),url:Qt.string().optional(),location:zF.optional()}).openapi({ref:"ConsoleLog"}),kv=ed.array(),yg=kv.array();import*as Eg from"zod";import{extendZodWithOpenApi as HF}from"zod-openapi";HF(Eg);var GF=Eg.object({logsPerPage:ed.array().array()}).openapi({ref:"DebugData"});var Il=class{async getConsoleLogsForRunAttempt(e,r,n){}async getNetworkLogsForRunAttempt(e,r,n){}async getHtmlSnapshot(e,r){}async getA11yTreeSnapshot(e,r){}async getScreenshot(e,r){}async storeConsoleLogsForRunAttempt(e,r,n,o){}async storeNetworkLogsForRunAttempt(e,r,n,o){}listVideoAssetPaths(){return[]}close(){}async storeScreenshot(e,r,n){}async storeHtmlSnapshot(e,r,n){}};import{z as I}from"zod";var jF=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),VF=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),$F=I.object({onContentLoad:I.number().optional(),onLoad:I.number().optional(),comment:I.string().optional()}),Ol=I.object({startedDateTime:I.string(),id:I.string(),title:I.string().optional(),pageTimings:$F,comment:I.string().optional()}),WF=I.array(Ol),qF=I.object({name:I.string(),value:I.string(),path:I.string().optional(),domain:I.string().optional(),expires:I.string().optional(),httpOnly:I.boolean().optional(),secure:I.boolean().optional(),comment:I.string().optional()}),Uv=I.array(qF),KF=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),Bv=I.array(KF),YF=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),XF=I.array(YF),JF=I.object({name:I.string(),value:I.string().optional(),fileName:I.string().optional(),contentType:I.string().optional(),comment:I.string().optional()}),QF=I.array(JF),ZF=I.object({mimeType:I.string(),params:QF,text:I.string(),comment:I.string().optional(),_redactedReason:I.string().optional()}),eU=I.object({method:I.string(),url:I.string(),httpVersion:I.string().optional(),cookies:Uv,headers:Bv,queryString:XF,postData:ZF.optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),tU=I.object({size:I.number().optional(),compression:I.number().optional(),mimeType:I.string().optional(),text:I.string().optional(),encoding:I.string().optional(),comment:I.string().optional(),_redactedReason:I.string().optional()}),rU=I.object({status:I.number(),statusText:I.string(),httpVersion:I.string().optional(),cookies:Uv,headers:Bv,content:tU,redirectURL:I.string().optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional(),_mocked:I.boolean().optional()}),Fv=I.object({expires:I.string().optional(),lastAccess:I.string(),eTag:I.string(),hitCount:I.number(),comment:I.string().optional()}),nU=I.object({beforeRequest:Fv.optional(),afterRequest:Fv.optional(),comment:I.string().optional()}),oU=I.object({blocked:I.number().optional(),dns:I.number().optional(),connect:I.number().optional(),send:I.number(),wait:I.number(),receive:I.number(),ssl:I.number().optional(),comment:I.string().optional()}),Ll=I.object({pageref:I.string().optional(),startedDateTime:I.string(),time:I.number().optional(),request:eU,response:rU.optional(),cache:nU.optional(),timings:oU,serverIPAddress:I.string().optional(),connection:I.string().optional(),comment:I.string().optional(),_resourceType:I.string().optional()}),iU=I.array(Ll),aU=I.object({version:I.string().default("1.1"),creator:jF.optional(),browser:VF.optional(),pages:WF.optional(),entries:iU,comment:I.string().optional()}),sU=I.object({log:aU}),Jte=I.record(I.string(),Ol),Qte=I.record(I.string(),Ll);function bg(t,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(t).sort((r,n)=>new Date(r.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((r,n)=>new Date(r.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}import{cloneDeep as lU}from"lodash-es";import{z as _n}from"zod";var Tg=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(Tg||{});var zv=_n.union([_n.string(),_n.number(),_n.boolean(),_n.null(),_n.record(_n.string(),_n.lazy(()=>zv)),_n.array(_n.lazy(()=>zv))]),Nl=class{flags;payloads;constructor(e,r){this.flags=e,this.payloads=r}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=lU(this.flags);return Object.entries(e).forEach(([r,n])=>{typeof n=="boolean"&&Object.values(Tg).includes(r)&&(e[r]=this.isBooleanFlagEnabled(r))}),e}getFlagPayload(e){let r=this.payloads[e];if(r!==void 0){if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r}}refresh(){throw new Error("Not implemented")}},lre=new Nl({},{});var vg={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Hv=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],ure=Object.keys(vg);import{z as Fo}from"zod";var mre=Fo.object({id:Fo.string(),name:Fo.string(),createdAt:Fo.coerce.date(),createdBy:Fo.string(),updatedAt:Fo.coerce.date(),updatedBy:Fo.string().nullable(),organizationId:Fo.string()});import{z as D}from"zod";import Uo from"zod";var Ka=Uo.object({platformSep:Uo.string(),fullPathSegments:Uo.string().array(),relativePathSegments:Uo.string().array(),relativePath:Uo.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Uo.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Uo.coerce.date(),createdAt:Uo.coerce.date()});var cU=D.array(Ka.extend({id:D.string(),name:D.string(),description:D.string().optional(),labels:D.string().array().optional()})),uU=Ka.extend({id:D.string(),name:D.string(),description:D.string().optional(),content:Ih}),dU=D.array(uU),Cre=D.object({tests:cU,modules:dU,labels:D.string().array()}),xre=Wu.merge(Gr),Gv=D.object({schemaVersion:D.string(),stepLists:_o}),jv=Gr.partial().merge(Xt.pick({id:!0})),Rg={name:D.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:D.string().optional(),baseUrl:D.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:D.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:D.nativeEnum(An).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Cu.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:D.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},Vv=D.object(Rg),_re=Wu.merge(D.object({relativeFilePath:D.string().describe("relative to project root")})),$v=D.object({name:D.string()}),Mre=D.object({relativeFilePath:D.string()}),Wv=D.object({name:D.string()}),Pre=D.object({relativeFilePath:D.string()}),qv=D.object({name:D.string(),description:D.string(),enabled:D.boolean(),steps:D.lazy(()=>ft.array()),testFilePath:D.string().describe("relative to the project root"),folderPath:D.string().optional().describe("user selected folder path")}),Kv=D.object({name:D.string(),description:D.string(),enabled:D.boolean()}).partial();var Ire=D.array(wT),Yv=D.object({defaultEnv:D.string().optional().describe("name of the default env, or undefined to unset")}),Xv=D.object({configFilePath:D.string().describe("full path on disk")}),Ore=D.string().array(),Lre=D.object({message:D.string(),newRelativeTestPath:D.string().optional()}),Ag=D.object({name:D.string(),absolutePath:D.string(),relativePath:D.string(),pathSegments:D.array(D.string()),isDirectory:D.boolean(),size:D.number(),createdAt:D.coerce.date(),modifiedAt:D.coerce.date(),accessedAt:D.coerce.date()}),Jv=D.object({pathSegments:D.array(D.string())}),Nre=D.object({absolutePath:D.string(),pathSegments:D.array(D.string()),contents:D.array(Ag)}),Qv=D.object({pathSegments:D.array(D.string())}),Zv=D.object({pathSegments:D.array(D.string()),newPathSegments:D.array(D.string())}),eR=D.object({pathSegments:D.array(D.string()),recursive:D.boolean().optional()}),Dre=D.object({success:D.boolean(),message:D.string(),pathSegments:D.array(D.string()).optional()}),kre=D.object({gitBranch:D.string(),fileMtime:D.coerce.date(),gitCommitSha:D.string()});var td=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],rd=td.map(t=>`**/${t}/**`),tR=!0,wr=!1,rR=15e4;import Mn from"chalk";import pU from"safe-stable-stringify";import mU from"truncate-json";import hU from"zod";var Oi=pU.configure({deterministic:!1});function nR(t){let e=Oi(t),{jsonString:r}=mU(e,5e4);return r}var gU=["app","version","env","namespace","host"];function je(t){let e=t.bindings()??{},r={};for(let n of Object.keys(e)){let o=e[n];!gU.includes(n)&&typeof o=="string"&&(r[n]=o)}return r}var wg=hU.enum(["debug","info","warn","error"]);var Dl={debug:20,info:30,warn:40,error:50},oR={20:"debug",30:"info",40:"warn",50:"error"},Li=class t{minLogLevel;logBindings;constructor(e,r){typeof e=="string"?this.minLogLevel=Dl[e]:this.minLogLevel=e,this.logBindings=r}logWithLevel(e,r,...n){try{this.logWithLevelHelper(e,r,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}indentMultiline(e,r=" "){return e.split(`
22
22
  `).map((n,o)=>o>0?`${r}${n}`:n).join(`
23
23
  `)}logWithLevelHelper(e,r,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let i=[];if(i.push(...n),console.log(r(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[s,c]of a){let l=c;if(c instanceof Error){l=c.message,console.log(r(` ${s}:`,l)),console.log(r(" stack:",c.stack));let d=Object.entries(c).filter(([p])=>p!=="message"&&p!=="stack");for(let[p,m]of d){if(m instanceof Error){console.log(r(` ${s}.${p}:`,m.message)),m.stack&&console.log(r(` ${s}.${p}.stack:`,m.stack));continue}if(typeof m=="object"&&m!==null){let g=this.indentMultiline(Oi(m,void 0,2)," ");console.log(r(` ${s}.${p}:`,g));continue}console.log(r(` ${s}.${p}:`,m))}}else typeof c=="object"?(l=Oi(c,void 0,2),l=this.indentMultiline(l),console.log(r(` ${s}:`,l))):console.log(r(` ${s}:`,l))}}else if(o)for(let a of o){let s=a;typeof a=="object"&&(s=Oi(a,void 0,2),s=s.split(`
24
24
  `).map((c,l)=>l>0?` ${c}`:c).join(`
25
- `)),console.log(" ",r(s))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=Dl[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Mn.reset,...e)}info(...e){this.logWithLevel(30,Mn.white,...e)}debug(...e){this.logWithLevel(20,Mn.dim,...e)}warn(...e){this.logWithLevel(40,Mn.yellow,...e)}error(...e){this.logWithLevel(50,Mn.red,...e)}success(...e){this.logWithLevel(1/0,Mn.green,...e)}dimmed(...e){this.logWithLevel(30,Mn.dim,...e)}underline(...e){this.logWithLevel(40,Mn.underline,...e)}bold(...e){this.logWithLevel(40,Mn.bold,...e)}grey(...e){this.logWithLevel(20,Mn.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},Cg=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},Vre=new Cg,fU=typeof window>"u"&&typeof process<"u"&&wg.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?wg.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,b=new Li(fU,{}),Pn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Pn,flush:async()=>{},bindings:()=>({})},nd={},od=({logger:t,logKey:e,maxCount:r,intervalMs:n},o,i,...a)=>{let s=nd[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},nd[e]=s),s.totalCount++,s.count<r&&(s.count++,t.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=nd[e];c?.totalCount!==c?.count&&t.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete nd[e]},n)};import{z as oe}from"zod";var SU=oe.array(Ka.extend({id:oe.string(),name:oe.string(),description:oe.string().optional(),labels:oe.string().array().optional()})),yU=oe.array(Ka.extend({id:oe.string(),name:oe.string(),description:oe.string().optional(),content:ug})),Xre=oe.object({name:oe.string(),description:oe.string().optional(),settings:ja.optional(),pathSegments:oe.string().array(),defaultEnv:oe.string().optional()}),Jre=oe.object({id:oe.string(),fileName:oe.string(),fullPath:oe.string(),relativeFilePath:oe.string().describe("relative to project root")}),Qre=Ev.extend({name:oe.string()}),Zre=oe.object({steps:Ga.array().optional(),settings:ja.optional()}),ene=oe.object({message:oe.literal("ok")}),tne=oe.object({name:eo.optional(),description:oe.string().min(1).optional(),settings:ja.optional(),disabled:oe.boolean().optional()}),rne=oe.object({message:oe.string(),newRelativeTestPath:oe.string().optional()}),nne=oe.object({tag:oe.string(),channel:oe.string(),filePath:oe.string()}),one=oe.object({name:eo}),ine=oe.object({tests:SU,modules:yU,labels:oe.string().array()}),ane=oe.object({name:oe.string(),description:oe.string(),enabled:oe.boolean()}).partial(),sne=oe.object({name:oe.string(),description:oe.string(),enabled:oe.boolean(),steps:Ga.array(),testFilePath:oe.string().describe("relative to the project root"),folderPath:oe.string().optional().describe("user selected folder path")}),lne=oe.object({packages:oe.string().array()});import{z as Tt}from"zod";var iR=Tt.object({id:Tt.string(),createdAt:Tt.coerce.date(),createdBy:Tt.string(),organizationId:Tt.string(),name:Tt.string(),description:Tt.string().nullish(),enabled:Tt.boolean(),schemaVersion:Tt.string().describe("Schema version for steps"),parameters:Tt.string().array().nullish().describe("Parameter list"),parameterEnums:Tt.record(Tt.string(),Tt.string().array()).nullish(),defaultParameters:Tt.record(Tt.string(),Tt.string()).nullish(),defaultCacheKey:Tt.string().nullish(),defaultCacheTtl:Tt.number().nullish(),defaultCacheAllInvocations:Tt.boolean().nullish(),autoAuth:Tt.boolean().nullish(),advanced:_h.nullish()}),Sne=iR.extend({steps:Tt.lazy(()=>Qe.array())}),aR=5*60*1e3,xg=fr.merge(iR.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as bne}from"date-fns-tz";import{z as $e}from"zod";var _g=yl.extend({aiAction:$e.boolean().optional(),stepLintSuggestions:$e.boolean().optional(),agentConfig:$e.record($e.string(),$e.string()).optional(),aiFailureAnalysis:$e.boolean().optional(),aiPageFiltering:$e.boolean().optional().describe("rag v2 feature flag")}),EU=$e.object({cliOnly:$e.boolean().optional()}),Mg=$e.object({fakerConstantSeed:$e.boolean().optional()}),sR=$e.object({ai:_g.optional(),githubAppInstallationId:$e.number().nullish(),githubAppSummaryMessageEnabled:$e.boolean().nullish(),githubReleaseAppInstallationId:$e.number().nullish(),gitlabAppAccessToken:$e.string().nullish(),gitlabAppBaseUrl:$e.string().nullish(),qaseAccessToken:$e.string().nullish(),testSuggestionsEnabled:$e.boolean().nullish(),browser:Gh.optional(),internal:EU.optional(),advanced:Mg.optional()}),Cne=$e.object({globalOverrides:$e.record($e.string()).optional(),agentConfig:$e.record($e.string(),$e.string()).optional()}),xne=$e.record($e.string(),$e.string()).nullish();import*as A from"zod";import{z as yt}from"zod";var Pg=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Pg||{});var bU=yt.object({type:yt.literal("DESCRIPTION_UPDATE"),thoughts:yt.string()}),id=yt.discriminatedUnion("type",[bU]),TU=yt.object({testId:yt.string(),name:yt.string(),orgId:yt.string(),runId:yt.string(),steps:ft.array(),purpose:yt.nativeEnum(Pg),details:id.or(id.array()).optional()});var Ine=TU.pick({name:!0,orgId:!0}),vU=yt.object({id:yt.string(),name:yt.string().nullish(),createdAt:yt.string().pipe(yt.coerce.date()).or(yt.date()),organizationId:yt.string(),schemaVersion:yt.string(),runId:yt.string().nullish(),purpose:yt.nativeEnum(Pg),details:id.or(id.array()).optional(),applied:yt.boolean().nullish(),appliedAt:yt.coerce.date().nullish()}),lR=vU.extend({steps:ft.array()});var ad="x-momentic-cli-version",cR="x-momentic-client-mode",uR="x-momentic-cli-type",dR="x-momentic-logger-tags",RU="x-momentic-main-branch-name",AU="x-momentic-branch-name",wU="x-momentic-commit-timestamp",CU="x-momentic-last-commit-on-main",xU="x-momentic-last-commit-on-main-timestamp",_U="x-momentic-merged-branch-name",pR="x-momentic-session-id",Xne=A.object({error:A.boolean(),reason:A.string(),message:A.string()}),Jne=Ct.merge(Yh),mR=cu,Qne=Ct.merge(Yh);var Zne=Ct.merge(VT).extend({useConsensus:A.boolean().optional(),attemptNumber:A.number().optional()}),Ig=PE,eoe=Ct.merge(WT),hR=cT,toe=Ct.merge(qT),gR=uT,roe=Ct.merge(KT),fR=dT,noe=Ct.merge($T),SR=lT,ooe=Ct.merge(HT),yR=sT,ioe=Ct.merge(GT),ER=iT,aoe=Ct.merge(jT);var soe=Ct.merge(QT),loe=Ct.merge(ZT),coe=A.object({testPaths:A.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:A.string().optional(),all:A.boolean().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional(),testInputMatrix:A.record(A.string(),A.string()).array().optional()}),bR=A.object({queuedTests:A.unknown().array(),runIds:A.string().uuid().array(),runGroupId:A.string().optional()});var uoe=A.string().array(),doe=A.union([A.object({paths:A.string().array().describe("run specific test paths (e.g. todo-test)"),all:A.boolean().describe("run all tests").optional()}),A.object({path:A.string().describe("deprecated; present for backcompat")})]),TR=A.object({tests:A.record(A.string().describe("Test name"),A.string().describe("Test YAML")),modules:A.record(A.string().describe("Module name"),A.string().describe("Module YAML"))}),MU=A.object({test:A.string().describe("test YAML"),modules:A.record(A.string().describe("moduleId"),A.string().describe("module YAML"))}),poe=MU.array(),moe=A.object({testId:A.string(),schemaVersion:A.string()}).merge(Ti);function Og(t){let{gitMainBranch:e,gitBranchName:r,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=t,a={};return e&&(a[RU]=encodeURIComponent(e)),r&&(a[AU]=encodeURIComponent(r)),n&&(a[wU]=n.toISOString()),o&&(a[CU]=encodeURIComponent(o)),i&&(a[xU]=i.toISOString()),t.mergedGitBranchName&&(a[_U]=encodeURIComponent(t.mergedGitBranchName)),a}var hoe=A.object({entries:A.array(ob),testId:A.string()}),goe=A.object({entries:A.array(uv),testId:A.string()}),foe=A.object({testId:A.string()});function vR(t){return A.record(A.unknown()).transform(e=>{let r={};for(let[n,o]of Object.entries(e)){let i=t.safeParse(o);i.success&&(r[n]=i.data)}return r})}var RR=vR(ib),AR=vR(dv),wR=A.object({trigger:A.nativeEnum(zr),status:A.nativeEnum(Me),startedAt:A.coerce.date().optional(),gitCommitSha:A.string().optional(),gitCommitShaShort:A.string().optional(),gitCommitTimestamp:A.coerce.date().optional(),gitBranchName:A.string().optional(),gitOriginUrl:A.string().optional(),gitCommitMessage:A.string().optional(),gitCommitAuthorName:A.string().optional(),githubRepository:A.string().optional(),gitlabProjectPath:A.string().optional(),pipelineId:A.string().optional(),cliVersion:A.string().optional()}),Soe=A.object({id:A.string()}),CR=A.object({status:A.nativeEnum(Me),updatedAt:A.coerce.date().optional(),finishedAt:A.coerce.date().optional()}),xR=A.object({stepsSnapshot:A.array(A.record(A.unknown())).optional(),runGroupId:A.string().optional(),testId:A.string(),testName:A.string(),resolvedBaseUrl:A.string().optional(),environmentName:A.string().optional(),labels:A.array(A.string()).optional(),cliVersion:A.string().optional(),trigger:A.nativeEnum(zr),schemaVersion:A.string().optional(),section:A.nativeEnum(Fu).optional(),resolvedInputs:A.record(A.string(),A.string()).optional(),quarantined:A.boolean().optional().default(!1),quarantinedReason:A.string().optional()}),yoe=A.object({id:A.string()}),PU=qh.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),_R=PU.array(),MR=qh.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),Eoe=A.object({id:A.string()}),PR=A.object({status:A.nativeEnum(Me),finishedAt:A.coerce.date().optional(),schemaVersion:A.string().optional().default("1.0.19"),results:A.record(A.string(),A.unknown()).array().optional(),beforeResults:A.record(A.string(),A.unknown()).array().optional(),afterResults:A.record(A.string(),A.unknown()).array().optional()}),boe=A.object({screenshot:A.string()}),IR=A.object({key:A.string()}),OR=A.object({orgId:A.string(),userId:A.string()}),LR=A.array(AT),Toe=A.record(A.string(),A.union([A.string(),A.boolean()])),voe=A.object({paths:A.string().array(),env:A.string().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional()}),NR=A.object({suiteRunIds:A.string().array(),runGroupIds:A.string().array()}),Roe=A.object({suiteRunIds:A.string().array()}),Aoe=FT.array(),woe=A.object({runGroupIds:A.string().array()}),IU=A.object({uploadUrl:A.string()}),Coe=Ct.merge(YT),xoe=Ct.merge(JT),_oe=Ct.merge(XT),OU=A.object({testId:A.string().optional().default(""),testName:A.string().optional().default(""),suiteId:A.string().optional().default(""),suiteName:A.string().optional().default(""),creditsUsed:A.number().optional()}),LU=A.object({transactionId:A.string(),timestamp:A.string(),event:A.nativeEnum(Pl),properties:OU}),Moe=LU.array(),DR=lR.omit({steps:!0}).extend({steps:A.array(A.record(A.string(),A.unknown())).describe("unparsed ResolvedStep[]")}),Poe=A.object({limit:A.number().max(10).optional(),afterTime:A.number().optional()}),kR=OT.array(),Ioe=A.object({applied:A.boolean().optional(),appliedAt:A.coerce.date().optional()}),FR=IU.extend({id:A.string()}),Ooe=A.object({runGroupId:A.string().uuid().optional()}),UR=A.object({runGroupId:A.string().uuid()}),BR=A.object({quarantined:A.object({testId:A.string().uuid(),quarantinedAt:A.coerce.date(),quarantinedBy:A.string().optional(),quarantinedReason:A.string()}).array()}),Loe=A.object({testId:A.string().uuid(),testName:A.string().optional(),reason:A.string(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),Noe=A.object({testName:A.string().optional(),reason:A.string().optional(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),Doe=Ct.merge(Rv),koe=Ct.merge(Av),Foe=Ct.merge(wv),Uoe=A.object({apkToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(vl).optional(),osVersion:A.nativeEnum(Rl).optional(),sessionId:A.string().optional()}),zR=A.object({name:A.string(),webRtcUrl:A.string(),adbUrl:A.string(),token:A.string(),apkDownloadUrl:A.string().optional(),playwrightServerUrl:A.string().optional(),region:A.string().optional()}),Boe=A.object({hostname:A.string().optional(),region:A.nativeEnum(vl).optional(),osVersion:A.nativeEnum(ag).optional(),sessionId:A.string().optional()}),HR=A.object({id:A.string(),apiUrl:A.string(),webRtcUrl:A.string(),wdaUrl:A.string(),token:A.string(),region:A.string().optional()}),zoe=A.object({channel:A.string(),tag:A.string(),md5:A.string()}),GR=A.object({id:A.string(),uploadUrl:A.string().optional(),downloadUrl:A.string(),md5:A.string().optional()}),jR=A.object({assets:A.array(A.object({channel:A.string(),tag:A.string(),md5:A.string(),createdAt:A.number().describe("Unix timestamp in milliseconds")}))});import{z as ae}from"zod";var VR=7,NU=3,joe=ae.object({localTestId:ae.string(),quarantinedAt:ae.date(),quarantinedBy:ae.string().optional(),quarantinedReason:ae.string(),quarantinedByGitEmail:ae.string().optional(),quarantinedByGitName:ae.string().optional(),quarantinedByGitUsername:ae.string().optional()}).or(ae.object({cloudTestId:ae.string(),quarantinedAt:ae.date(),quarantinedBy:ae.string().optional(),quarantinedReason:ae.string(),quarantinedByGitEmail:ae.string().optional(),quarantinedByGitName:ae.string().optional(),quarantinedByGitUsername:ae.string().optional()})),$R=(r=>(r.QUARANTINE="QUARANTINE",r.UNQUARANTINE="UNQUARANTINE",r))($R||{});var Lg=ae.object({name:ae.string(),description:ae.string().nullish(),effect:ae.nativeEnum($R),labels:ae.array(ae.string()).nullish(),githubRepository:ae.string().nullish(),gitlabProjectPath:ae.string().nullish(),gitBranchName:ae.string().nullish(),slackNotificationChannel:ae.string().nullish()}),DU=ae.object({type:ae.literal("LAST_N_RUNS"),lastN:ae.number().min(NU)}),kU=ae.object({type:ae.literal("LAST_N_HOURS"),lastN:ae.number().min(1).max(VR*24)}),FU=ae.object({type:ae.literal("LAST_N_DAYS"),lastN:ae.number().min(1).max(VR)}),Ng=ae.discriminatedUnion("type",[DU,kU,FU]),UU=ae.object({flakeRateThreshold:ae.number().min(1).max(100),evaluationWindow:Ng}),BU=Lg.extend({type:ae.literal("FLAKE_RATE"),config:UU}),zU=ae.object({passRateThreshold:ae.number().min(1).max(100),evaluationWindow:Ng}),HU=Lg.extend({type:ae.literal("PASS_RATE"),config:zU}),GU=ae.object({failureCountThreshold:ae.number().min(0),evaluationWindow:Ng}),jU=Lg.extend({type:ae.literal("FAILURE_COUNT"),config:GU}),Voe=ae.discriminatedUnion("type",[BU,HU,jU]);import{z as vt}from"zod";var qoe=vt.object({repositoriesIndexed:vt.boolean(),indexingInProgress:vt.boolean(),indexesOutdated:vt.boolean()}),WR=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(WR||{}),qR=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(qR||{}),Koe=vt.object({name:vt.string(),status:vt.nativeEnum(WR),conclusion:vt.nativeEnum(qR).nullable()}),kl=vt.object({sha:vt.string(),message:vt.string(),author:vt.object({name:vt.string().optional(),email:vt.string().optional(),date:vt.coerce.date().optional()}),committer:vt.object({name:vt.string().optional(),email:vt.string().optional(),date:vt.coerce.date().optional()})}),Dg=vt.object({mergedBranch:vt.string().optional()});import{z as ut}from"zod";var KR=ut.object({orgId:ut.string(),cacheKeys:ut.string().array()}),Joe=ut.object({keyParams:KR,clientMetadata:ut.string(),lockAcquisitionTimeoutMs:ut.number().optional()}),YR=ut.object({acquired:ut.boolean(),acquiredByMetadata:ut.string(),keyPrefix:ut.string()}),Qoe=ut.object({keyPrefix:ut.string(),result:ut.string(),ttlMs:ut.number()}),Zoe=ut.union([ut.object({keyPrefix:ut.string()}),KR]),VU=ut.object({remainingTtlMs:ut.number(),value:ut.string().nullish()}),eie=ut.object({results:ut.record(ut.string(),VU),activeLocks:ut.string().array()}),XR=0,JR=5*60*1e3;var oie=90*24*60*60*1e3,iie=7*24*60*60*1e3;import{z as QR}from"zod";var lie=QR.object({quarantineNotifications:QR.string().nullish()});import{z as Ut}from"zod";var $U=Ut.object({version:Ut.string(),json:Ut.record(Ut.unknown()),hash:Ut.string()}),ZR=Ut.record(Ut.unknown()),pie=Ut.object({newSvgs:Ut.array($U),metadata:ZR.optional()}),WU=Ut.object({version:Ut.string(),json:Ut.record(Ut.unknown()).nullish(),hash:Ut.string(),description:Ut.string().nullish(),metadata:ZR.nullish()}),eA=Ut.record(Ut.string().describe("icon hash"),WU);import{z as ht}from"zod";var kg=ht.object({assertion:ht.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),qU=ht.object({instruction:ht.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:kg.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),tA=qU.extend({subSteps:ht.lazy(()=>tA.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),rA=ht.object({name:ht.string().describe("Short name describing the test plan"),description:ht.string().nullish().transform(t=>t??void 0).describe("Longer form description of the high level goal of the test plan")}),nA=rA.extend({id:ht.string(),createdAt:ht.coerce.date(),updatedAt:ht.coerce.date(),updatedBy:ht.string(),createdBy:ht.string(),test:ht.object({id:ht.string(),name:ht.string()}).nullish().transform(t=>t??void 0)}),fie=nA.extend({testGenRuns:ht.tuple([]).or(ht.tuple([ht.object({id:ht.string(),startedAt:ht.coerce.date(),status:ht.nativeEnum(Me)})]))}),oA=ht.object({preConditions:kg.array().nullish().transform(t=>t??[]),postConditions:kg.array().nullish().transform(t=>t??[]),steps:tA.array().nullish().transform(t=>t??[])}),Sie=nA.extend({plan:oA.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),KU=rA.extend({plan:oA.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),yie=KU.array().nullish().transform(t=>t??[]);import{validator as YU}from"@exodus/schemasafe";function iA(t){let e;try{e=JSON.parse(t)}catch(r){return`The schema is not valid JSON. ${r}`}try{YU(e)}catch(r){return`The schema is not a valid JSON schema. ${r}`}}var aA=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,r])=>e.trim()&&r.trim())))};import{z as Die}from"zod";var sd=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};var Ug="browser-crash-dump.zip",Fg=class{loggerBindings;getParentStepIdChain(){return[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}recordStepDuration(){}async finish(){}async startSubSteps(){return new Fl}},Fl=class{getParentStepIdChain(){return[]}async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new Fg}};import{z as Bg}from"zod";var $ie=Bg.object({parentStepIdChain:Bg.array(Bg.string()),result:cn});import{z as Z}from"zod";var ur="assets",XU=Z.object({step:ft,status:Z.nativeEnum(Fe),startedAt:Z.coerce.date(),finishedAt:Z.coerce.date().optional(),healMetadata:Z.object({healType:Z.nativeEnum(gl).or(Z.literal("AI")),healedAt:Z.coerce.date()}).optional(),beforeSnapshotId:Z.string().uuid().optional(),afterSnapshotId:Z.string().uuid().optional(),message:Z.string().optional()}),JU=XU.extend({finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)}),eae=JU.extend({step:Z.unknown()}),zg=Z.object({avdId:Z.string().optional(),channel:Z.string().optional(),tag:Z.string().optional()}),sA="1.0.0",Hg=PR.extend({id:Z.string().uuid().optional(),startedAt:Z.coerce.date(),runAttemptSchemaVersion:Z.string().optional(),schemaVersion:Z.string().optional().default("1.0.19"),results:Z.record(Z.string(),Z.unknown()).array().optional(),beforeResults:Z.record(Z.string(),Z.unknown()).array().optional(),afterResults:Z.record(Z.string(),Z.unknown()).array().optional(),assetDetails:zg.optional(),activeVideos:Z.array(Z.object({videoName:Z.string(),timestamp:Z.coerce.date()})).optional()}),lA=Hg.extend({assetDetails:zg.optional(),finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)}),tae=Hg.merge(Sl),rae=lA.merge(Sl),cA=Z.object({results:Z.array(cn),beforeResults:Z.array(cn).optional(),afterResults:Z.array(cn).optional()}),nae=Hg.merge(cA),oae=lA.merge(cA),uA=MR.merge(xR).extend({executionType:Z.nativeEnum(ka).optional().default("WEB"),testId:Z.string().uuid(),testDescription:Z.string().optional(),runGroupId:Z.string().uuid(),status:Z.nativeEnum(Me),startedAt:Z.coerce.date(),attempts:Z.number(),failureRecoveryDetails:Z.object({attempts:Z.number()}).optional()}),QU=uA.merge(zg),iae=uA.extend({finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)}),aae=QU.extend({finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)}),ZU=wR.merge(CR).extend({id:Z.string().uuid().optional(),startedAt:Z.coerce.date(),cliVersion:Z.string(),labels:Z.string().array().optional().default([])}),ld=ZU.extend({updatedAt:Z.coerce.date().optional().transform(t=>t??new Date),finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)});function dA(t){try{return eB(t)&&tB(t).isDirectory()}catch(e){return b.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as rB,input as nB}from"@inquirer/prompts";import{existsSync as oB,mkdirSync as iB,statSync as aB}from"fs";var Ni=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{dirname as sB}from"path";var lB=!1,mA=(()=>{try{return aB("/.dockerenv"),!0}catch{return!1}})();async function Bt(t){return Ni||lB||mA?!0:(await b.flush(),await new Promise(r=>setTimeout(r,100)),await rB({message:t}))}async function Gg(t){let e=sB(t);return dA(e)?oB(t)?Bt(`File '${pA(t)}' already exists. Overwrite existing content?`):!0:await Bt(`Directory '${pA(e)}' doesn't exist. Create it now?`)?(iB(e,{recursive:!0}),!0):!1}function pA(t){return t.replace(/(\s+)/g,"\\$1")}async function hA(t,e){return Ni||mA?e:(await nB({message:t,default:e})).trim()||e}import In,{supportsColor as EB}from"chalk";import{Console as gA}from"console";import{format as Ul}from"util";var jg=class extends Error{constructor(e,r,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,r),Error.stackTraceLimit=o}},cd=class t extends gA{_buffer=[];_groupDepth=0;Console=gA;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,r,n,o=2){let i=new jg(void 0,t.write).stack;if(!i)return e;let a=i.split(`
25
+ `)),console.log(" ",r(s))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=Dl[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Mn.reset,...e)}info(...e){this.logWithLevel(30,Mn.white,...e)}debug(...e){this.logWithLevel(20,Mn.dim,...e)}warn(...e){this.logWithLevel(40,Mn.yellow,...e)}error(...e){this.logWithLevel(50,Mn.red,...e)}success(...e){this.logWithLevel(1/0,Mn.green,...e)}dimmed(...e){this.logWithLevel(30,Mn.dim,...e)}underline(...e){this.logWithLevel(40,Mn.underline,...e)}bold(...e){this.logWithLevel(40,Mn.bold,...e)}grey(...e){this.logWithLevel(20,Mn.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},Cg=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},Vre=new Cg,fU=typeof window>"u"&&typeof process<"u"&&wg.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?wg.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,b=new Li(fU,{}),Pn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Pn,flush:async()=>{},bindings:()=>({})},nd={},od=({logger:t,logKey:e,maxCount:r,intervalMs:n},o,i,...a)=>{let s=nd[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},nd[e]=s),s.totalCount++,s.count<r&&(s.count++,t.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=nd[e];c?.totalCount!==c?.count&&t.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete nd[e]},n)};import{z as ee}from"zod";var SU=ee.array(Ka.extend({id:ee.string(),name:ee.string(),description:ee.string().optional(),labels:ee.string().array().optional()})),yU=ee.array(Ka.extend({id:ee.string(),name:ee.string(),description:ee.string().optional(),content:ug})),Xre=ee.object({name:ee.string(),description:ee.string().optional(),settings:ja.optional(),pathSegments:ee.string().array(),defaultEnv:ee.string().optional()}),Jre=ee.object({id:ee.string(),fileName:ee.string(),fullPath:ee.string(),relativeFilePath:ee.string().describe("relative to project root")}),Qre=Ev.extend({name:ee.string()}),Zre=ee.object({steps:Ga.array().optional(),settings:ja.optional(),labels:ee.array(ee.string()).optional()}),ene=ee.object({message:ee.literal("ok")}),tne=ee.object({name:eo.optional(),description:ee.string().min(1).optional(),settings:ja.optional(),disabled:ee.boolean().optional(),labels:ee.array(ee.string()).optional()}),rne=ee.object({message:ee.string(),newRelativeTestPath:ee.string().optional()}),nne=ee.object({tag:ee.string(),channel:ee.string(),filePath:ee.string()}),one=ee.object({name:eo}),ine=ee.object({tests:SU,modules:yU,labels:ee.string().array()}),ane=ee.object({name:ee.string(),description:ee.string(),enabled:ee.boolean()}).partial(),sne=ee.object({name:ee.string(),description:ee.string(),enabled:ee.boolean(),steps:Ga.array(),testFilePath:ee.string().describe("relative to the project root"),folderPath:ee.string().optional().describe("user selected folder path")}),lne=ee.object({packages:ee.string().array()});import{z as Tt}from"zod";var iR=Tt.object({id:Tt.string(),createdAt:Tt.coerce.date(),createdBy:Tt.string(),organizationId:Tt.string(),name:Tt.string(),description:Tt.string().nullish(),enabled:Tt.boolean(),schemaVersion:Tt.string().describe("Schema version for steps"),parameters:Tt.string().array().nullish().describe("Parameter list"),parameterEnums:Tt.record(Tt.string(),Tt.string().array()).nullish(),defaultParameters:Tt.record(Tt.string(),Tt.string()).nullish(),defaultCacheKey:Tt.string().nullish(),defaultCacheTtl:Tt.number().nullish(),defaultCacheAllInvocations:Tt.boolean().nullish(),autoAuth:Tt.boolean().nullish(),advanced:_h.nullish()}),Sne=iR.extend({steps:Tt.lazy(()=>Ze.array())}),aR=5*60*1e3,xg=fr.merge(iR.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as bne}from"date-fns-tz";import{z as We}from"zod";var _g=yl.extend({aiAction:We.boolean().optional(),stepLintSuggestions:We.boolean().optional(),agentConfig:We.record(We.string(),We.string()).optional(),aiFailureAnalysis:We.boolean().optional(),aiPageFiltering:We.boolean().optional().describe("rag v2 feature flag")}),EU=We.object({cliOnly:We.boolean().optional()}),Mg=We.object({fakerConstantSeed:We.boolean().optional()}),sR=We.object({ai:_g.optional(),githubAppInstallationId:We.number().nullish(),githubAppSummaryMessageEnabled:We.boolean().nullish(),githubReleaseAppInstallationId:We.number().nullish(),gitlabAppAccessToken:We.string().nullish(),gitlabAppBaseUrl:We.string().nullish(),qaseAccessToken:We.string().nullish(),testSuggestionsEnabled:We.boolean().nullish(),browser:Gh.optional(),internal:EU.optional(),advanced:Mg.optional()}),Cne=We.object({globalOverrides:We.record(We.string()).optional(),agentConfig:We.record(We.string(),We.string()).optional()}),xne=We.record(We.string(),We.string()).nullish();import*as A from"zod";import{z as yt}from"zod";var Pg=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Pg||{});var bU=yt.object({type:yt.literal("DESCRIPTION_UPDATE"),thoughts:yt.string()}),id=yt.discriminatedUnion("type",[bU]),TU=yt.object({testId:yt.string(),name:yt.string(),orgId:yt.string(),runId:yt.string(),steps:ft.array(),purpose:yt.nativeEnum(Pg),details:id.or(id.array()).optional()});var Ine=TU.pick({name:!0,orgId:!0}),vU=yt.object({id:yt.string(),name:yt.string().nullish(),createdAt:yt.string().pipe(yt.coerce.date()).or(yt.date()),organizationId:yt.string(),schemaVersion:yt.string(),runId:yt.string().nullish(),purpose:yt.nativeEnum(Pg),details:id.or(id.array()).optional(),applied:yt.boolean().nullish(),appliedAt:yt.coerce.date().nullish()}),lR=vU.extend({steps:ft.array()});var ad="x-momentic-cli-version",cR="x-momentic-client-mode",uR="x-momentic-cli-type",dR="x-momentic-logger-tags",RU="x-momentic-main-branch-name",AU="x-momentic-branch-name",wU="x-momentic-commit-timestamp",CU="x-momentic-last-commit-on-main",xU="x-momentic-last-commit-on-main-timestamp",_U="x-momentic-merged-branch-name",pR="x-momentic-session-id",Xne=A.object({error:A.boolean(),reason:A.string(),message:A.string()}),Jne=Ct.merge(Yh),mR=cu,Qne=Ct.merge(Yh);var Zne=Ct.merge(VT).extend({useConsensus:A.boolean().optional(),attemptNumber:A.number().optional()}),Ig=PE,eoe=Ct.merge(WT),hR=cT,toe=Ct.merge(qT),gR=uT,roe=Ct.merge(KT),fR=dT,noe=Ct.merge($T),SR=lT,ooe=Ct.merge(HT),yR=sT,ioe=Ct.merge(GT),ER=iT,aoe=Ct.merge(jT);var soe=Ct.merge(QT),loe=Ct.merge(ZT),coe=A.object({testPaths:A.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:A.string().optional(),all:A.boolean().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional(),testInputMatrix:A.record(A.string(),A.string()).array().optional()}),bR=A.object({queuedTests:A.unknown().array(),runIds:A.string().uuid().array(),runGroupId:A.string().optional()});var uoe=A.string().array(),doe=A.union([A.object({paths:A.string().array().describe("run specific test paths (e.g. todo-test)"),all:A.boolean().describe("run all tests").optional()}),A.object({path:A.string().describe("deprecated; present for backcompat")})]),TR=A.object({tests:A.record(A.string().describe("Test name"),A.string().describe("Test YAML")),modules:A.record(A.string().describe("Module name"),A.string().describe("Module YAML"))}),MU=A.object({test:A.string().describe("test YAML"),modules:A.record(A.string().describe("moduleId"),A.string().describe("module YAML"))}),poe=MU.array(),moe=A.object({testId:A.string(),schemaVersion:A.string()}).merge(Ti);function Og(t){let{gitMainBranch:e,gitBranchName:r,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=t,a={};return e&&(a[RU]=encodeURIComponent(e)),r&&(a[AU]=encodeURIComponent(r)),n&&(a[wU]=n.toISOString()),o&&(a[CU]=encodeURIComponent(o)),i&&(a[xU]=i.toISOString()),t.mergedGitBranchName&&(a[_U]=encodeURIComponent(t.mergedGitBranchName)),a}var hoe=A.object({entries:A.array(ob),testId:A.string()}),goe=A.object({entries:A.array(uv),testId:A.string()}),foe=A.object({testId:A.string()});function vR(t){return A.record(A.unknown()).transform(e=>{let r={};for(let[n,o]of Object.entries(e)){let i=t.safeParse(o);i.success&&(r[n]=i.data)}return r})}var RR=vR(ib),AR=vR(dv),wR=A.object({trigger:A.nativeEnum(zr),status:A.nativeEnum(Me),startedAt:A.coerce.date().optional(),gitCommitSha:A.string().optional(),gitCommitShaShort:A.string().optional(),gitCommitTimestamp:A.coerce.date().optional(),gitBranchName:A.string().optional(),gitOriginUrl:A.string().optional(),gitCommitMessage:A.string().optional(),gitCommitAuthorName:A.string().optional(),githubRepository:A.string().optional(),gitlabProjectPath:A.string().optional(),pipelineId:A.string().optional(),cliVersion:A.string().optional()}),Soe=A.object({id:A.string()}),CR=A.object({status:A.nativeEnum(Me),updatedAt:A.coerce.date().optional(),finishedAt:A.coerce.date().optional()}),xR=A.object({stepsSnapshot:A.array(A.record(A.unknown())).optional(),runGroupId:A.string().optional(),testId:A.string(),testName:A.string(),resolvedBaseUrl:A.string().optional(),environmentName:A.string().optional(),labels:A.array(A.string()).optional(),cliVersion:A.string().optional(),trigger:A.nativeEnum(zr),schemaVersion:A.string().optional(),section:A.nativeEnum(Fu).optional(),resolvedInputs:A.record(A.string(),A.string()).optional(),quarantined:A.boolean().optional().default(!1),quarantinedReason:A.string().optional()}),yoe=A.object({id:A.string()}),PU=qh.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),_R=PU.array(),MR=qh.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),Eoe=A.object({id:A.string()}),PR=A.object({status:A.nativeEnum(Me),finishedAt:A.coerce.date().optional(),schemaVersion:A.string().optional().default("1.0.19"),results:A.record(A.string(),A.unknown()).array().optional(),beforeResults:A.record(A.string(),A.unknown()).array().optional(),afterResults:A.record(A.string(),A.unknown()).array().optional()}),boe=A.object({screenshot:A.string()}),IR=A.object({key:A.string()}),OR=A.object({orgId:A.string(),userId:A.string()}),LR=A.array(AT),Toe=A.record(A.string(),A.union([A.string(),A.boolean()])),voe=A.object({paths:A.string().array(),env:A.string().optional(),urlOverride:A.string().optional(),customHeaders:A.record(A.string(),A.string()).optional()}),NR=A.object({suiteRunIds:A.string().array(),runGroupIds:A.string().array()}),Roe=A.object({suiteRunIds:A.string().array()}),Aoe=FT.array(),woe=A.object({runGroupIds:A.string().array()}),IU=A.object({uploadUrl:A.string()}),Coe=Ct.merge(YT),xoe=Ct.merge(JT),_oe=Ct.merge(XT),OU=A.object({testId:A.string().optional().default(""),testName:A.string().optional().default(""),suiteId:A.string().optional().default(""),suiteName:A.string().optional().default(""),creditsUsed:A.number().optional()}),LU=A.object({transactionId:A.string(),timestamp:A.string(),event:A.nativeEnum(Pl),properties:OU}),Moe=LU.array(),DR=lR.omit({steps:!0}).extend({steps:A.array(A.record(A.string(),A.unknown())).describe("unparsed ResolvedStep[]")}),Poe=A.object({limit:A.number().max(10).optional(),afterTime:A.number().optional()}),kR=OT.array(),Ioe=A.object({applied:A.boolean().optional(),appliedAt:A.coerce.date().optional()}),FR=IU.extend({id:A.string()}),Ooe=A.object({runGroupId:A.string().uuid().optional()}),UR=A.object({runGroupId:A.string().uuid()}),BR=A.object({quarantined:A.object({testId:A.string().uuid(),quarantinedAt:A.coerce.date(),quarantinedBy:A.string().optional(),quarantinedReason:A.string()}).array()}),Loe=A.object({testId:A.string().uuid(),testName:A.string().optional(),reason:A.string(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),Noe=A.object({testName:A.string().optional(),reason:A.string().optional(),gitLocalUsername:A.string().optional(),gitLocalEmail:A.string().optional(),gitLocalName:A.string().optional()}),Doe=Ct.merge(Rv),koe=Ct.merge(Av),Foe=Ct.merge(wv),Uoe=A.object({apkToInstall:A.object({channel:A.string(),tag:A.string().optional()}).optional(),hostname:A.string().optional(),region:A.nativeEnum(vl).optional(),osVersion:A.nativeEnum(Rl).optional(),sessionId:A.string().optional()}),zR=A.object({name:A.string(),webRtcUrl:A.string(),adbUrl:A.string(),token:A.string(),apkDownloadUrl:A.string().optional(),playwrightServerUrl:A.string().optional(),region:A.string().optional()}),Boe=A.object({hostname:A.string().optional(),region:A.nativeEnum(vl).optional(),osVersion:A.nativeEnum(ag).optional(),sessionId:A.string().optional()}),HR=A.object({id:A.string(),apiUrl:A.string(),webRtcUrl:A.string(),wdaUrl:A.string(),token:A.string(),region:A.string().optional()}),zoe=A.object({channel:A.string(),tag:A.string(),md5:A.string()}),GR=A.object({id:A.string(),uploadUrl:A.string().optional(),downloadUrl:A.string(),md5:A.string().optional()}),jR=A.object({assets:A.array(A.object({channel:A.string(),tag:A.string(),md5:A.string(),createdAt:A.number().describe("Unix timestamp in milliseconds")}))});import{z as ae}from"zod";var VR=7,NU=3,joe=ae.object({localTestId:ae.string(),quarantinedAt:ae.date(),quarantinedBy:ae.string().optional(),quarantinedReason:ae.string(),quarantinedByGitEmail:ae.string().optional(),quarantinedByGitName:ae.string().optional(),quarantinedByGitUsername:ae.string().optional()}).or(ae.object({cloudTestId:ae.string(),quarantinedAt:ae.date(),quarantinedBy:ae.string().optional(),quarantinedReason:ae.string(),quarantinedByGitEmail:ae.string().optional(),quarantinedByGitName:ae.string().optional(),quarantinedByGitUsername:ae.string().optional()})),$R=(r=>(r.QUARANTINE="QUARANTINE",r.UNQUARANTINE="UNQUARANTINE",r))($R||{});var Lg=ae.object({name:ae.string(),description:ae.string().nullish(),effect:ae.nativeEnum($R),labels:ae.array(ae.string()).nullish(),githubRepository:ae.string().nullish(),gitlabProjectPath:ae.string().nullish(),gitBranchName:ae.string().nullish(),slackNotificationChannel:ae.string().nullish()}),DU=ae.object({type:ae.literal("LAST_N_RUNS"),lastN:ae.number().min(NU)}),kU=ae.object({type:ae.literal("LAST_N_HOURS"),lastN:ae.number().min(1).max(VR*24)}),FU=ae.object({type:ae.literal("LAST_N_DAYS"),lastN:ae.number().min(1).max(VR)}),Ng=ae.discriminatedUnion("type",[DU,kU,FU]),UU=ae.object({flakeRateThreshold:ae.number().min(1).max(100),evaluationWindow:Ng}),BU=Lg.extend({type:ae.literal("FLAKE_RATE"),config:UU}),zU=ae.object({passRateThreshold:ae.number().min(1).max(100),evaluationWindow:Ng}),HU=Lg.extend({type:ae.literal("PASS_RATE"),config:zU}),GU=ae.object({failureCountThreshold:ae.number().min(0),evaluationWindow:Ng}),jU=Lg.extend({type:ae.literal("FAILURE_COUNT"),config:GU}),Voe=ae.discriminatedUnion("type",[BU,HU,jU]);import{z as vt}from"zod";var qoe=vt.object({repositoriesIndexed:vt.boolean(),indexingInProgress:vt.boolean(),indexesOutdated:vt.boolean()}),WR=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(WR||{}),qR=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(qR||{}),Koe=vt.object({name:vt.string(),status:vt.nativeEnum(WR),conclusion:vt.nativeEnum(qR).nullable()}),kl=vt.object({sha:vt.string(),message:vt.string(),author:vt.object({name:vt.string().optional(),email:vt.string().optional(),date:vt.coerce.date().optional()}),committer:vt.object({name:vt.string().optional(),email:vt.string().optional(),date:vt.coerce.date().optional()})}),Dg=vt.object({mergedBranch:vt.string().optional()});import{z as ut}from"zod";var KR=ut.object({orgId:ut.string(),cacheKeys:ut.string().array()}),Joe=ut.object({keyParams:KR,clientMetadata:ut.string(),lockAcquisitionTimeoutMs:ut.number().optional()}),YR=ut.object({acquired:ut.boolean(),acquiredByMetadata:ut.string(),keyPrefix:ut.string()}),Qoe=ut.object({keyPrefix:ut.string(),result:ut.string(),ttlMs:ut.number()}),Zoe=ut.union([ut.object({keyPrefix:ut.string()}),KR]),VU=ut.object({remainingTtlMs:ut.number(),value:ut.string().nullish()}),eie=ut.object({results:ut.record(ut.string(),VU),activeLocks:ut.string().array()}),XR=0,JR=5*60*1e3;var oie=90*24*60*60*1e3,iie=7*24*60*60*1e3;import{z as QR}from"zod";var lie=QR.object({quarantineNotifications:QR.string().nullish()});import{z as Ut}from"zod";var $U=Ut.object({version:Ut.string(),json:Ut.record(Ut.unknown()),hash:Ut.string()}),ZR=Ut.record(Ut.unknown()),pie=Ut.object({newSvgs:Ut.array($U),metadata:ZR.optional()}),WU=Ut.object({version:Ut.string(),json:Ut.record(Ut.unknown()).nullish(),hash:Ut.string(),description:Ut.string().nullish(),metadata:ZR.nullish()}),eA=Ut.record(Ut.string().describe("icon hash"),WU);import{z as ht}from"zod";var kg=ht.object({assertion:ht.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),qU=ht.object({instruction:ht.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:kg.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),tA=qU.extend({subSteps:ht.lazy(()=>tA.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),rA=ht.object({name:ht.string().describe("Short name describing the test plan"),description:ht.string().nullish().transform(t=>t??void 0).describe("Longer form description of the high level goal of the test plan")}),nA=rA.extend({id:ht.string(),createdAt:ht.coerce.date(),updatedAt:ht.coerce.date(),updatedBy:ht.string(),createdBy:ht.string(),test:ht.object({id:ht.string(),name:ht.string()}).nullish().transform(t=>t??void 0)}),fie=nA.extend({testGenRuns:ht.tuple([]).or(ht.tuple([ht.object({id:ht.string(),startedAt:ht.coerce.date(),status:ht.nativeEnum(Me)})]))}),oA=ht.object({preConditions:kg.array().nullish().transform(t=>t??[]),postConditions:kg.array().nullish().transform(t=>t??[]),steps:tA.array().nullish().transform(t=>t??[])}),Sie=nA.extend({plan:oA.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),KU=rA.extend({plan:oA.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),yie=KU.array().nullish().transform(t=>t??[]);import{validator as YU}from"@exodus/schemasafe";function iA(t){let e;try{e=JSON.parse(t)}catch(r){return`The schema is not valid JSON. ${r}`}try{YU(e)}catch(r){return`The schema is not a valid JSON schema. ${r}`}}var aA=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,r])=>e.trim()&&r.trim())))};import{z as Die}from"zod";var sd=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};var Ug="browser-crash-dump.zip",Fg=class{loggerBindings;getParentStepIdChain(){return[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}recordStepDuration(){}async finish(){}async startSubSteps(){return new Fl}},Fl=class{getParentStepIdChain(){return[]}async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new Fg}};import{z as Bg}from"zod";var $ie=Bg.object({parentStepIdChain:Bg.array(Bg.string()),result:cn});import{z as Z}from"zod";var ur="assets",XU=Z.object({step:ft,status:Z.nativeEnum(Fe),startedAt:Z.coerce.date(),finishedAt:Z.coerce.date().optional(),healMetadata:Z.object({healType:Z.nativeEnum(gl).or(Z.literal("AI")),healedAt:Z.coerce.date()}).optional(),beforeSnapshotId:Z.string().uuid().optional(),afterSnapshotId:Z.string().uuid().optional(),message:Z.string().optional()}),JU=XU.extend({finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)}),eae=JU.extend({step:Z.unknown()}),zg=Z.object({avdId:Z.string().optional(),channel:Z.string().optional(),tag:Z.string().optional()}),sA="1.0.0",Hg=PR.extend({id:Z.string().uuid().optional(),startedAt:Z.coerce.date(),runAttemptSchemaVersion:Z.string().optional(),schemaVersion:Z.string().optional().default("1.0.19"),results:Z.record(Z.string(),Z.unknown()).array().optional(),beforeResults:Z.record(Z.string(),Z.unknown()).array().optional(),afterResults:Z.record(Z.string(),Z.unknown()).array().optional(),assetDetails:zg.optional(),activeVideos:Z.array(Z.object({videoName:Z.string(),timestamp:Z.coerce.date()})).optional()}),lA=Hg.extend({assetDetails:zg.optional(),finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)}),tae=Hg.merge(Sl),rae=lA.merge(Sl),cA=Z.object({results:Z.array(cn),beforeResults:Z.array(cn).optional(),afterResults:Z.array(cn).optional()}),nae=Hg.merge(cA),oae=lA.merge(cA),uA=MR.merge(xR).extend({executionType:Z.nativeEnum(ka).optional().default("WEB"),testId:Z.string().uuid(),testDescription:Z.string().optional(),runGroupId:Z.string().uuid(),status:Z.nativeEnum(Me),startedAt:Z.coerce.date(),attempts:Z.number(),failureRecoveryDetails:Z.object({attempts:Z.number()}).optional()}),QU=uA.merge(zg),iae=uA.extend({finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)}),aae=QU.extend({finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)}),ZU=wR.merge(CR).extend({id:Z.string().uuid().optional(),startedAt:Z.coerce.date(),cliVersion:Z.string(),labels:Z.string().array().optional().default([])}),ld=ZU.extend({updatedAt:Z.coerce.date().optional().transform(t=>t??new Date),finishedAt:Z.coerce.date().optional().transform(t=>t??new Date)});function dA(t){try{return eB(t)&&tB(t).isDirectory()}catch(e){return b.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as rB,input as nB}from"@inquirer/prompts";import{existsSync as oB,mkdirSync as iB,statSync as aB}from"fs";var Ni=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{dirname as sB}from"path";var lB=!1,mA=(()=>{try{return aB("/.dockerenv"),!0}catch{return!1}})();async function Bt(t){return Ni||lB||mA?!0:(await b.flush(),await new Promise(r=>setTimeout(r,100)),await rB({message:t}))}async function Gg(t){let e=sB(t);return dA(e)?oB(t)?Bt(`File '${pA(t)}' already exists. Overwrite existing content?`):!0:await Bt(`Directory '${pA(e)}' doesn't exist. Create it now?`)?(iB(e,{recursive:!0}),!0):!1}function pA(t){return t.replace(/(\s+)/g,"\\$1")}async function hA(t,e){return Ni||mA?e:(await nB({message:t,default:e})).trim()||e}import In,{supportsColor as EB}from"chalk";import{Console as gA}from"console";import{format as Ul}from"util";var jg=class extends Error{constructor(e,r,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,r),Error.stackTraceLimit=o}},cd=class t extends gA{_buffer=[];_groupDepth=0;Console=gA;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,r,n,o=2){let i=new jg(void 0,t.write).stack;if(!i)return e;let a=i.split(`
26
26
  `).slice(o).filter(Boolean).join(`
27
27
  `);return e.push({message:n,origin:a,type:r}),e}_log(e,r){t.write(this._buffer,e," ".repeat(this._groupDepth)+r,3)}debug(e,...r){this._log("debug",Ul(e,...r))}error(e,...r){this._log("error",Ul(e,...r))}info(e,...r){this._log("info",Ul(e,...r))}log(e,...r){this._log("log",Ul(e,...r))}warn(e,...r){this._log("warn",Ul(e,...r))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function fA(t){let e=globalThis.console,r=new cd;globalThis.console=r;try{t()}finally{let o=r.getBuffer()?.map(i=>i.message).join(`
28
28
  `);process.stderr.write(`${o}
29
29
  `),globalThis.console=e}}var dt=" ".repeat(6);function SA(t,e="",r=!1){let n=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(n-e.length,20),i=t.split(`
30
30
  `),a=[];for(let s of i)if(r){let c=s;for(;c.length>o;){let u=c.slice(0,o+1).lastIndexOf(" "),d=u>-1?u:o;a.push(e+c.slice(0,d)),c=c.slice(d).trimStart()}a.push(e+c)}else{let c=s.split(" "),l="";for(let u of c){if(!l.length){l=u;continue}let d=`${l} ${u}`;d.length<=o?l=d:(a.push(e+l),l=u)}a.push(e+l)}return a.join(`
31
- `)}import cB from"fetch-retry";import uB from"os";import yA,{multistream as dB}from"pino";import pB from"pino-pretty";import mB from"pino-std-serializers";var Ya=new Map,hB=!0,EA="Log throttle exceeded",gB=100,fB=5e3,SB=cB(global.fetch,{retries:2,retryOn:function(t,e,r){return!!(e!==null||r&&r.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),Vg=class t{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:r,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=r??uB.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=hB?yA(a):yA(a,dB([{stream:pB({colorize:!0})}]))}child(e){return new t({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let r=await SB(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Oi(e),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Got error status (${r.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===EA)return!0;let r=Date.now();return r-this.lastWindowStart>fB&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,EA),this.droppedLogsInWindow=!1,this.lastWindowStart=r),this.logsInCurrentWindow<gB?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,r,n,...o){try{this.logHelper(e,r,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,r,n,...o){if(Dl[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof r=="string"&&!n&&(r={message:r}),typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&(r.err=mB.err(r.err));let i={...this.bindingAttributes,...r&&typeof r=="object"?r:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:nR({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let r=this.bindingAttributes.app;this.bindingAttributes.app=e,Ya.set("app",this),Ya.delete(r)}debug(e,r,...n){this.log("debug",e,r,...n)}info(e,r,...n){this.log("info",e,r,...n)}warn(e,r,...n){this.log("warn",e,r,...n)}error(e,r,...n){this.log("error",e,r,...n)}bindings(){return this.bindingAttributes}addBinding(e,r){this.bindingAttributes[e]=r}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=oR[e]):(this.minLevelValue=Dl[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Xa=({app:t,hostname:e,disableConsoleLogs:r})=>(Ya.has(t)||Ya.set(t,new Vg({bindings:{app:t},hostname:e,disableConsoleLogs:r})),Ya.get(t));async function TA(){await Promise.all([...Ya.values()].map(t=>t.flush()))}import{hostname as yB}from"os";var X=Xa({app:"cli",hostname:yB(),disableConsoleLogs:!0}).child({cliVersion:"2.29.4"});var bB=5;async function dd({getResults:t,checkDone:e,name:r,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>bB&&(b.error(`Failed to fetch ${r} status too many times.`),process.exit(1));try{a=await t(),i=0}catch(l){i++,X.warn({err:l},"Failed to fetch run status, retrying..."),b.warn({err:l},"Failed to fetch run status, retrying..."),await new Promise(u=>setTimeout(u,1500*i));continue}if(e(a))return a;let c=Math.max(1e4,Math.floor(n/100));await new Promise(l=>setTimeout(l,c))}b.error(`Timeout elapsed waiting for ${r} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function Ja({results:t,startTime:e,entity:r,getDisplayLine:n,onFailed:o}){let i=t.filter(u=>u.status==="PASSED"&&u.quarantined),a=t.filter(u=>u.status==="PASSED"&&!u.quarantined),s=t.filter(u=>u.status==="FAILED"&&u.quarantined),c=t.filter(u=>u.status==="FAILED"&&!u.quarantined),l=t.filter(u=>u.status==="CANCELLED");return fA(()=>{if(c.forEach(u=>{b.log(""),o(u)}),c.length){b.log("");let u=c.length===1?"":"s";b.error(`${c.length} ${r}${u} failed:`),c.forEach(d=>{b.dimmed(n(d))})}if(l.length){b.log("");let u=l.length===1?"":"s";b.warn(`${l.length} ${r}${u} cancelled:`),l.forEach(d=>{b.dimmed(n(d))})}if(a.length){b.log("");let u=a.length===1?"":"s";b.success(`${a.length} ${r}${u} passed:`),a.forEach(d=>{b.dimmed(n(d))})}if(s.length){b.log("");let u=s.length===1?"":"s";b.warn(`${s.length} quarantined ${r}${u} failed:`),s.forEach(d=>{b.dimmed(n(d))})}if(i.length){b.log("");let u=i.length===1?"":"s";b.warn(`${i.length} quarantined ${r}${u} passed:`),i.forEach(d=>{b.dimmed(n(d))})}b.log(""),b.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var pd=(t,e)=>{if(!t.failureDetails||!t.failureReason)return;let r=Su[t.failureDetails?.classification?.reason||t.failureReason],n=t.failureDetails?.classification?.summary||Pa[t.failureReason],o=t.failureDetails.classification?.rootCause;if(b.error(e),o){b.log(`${dt}- Error type: ${In.dim(r)}`);let i="- Root cause analysis:",a=SA(`${i} ${o}`,`${dt} `,!1),s=a.indexOf(":");b.log(`${dt}${i} ${In.dim(a.slice(s+1))}`)}else b.log(`${dt}Reason: ${In.red(r)}`),b.log(`${dt}Description: ${In.red(n)}`)},Bl=({status:t,testLogRef:e,getRunningTestsCount:r,getTotalTestsCount:n,additionalText:o})=>{t=t.toUpperCase();let i=t,a;t.includes("FAIL")?(i=In.bgRed.white("FAIL"),a=3):t.includes("PASS")?(i=In.bgGreen.white("PASS"),a=3):t.includes("START")?(i=In.bgBlue.white("START"),a=2):t.includes("CANCEL")?(i=In.bgRgb(191,68,11).white("CANCEL"),a=1):t.includes("RETRY")?(i=In.bgRgb(191,68,11).white("RETRY"),a=2):t.includes("RUN")||t.includes("PROG")?(i=In.bgMagenta.white("RUNNING"),a=0):(b.warn(`Unknown status tried to be logged in run test locally: ${t}`),a=0),EB||(i=`${i}`),b.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${r()}/${n()})`)};import TB from"fs";import{tmpdir as vB}from"os";import RB from"path";import{registry as zl}from"playwright-core/lib/server";import vA from"proper-lockfile";var RA=RB.join(vB(),"momenticBrowserInstallation");var $g=["chrome","chromium","chrome-for-testing","ffmpeg"],AB={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},AA={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function wA(t){if(t==="Org Default")return!1;let e=AA[AB[t]??""]??"",r=zl.findExecutable(e);return!r||r.installType==="none"?!1:Wg(r)}function Wg(t){let e=t.executablePath();return TB.existsSync(e)}function wB(t,e){let r=AA[t];if(!r)throw new Error(`Requested install of unknown browser type ${t}`);let n=zl.findExecutable(r);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${t}`);if(!(!e&&Wg(n)))return n}async function CB({browser:t,force:e}){let r=wB(t,e);if(!r){b.info(`Browser '${t}' is already installed, skipping...`);return}b.info(`Installing browser '${t}'...`);try{await zl.installDeps([r],!1),await zl.install([r],!1)}catch(n){if(n.message.includes("Lock file is already being held")){b.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=zl.findExecutable(t),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Wg(o);)b.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function CA({rawBrowsers:t,force:e=!1,all:r=!1}){let n=r?$g:Array.from(new Set(t));try{await vA.lock(RA,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){b.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await CB({browser:i,force:e})}catch(a){o=a,b.error(`Failed to install the ${i} browser: ${a}`)}}finally{await vA.unlock(RA,{realpath:!1})}if(o)throw o}import xB from"blocked-at";import _B from"why-is-node-running";function xA(t){MB(t),PB()}function MB(t){xB((e,r)=>{console.warn(`Detected the NodeJS event loop was blocked for ${e.toFixed(0)}ms. This can cause the CLI to hang.`);let n=r.join(`
32
- `);console.warn(n),t.warn({stack:n,time:e},"NodeJS event loop blocked")},{threshold:1e3,trimFalsePositives:!0})}function PB(){process.on("SIGINT",()=>{if("_getActiveHandles"in process){let t=process._getActiveHandles();console.log("Active handles:",t.map(e=>e.constructor?.name))}_B(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}function _A(t){let e=t?.shardIndex??1,r=t?.shardCount??1;if(e<1)throw new Error("Shard index must be greater than 0.");if(r<1)throw new Error("Shard count must be greater than 0.");if(e>r)throw new Error("Shard index cannot be greater than shard count")}function IB(t,e,r,n){if(r>t.length&&(b.warn(`Shard count ${r} is greater than the number of tests ${t.length}! Some workers won't have any tests to run.`),r=Math.max(r,t.length),e>r))return[];let o=Math.floor((e-1)*(t.length/r)),i=Math.floor(e*(t.length/r));return(n?[...t].sort((s,c)=>n(s).localeCompare(n(c))):[...t].sort()).filter((s,c)=>c>=o&&c<i)}function MA(t){let{items:e,shardIndex:r,shardCount:n,sortKey:o}=t;return n>1?IB(e,r,n,o):e}import{randomUUID as p5}from"crypto";import yL from"body-parser";import eY from"cors";import tY from"dedent";import{Router as Nz}from"express";import dr from"fs";import{globSync as Dz}from"glob";import Dt from"path";import Ud from"fs";import{z as zB}from"zod";var z="v1",qg="cli",Di="2.29.4";var Bo=3.1783027;function OB(t){let e=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Pe(t){return Math.ceil(Kg(t)/Bo)}function Kg(t){let e=0;if(typeof t=="string"){let r=t;r=r.replaceAll(`
31
+ `)}import cB from"fetch-retry";import uB from"os";import yA,{multistream as dB}from"pino";import pB from"pino-pretty";import mB from"pino-std-serializers";var Ya=new Map,hB=!0,EA="Log throttle exceeded",gB=100,fB=5e3,SB=cB(global.fetch,{retries:2,retryOn:function(t,e,r){return!!(e!==null||r&&r.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),Vg=class t{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:r,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=r??uB.hostname(),this.disableConsoleLogs=n,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=hB?yA(a):yA(a,dB([{stream:pB({colorize:!0})}]))}child(e){return new t({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let r=await SB(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Oi(e),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Got error status (${r.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===EA)return!0;let r=Date.now();return r-this.lastWindowStart>fB&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,EA),this.droppedLogsInWindow=!1,this.lastWindowStart=r),this.logsInCurrentWindow<gB?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,r,n,...o){try{this.logHelper(e,r,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,r,n,...o){if(Dl[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof r=="string"&&!n&&(r={message:r}),typeof r=="object"&&r&&"err"in r&&r.err instanceof Error&&(r.err=mB.err(r.err));let i={...this.bindingAttributes,...r&&typeof r=="object"?r:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:nR({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let r=this.bindingAttributes.app;this.bindingAttributes.app=e,Ya.set("app",this),Ya.delete(r)}debug(e,r,...n){this.log("debug",e,r,...n)}info(e,r,...n){this.log("info",e,r,...n)}warn(e,r,...n){this.log("warn",e,r,...n)}error(e,r,...n){this.log("error",e,r,...n)}bindings(){return this.bindingAttributes}addBinding(e,r){this.bindingAttributes[e]=r}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=oR[e]):(this.minLevelValue=Dl[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Xa=({app:t,hostname:e,disableConsoleLogs:r})=>(Ya.has(t)||Ya.set(t,new Vg({bindings:{app:t},hostname:e,disableConsoleLogs:r})),Ya.get(t));async function TA(){await Promise.all([...Ya.values()].map(t=>t.flush()))}import{hostname as yB}from"os";var X=Xa({app:"cli",hostname:yB(),disableConsoleLogs:!0}).child({cliVersion:"2.29.5"});var bB=5;async function dd({getResults:t,checkDone:e,name:r,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>bB&&(b.error(`Failed to fetch ${r} status too many times.`),process.exit(1));try{a=await t(),i=0}catch(l){i++,X.warn({err:l},"Failed to fetch run status, retrying..."),b.warn({err:l},"Failed to fetch run status, retrying..."),await new Promise(u=>setTimeout(u,1500*i));continue}if(e(a))return a;let c=Math.max(1e4,Math.floor(n/100));await new Promise(l=>setTimeout(l,c))}b.error(`Timeout elapsed waiting for ${r} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function Ja({results:t,startTime:e,entity:r,getDisplayLine:n,onFailed:o}){let i=t.filter(u=>u.status==="PASSED"&&u.quarantined),a=t.filter(u=>u.status==="PASSED"&&!u.quarantined),s=t.filter(u=>u.status==="FAILED"&&u.quarantined),c=t.filter(u=>u.status==="FAILED"&&!u.quarantined),l=t.filter(u=>u.status==="CANCELLED");return fA(()=>{if(c.forEach(u=>{b.log(""),o(u)}),c.length){b.log("");let u=c.length===1?"":"s";b.error(`${c.length} ${r}${u} failed:`),c.forEach(d=>{b.dimmed(n(d))})}if(l.length){b.log("");let u=l.length===1?"":"s";b.warn(`${l.length} ${r}${u} cancelled:`),l.forEach(d=>{b.dimmed(n(d))})}if(a.length){b.log("");let u=a.length===1?"":"s";b.success(`${a.length} ${r}${u} passed:`),a.forEach(d=>{b.dimmed(n(d))})}if(s.length){b.log("");let u=s.length===1?"":"s";b.warn(`${s.length} quarantined ${r}${u} failed:`),s.forEach(d=>{b.dimmed(n(d))})}if(i.length){b.log("");let u=i.length===1?"":"s";b.warn(`${i.length} quarantined ${r}${u} passed:`),i.forEach(d=>{b.dimmed(n(d))})}b.log(""),b.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var pd=(t,e)=>{if(!t.failureDetails||!t.failureReason)return;let r=Su[t.failureDetails?.classification?.reason||t.failureReason],n=t.failureDetails?.classification?.summary||Pa[t.failureReason],o=t.failureDetails.classification?.rootCause;if(b.error(e),o){b.log(`${dt}- Error type: ${In.dim(r)}`);let i="- Root cause analysis:",a=SA(`${i} ${o}`,`${dt} `,!1),s=a.indexOf(":");b.log(`${dt}${i} ${In.dim(a.slice(s+1))}`)}else b.log(`${dt}Reason: ${In.red(r)}`),b.log(`${dt}Description: ${In.red(n)}`)},Bl=({status:t,testLogRef:e,getRunningTestsCount:r,getTotalTestsCount:n,additionalText:o})=>{t=t.toUpperCase();let i=t,a;t.includes("FAIL")?(i=In.bgRed.white("FAIL"),a=3):t.includes("PASS")?(i=In.bgGreen.white("PASS"),a=3):t.includes("START")?(i=In.bgBlue.white("START"),a=2):t.includes("CANCEL")?(i=In.bgRgb(191,68,11).white("CANCEL"),a=1):t.includes("RETRY")?(i=In.bgRgb(191,68,11).white("RETRY"),a=2):t.includes("RUN")||t.includes("PROG")?(i=In.bgMagenta.white("RUNNING"),a=0):(b.warn(`Unknown status tried to be logged in run test locally: ${t}`),a=0),EB||(i=`${i}`),b.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${r()}/${n()})`)};import TB from"fs";import{tmpdir as vB}from"os";import RB from"path";import{registry as zl}from"playwright-core/lib/server";import vA from"proper-lockfile";var RA=RB.join(vB(),"momenticBrowserInstallation");var $g=["chrome","chromium","chrome-for-testing","ffmpeg"],AB={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},AA={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function wA(t){if(t==="Org Default")return!1;let e=AA[AB[t]??""]??"",r=zl.findExecutable(e);return!r||r.installType==="none"?!1:Wg(r)}function Wg(t){let e=t.executablePath();return TB.existsSync(e)}function wB(t,e){let r=AA[t];if(!r)throw new Error(`Requested install of unknown browser type ${t}`);let n=zl.findExecutable(r);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${t}`);if(!(!e&&Wg(n)))return n}async function CB({browser:t,force:e}){let r=wB(t,e);if(!r){b.info(`Browser '${t}' is already installed, skipping...`);return}b.info(`Installing browser '${t}'...`);try{await zl.installDeps([r],!1),await zl.install([r],!1)}catch(n){if(n.message.includes("Lock file is already being held")){b.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=zl.findExecutable(t),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Wg(o);)b.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function CA({rawBrowsers:t,force:e=!1,all:r=!1}){let n=r?$g:Array.from(new Set(t));try{await vA.lock(RA,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){b.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of n)try{await CB({browser:i,force:e})}catch(a){o=a,b.error(`Failed to install the ${i} browser: ${a}`)}}finally{await vA.unlock(RA,{realpath:!1})}if(o)throw o}import xB from"blocked-at";import _B from"why-is-node-running";function xA(t){MB(t),PB()}function MB(t){xB((e,r)=>{console.warn(`Detected the NodeJS event loop was blocked for ${e.toFixed(0)}ms. This can cause the CLI to hang.`);let n=r.join(`
32
+ `);console.warn(n),t.warn({stack:n,time:e},"NodeJS event loop blocked")},{threshold:1e3,trimFalsePositives:!0})}function PB(){process.on("SIGINT",()=>{if("_getActiveHandles"in process){let t=process._getActiveHandles();console.log("Active handles:",t.map(e=>e.constructor?.name))}_B(),setImmediate(()=>{setTimeout(()=>{process.exit(1)},2e3).unref()})})}function _A(t){let e=t?.shardIndex??1,r=t?.shardCount??1;if(e<1)throw new Error("Shard index must be greater than 0.");if(r<1)throw new Error("Shard count must be greater than 0.");if(e>r)throw new Error("Shard index cannot be greater than shard count")}function IB(t,e,r,n){if(r>t.length&&(b.warn(`Shard count ${r} is greater than the number of tests ${t.length}! Some workers won't have any tests to run.`),r=Math.max(r,t.length),e>r))return[];let o=Math.floor((e-1)*(t.length/r)),i=Math.floor(e*(t.length/r));return(n?[...t].sort((s,c)=>n(s).localeCompare(n(c))):[...t].sort()).filter((s,c)=>c>=o&&c<i)}function MA(t){let{items:e,shardIndex:r,shardCount:n,sortKey:o}=t;return n>1?IB(e,r,n,o):e}import{randomUUID as p5}from"crypto";import yL from"body-parser";import eY from"cors";import tY from"dedent";import{Router as Nz}from"express";import dr from"fs";import{globSync as Dz}from"glob";import Dt from"path";import Ud from"fs";import{z as zB}from"zod";var z="v1",qg="cli",Di="2.29.5";var Bo=3.1783027;function OB(t){let e=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Pe(t){return Math.ceil(Kg(t)/Bo)}function Kg(t){let e=0;if(typeof t=="string"){let r=t;r=r.replaceAll(`
33
33
  `,""),r=r.replaceAll(" ","");let n=OB(r);return r.length-n+Bo*n}if(typeof t>"u"||t===null)return 0;if(typeof t=="number")return String(t).length;if(Array.isArray(t))return t.forEach(r=>{e+=Kg(r)}),e;if(typeof t=="object"){let r=t;return r.type==="image"||r.type==="media"&&"data"in r&&"mediaType"in r&&typeof r.mediaType=="string"&&r.mediaType.includes("jpeg")?1600:(Object.keys(r).forEach(n=>{e+=String(n).length,n==="image_url"?(r[n]??{}).detail==="high"?e+=1105*Bo:e+=85*Bo:n==="source"&&typeof r[n]=="object"&&r[n]?.type==="base64"?e+=1600*Bo:e+=Kg(r[n])}),e)}if(typeof t=="boolean")return t?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof t}': ${t}`)}var zo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var PA=t=>{let e=t.reason===void 0?new DOMException("This operation was aborted.","AbortError"):t.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function $(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:p}=e;if(p.aborted)return c(PA(p));l=()=>c(PA(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof t.cancel=="function"&&Promise.resolve().then(()=>t.cancel()).catch(()=>{});let p=o instanceof Error?o:new zo(o??`Promise timed out after ${r}ms`);c(p)}};r<1/0&&(a=i.setTimeout(u,r));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(t).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}var md=class{limit;windowMs;userActions;constructor(e,r){this.limit=e,this.windowMs=r,this.userActions=new Map}_cleanup(e,r="DEFAULT_USER"){let n=Date.now(),o=`${r}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>n-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,r="DEFAULT_USER"){let n=Date.now(),o=`${r}:${e}`;this._cleanup(r,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};var LB=9e4,NB=3,DB=1500,kB=15e3,un=class extends Error{status;rawError;constructor(e,r,n,o={}){super(n,o),this.status=e,this.rawError=r}};async function FB(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Yg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Di&&(e[ad]=Di),qg&&(e[uR]=qg),e}async sendRequest(e,r){let{retries:n=NB,requestTimeoutMs:o=LB,initialRetryDelayMs:i=DB,maxRetryDelayMs:a=kB,onFailedRequest:s}=r,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:r.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,r,o)}catch(p){u=p;try{s?.(u)}catch{}if(p instanceof un&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new zo),c===0)throw u;let m=l-c,g=Math.min(i*Math.pow(2,m-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,r,n){let o={path:e,baseUrl:this.baseUrl,method:r.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();r.signal&&r.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...r.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:r.method,body:r.body?JSON.stringify(r.body):void 0,headers:l,signal:i.signal});if(!u.ok){let p=await FB(u);throw new un(u.status,p,`Request to ${r.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&r.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),r.signal&&r.signal.removeEventListener("abort",s)}}},zt=class extends Yg{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[cR]:this.mode??""}}};import{createAnthropic as UB}from"@ai-sdk/anthropic";function BB(t){let{apiKey:e,sessionId:r,extraHeaders:n,loggerTags:o}=t,i={Authorization:`Bearer ${e}`,[ad]:Di??"",...r&&{[pR]:r},...n||{}};return o&&(i[dR]=JSON.stringify(o)),i}var Hl=t=>e=>{let r=BB(t);return UB({baseURL:`${t.baseUrl}/v1/llm/anthropic/${e}`,headers:r,apiKey:t.apiKey})(e)};var no=class extends zt{agentConfig;constructor(e,r){let n={...Gu,...e};super(r),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,r){let n={...e,loggerTags:r.loggerTags},o=await this.sendRequest(`/${z}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:r.abortSignal});return zT.parse(o)}async rankChunksWithRag(e,r){let n=await this.sendRequest(`/${z}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Di,...e},signal:r.abortSignal});return BT.parse(n)}async getScreenshotFromS3(e){let r=await this.sendRequest(`/${z}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return zB.string().parse(r)}async getElementLocation(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${z}/web-agent/locate-element`,{method:"POST",body:n,signal:r.abortSignal});return yR.parse(o)}async getAssertionResult(e,r){let n={...e,disableCache:!!r.disableCache,useConsensus:!!r.useConsensus,attemptNumber:r.attemptNumber,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${z}/web-agent/assertion`,{method:"POST",body:n,signal:r.abortSignal});return Ig.parse(o)}async getLintStepResult(e,r){let n={...e,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/step`,{method:"POST",body:n,signal:r.abortSignal});return SR.parse(o)}async getLintMcpCopilotMessageResult(e,r){let n={message:e.message,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:r.abortSignal});return hR.parse(o)}async getMcpCopilotConversationEvaluation(e,r){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${z}/web-agent/mcp-copilot-conversation-evaluator`,{method:"POST",body:n,signal:r.abortSignal});return gR.parse(o)}async getMcpCopilotChatSummary(e,r){let n={messagesAndToolCalls:e.messagesAndToolCalls,disableCache:!!r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${z}/web-agent/mcp-copilot-chat-summary`,{method:"POST",body:n,signal:r.abortSignal});return fR.parse(o)}async getVisualAssertionResult(e,r){let n={...e,disableCache:!!r.disableCache,useConsensus:!!r.useConsensus,attemptNumber:r.attemptNumber,loggerTags:r.loggerTags,useMemory:r.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${z}/web-agent/visual-assertion`,{method:"POST",body:n,signal:r.abortSignal});return Ig.parse(o)}async getAiActionCommand(e,r){let n=await this.sendRequest(`/${z}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return mR.parse(n)}async getMultiturnAiActionCommand(e,r){return await this.sendRequest(`/${z}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal})}async getMultiturnAiActionEvaluation(e,r){let n=await this.sendRequest(`/${z}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return zh.parse(n)}async getReverseMappedDescription(e,r){let n=await this.sendRequest(`/${z}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:r.disableCache,loggerTags:r.loggerTags},signal:r.abortSignal});return ER.parse(n)}async getTextExtraction(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${z}/web-agent/text-extraction`,{method:"POST",body:n,signal:r.abortSignal});return Fh.parse(o)}async getPageSummary(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${z}/web-agent/page-summary`,{method:"POST",body:n,signal:r.abortSignal});return fT.parse(o)}async getSmartWaitingDecision(e,r){let n={...e,disableCache:r.disableCache,loggerTags:r.loggerTags},o=await this.sendRequest(`/${z}/web-agent/smart-waiting`,{method:"POST",body:n,signal:r.abortSignal});return ST.parse(o)}async getTestResultClassification(e,r){let n=await this.sendRequest(`/${z}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return fh.parse(n)}async getExtractedKeywords(e,r){let n=await this.sendRequest(`/${z}/web-agent/extract-keywords`,{method:"POST",body:e,signal:r.abortSignal});return ev.parse(n)}async getAutohealingProposal(e,r){let n=await this.sendRequest(`/${z}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return pT.parse(n)}async getFailureRecoveryProposal(e,r){let n=await this.sendRequest(`/${z}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return hT.parse(n)}async getFailureRecoveryPlan(e,r){let n=await this.sendRequest(`/${z}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:r.loggerTags},signal:r.abortSignal});return mT.parse(n)}async getIframeRegex(e,r){let n=await this.sendRequest(`/${z}/web-agent/iframe-regex`,{method:"POST",body:e,signal:r.abortSignal});return CE.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Hl({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as Xg}from"zod";var et=class extends zt{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${z}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:r=>{b.warn(`API key check failed: ${r.message}`)}});return OR.parse(e)}async bulkGetRunStatus(e){let r=await this.sendRequest(`/${z}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return _R.parse(r)}async getTestYAMLExport(e){let r=await this.sendRequest(`/${z}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return TR.parse(r)}async updateStepCaches(e,r){await this.sendRequest(`/${z}/cache`,{method:"PATCH",body:e,extraHeaders:r,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,r){let n=await this.sendRequest(`/${z}/cache`,{method:"POST",body:e,extraHeaders:r,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return RR.parse(n)}async updateMobileStepCaches(e,r){await this.sendRequest(`/${z}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:r,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,r){let n=await this.sendRequest(`/${z}/mobile-cache`,{method:"POST",body:e,extraHeaders:r,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return AR.parse(n)}async queueTests(e){let r=await this.sendRequest(`/${z}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return bR.parse(r)}async uploadScreenshot(e){let r=await this.sendRequest(`/${z}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return IR.parse(r)}async getAllEnvironments(){let e=await this.sendRequest(`/${z}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return LR.parse(e)}async acquireCacheLock(e,r){let n=await this.sendRequest(`/${z}/result-cache/lock`,{method:"POST",body:e,signal:r,retries:3,requestTimeoutMs:3e4});return YR.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${z}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${z}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(r){if(r instanceof Error&&r.message.includes("404"))return null;throw r}}async queueSuiteRuns(e){let r=await this.sendRequest(`/${z}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return NR.parse(r)}async bulkGetRunGroupStatus(e){let r={runGroupIds:e},n=await this.sendRequest(`/${z}/run-groups/status`,{method:"POST",body:r,retries:3,requestTimeoutMs:5e3});return NT.array().parse(n)}async uploadProposedSteps(e,r){try{await this.sendRequest(`/${z}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){r.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,r){try{await this.sendRequest(`/${z}/billing/events`,{method:"POST",body:r,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let r=await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return DR.parse(r)}async patchTestFragment(e,r){await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"PATCH",body:r,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,r){let n=await this.sendRequest(`/${z}/results/tests/${e}`,{method:"POST",body:r,retries:3,requestTimeoutMs:1e4});return kR.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${z}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return FR.parse(e)}async startProcessingResultsUpload(e,r){let n=await this.sendRequest(`/${z}/results/uploads/${e}/process`,{method:"POST",body:r,retries:3,requestTimeoutMs:1e4});return UR.parse(n)}async fetchIconKnowledgeBase(e){try{let r=await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return eA.parse(r)}catch(r){return e.error({err:r},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,r){try{await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){r.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,r,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${z}/git/github/${e}/${r}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return kl.parse(a)}async getCommitFromGithub(e,r,n){let o=await this.sendRequest(`/${z}/git/github/${e}/${r}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return kl.parse(o)}async getMergedBranchFromGithub(e,r,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${z}/git/github/${e}/${r}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Dg.parse(a)}async getMergeBaseCommitFromGitlab(e,r,n){let o=new URLSearchParams;o.set("base",r),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${z}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return kl.parse(a)}async getCommitFromGitlab(e,r){let n=encodeURIComponent(e),o=await this.sendRequest(`/${z}/git/gitlab/${n}/commits/${r}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return kl.parse(o)}async getMergedBranchFromGitlab(e,r,n){let o=encodeURIComponent(r),i=encodeURIComponent(e),a=await this.sendRequest(`/${z}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Dg.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${z}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Xg.record(Xg.string(),Xg.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${z}/quarantine`,{method:"GET"});return BR.parse(e)}async quarantineTest(e,r,n){await this.sendRequest(`/${z}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:r,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,r,n){await this.sendRequest(`/${z}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:r,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let r=await this.sendRequest(`/${z}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return zR.parse(r)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${z}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:r,md5:n}){let o={channel:e,tag:r,md5:n},i=await this.sendRequest(`/${z}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return GR.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${z}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${z}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return jR.parse(e)}async deleteAndroidAsset(e,r){await this.sendRequest(`/${z}/limbar/assets/${e}/${r}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}async createIosEmulator(e){let r=await this.sendRequest(`/${z}/limbar/ios`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return HR.parse(r)}async extendIosEmulatorTtl(e){try{await this.sendRequest(`/${z}/limbar/ios/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async deleteIosEmulator(e){await this.sendRequest(`/${z}/limbar/ios/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async generateMobileLogcatUploadUrl(e){let r=await this.sendRequest(`/${z}/logcat/mobile/upload`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return bv.parse(r)}};async function Jg(t){let e=process.versions.node,r=parseInt(e.split(".")[0]);(isNaN(r)||r<18)&&(b.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),b.debug(`Identified node version ${e}`);let n=await t.client.getAuthInfo();return b.debug("Got auth info from API"),n}var hd=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,r){await this.apiClient.reportBillableEvents(e,r)}};var Ho=class extends zt{generator;constructor(e,r){super(e),this.generator=r}async runTemplateMatching(e,r={}){let n=await this.sendRequest(`/${z}/web-agent/template-matching`,{method:"POST",body:e,signal:r?.signal});return xE.parse(n)}async constructIframeRegex(e,r={}){return this.generator.getIframeRegex(e,{abortSignal:r.signal})}};var Qa=class{constructor(e,r){this.client=e;this.orgId=r}async acquireCacheLock(e,r){return this.client.acquireCacheLock(e,r)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,r){return this.client.saveNewIcons(e,r)}};import{Faker as HB,en as GB}from"@faker-js/faker";var Za="v1",On=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new HB({locale:GB}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let r=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Za}/tools/ai/generate`,{method:"POST",body:r}).catch(n=>{throw n instanceof un?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Za}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(r=>{throw r instanceof un?new Error(r.rawError):new Error(`Failed to send sms: ${r.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Za}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(r=>{throw r instanceof un?new Error(r.rawError):r})}async sendEmail(e){return this.httpClient.sendRequest(`/${Za}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(r=>{throw r instanceof un?new Error(r.rawError):new Error(`Failed to send email: ${r.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Za}/tools/email/fetchAll`,{method:"POST",body:e}).catch(r=>{throw r instanceof un?new Error(r.rawError):new Error(`Failed to fetch all emails: ${r.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Za}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(r=>{throw r instanceof un?new Error(r.rawError):new Error(`Failed to fetch latest emails: ${r.message}`)})}};function IA(t,e,r){return fetch(t,{method:"PUT",body:r,headers:{"Content-Type":e}})}var gd=class{constructor(e){this.client=e}async uploadResultsArchive(e,r){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await IA(n,"application/zip",r);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};function tt(t,e,r=!1){return t.length<e?t:t.slice(0,e-3)+(r?"...TRUNCATED...":"[...]")}var oo={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},io={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Qg={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Zg={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function OA(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?io[t.operation]:oo[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let r=t.negated?io[t.operation]:oo[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${r}`:`attribute '${t.attr}' ${r} '${t.value}'`}case"ELEMENT_NAME":{let r=t.negated?io[t.operation]:oo[t.operation];return t.operation==="EXISTS"?`tag name ${r}`:`tag name ${r} '${t.value}'`}case"ELEMENT_STYLE":{let r=t.negated?io[t.operation]:oo[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${r}`:`style property '${t.property}' ${r} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?Zg[t.condition]:Qg[t.condition];default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var epe={CONTENT:"The page"};function VB(t){switch(t.type){case"VALUE":return`the option with value ${t.value}`;case"LABEL":return`the option with label ${t.label}`;case"INDEX":return`the option at index ${t.index}`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Sd(t){switch(t.type){case"SUBSTRING":return`match substring '${t.url}'`;case"REGEX":return`match regex '${t.regex}'`;case"GLOB":return`match glob '${t.glob}'`;case"DOMAIN":return`match domain '${t.domain}'`;default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function fd(t){let e="";return t.method&&(e=` with method ${t.method}`),`${Sd(t.urlMatcher)}${e}`}function $B(t){return`${t.negated?io.CONTAINS:oo.CONTAINS} '${t.value}'`}function WB(t){switch(t.type){case"CONTENT":return $B(t);default:return t.type,""}}function ao(t,e=!0){switch(t.type){case"SUCCESS":return t.condition?.assertion?`Check success condition: ${t.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${t.goal}`;case"NAVIGATE":return`Go to URL: ${e?tt(t.url,30):t.url}`;case"DIALOG":return`Automatically ${t.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${Wt(t.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${Wt(t.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${Wt(t.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${Wt(t.target)}`:""}`;case"WAIT":return`Wait for ${t.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(t.target?.type==="coordinates")return`Click at coordinates: ${Wt(t.target)}`;let n="";return t.target?.elementDescriptor.length?n=` on element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${Wt(t.target)}`;case"BLUR":return`Focus ${Wt(t.target)}`;case"DRAG":return`Drag ${Wt(t.fromTarget)} onto ${Wt(t.toTarget)}`;case"MOUSE_DRAG":return t.target?.type==="description"&&t.target.elementDescriptor?`Click and drag ${Wt(t.target)} by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`:`Click and drag mouse by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`;case"TYPE":{let n="";return t.target?.type==="coordinates"?n=` in element at coordinates: ${Wt(t.target)}`:t.target?.elementDescriptor.length?n=` in element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Type '${t.value}'${n||""}`}case"HOVER":{let n="";return t.target.type==="coordinates"?n=` over coordinates: ${Wt(t.target)}`:t.target.elementDescriptor.length>0?n=` over element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${t.value}`;case"KEY_DOWN":return`Hold down ${t.value} on the keyboard`;case"KEY_UP":return`Release ${t.value} on the keyboard`;case"SELECT_OPTION":{let n="",o=VB(t.choice);return t.target.type==="coordinates"?n=` from element at coordinates: ${Wt(t.target)}`:t.target.elementDescriptor.length>0?n=` from: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":switch(t.action.type){case"SUBSTRING":return`Switch to tab with substring: ${t.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${t.action.pattern}`;case"INDEX":return`Switch to tab at index: ${t.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${t.url}`;case"REQUEST":return`Send ${t.method} request to ${t.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${t.url}`;case"COOKIE":return`Set cookie: ${t.value}`;case"LOCAL_STORAGE":return`Set local storage: ${t.key}: ${t.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?tt(t.code,30):t.code}`;case"AI_ASSERTION":return`Assertion: '${t.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${t.target?`for element: ${Wt(t.target)}`:"for entire page"}`;case"FILE_UPLOAD":return t.fileSource.type==="URL"?`Upload file: ${t.fileSource.url}`:`Upload file: ${t.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${Wt(t.target)} ${OA(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${WB(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${Sd(t.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return t.requestMatcher?`Register a listener for network requests that ${fd(t.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return t.key?`Wait for the listener ${t.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return t.requestMatcher?`Start recording requests that match ${fd(t.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return t.key?`Get the requests that were recorded for ${t.key}`:"Get the requests that were recorded";case"SET_HEADER":return t.name?t.requestMatcher?`Set a ${t.name} header for requests that match ${fd(t.requestMatcher)}`:`Set a ${t.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return t.requestMatcher?`Mock requests that ${fd(t.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return t.key?`Remove the mock with key ${t.key}`:"Remove all route mocks";case"OFFLINE_MODE":return t.enable?"Enable offline mode":"Disable offline mode";default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function qB(t){return typeof t=="object"&&t!==null}function Ln(t){if(Array.isArray(t))return t.map(Ln);if(qB(t)){let e={};return Object.entries(t).forEach(([r,n])=>{n!==void 0&&(e[r]=Ln(n))}),e}return t}function Gl(t,e,r,n){let{negated:o,ignoreCase:i}=n,a=t.trim(),s=e.trim();i&&(a=a.toLowerCase(),s=s.toLowerCase());let c;switch(r){case"CONTAINS":{c=a.includes(s);break}case"EQUALS":{c=a===s;break}case"STARTS_WITH":{c=a.startsWith(s);break}case"EXISTS":{c=a.length>0;break}default:throw new Error(`Unrecognized content assertion type: ${r}`)}return o?!c:c}function LA(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function es(t){return t.type==="ELEMENT_EXISTENCE"?t.negated?Qg[t.condition]:Zg[t.condition]:t.negated?oo[t.operation]:io[t.operation]}import{diff as YB}from"deep-object-diff";import{cloneDeep as Td}from"lodash-es";function ki(t){let e={parentChain:[]};return yd(t,e),e}function yd(t,e){let{onPresetAction:r,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=t;for(let a of t.steps)switch(a.type){case"PRESET_ACTION":if(r(a,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(a,e)&&i)return!0;e.parentChain.push(a);for(let c of a.blocks)if(r(c.assertion,e)&&i||yd({...t,steps:c.steps},e)&&i)return!0;if(yd({...t,steps:a.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"SECTION":case"AI_ACTION":if(n?.(a,e)&&i)return!0;if(a.steps){if(e.parentChain.push(a),yd({...t,steps:a.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(n?.(a,e)&&i)return!0;break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(a)}}function NA(t,e,r,n){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==n[s])return!1;i.shift()}return!!KB([t],r,i).result}function KB(t,e,r=[]){let n,o=[],i=(a,s)=>{let c=JSON.stringify(s.parentChain.map(u=>u.id)),l=r.length===0?!0:JSON.stringify(r)===c;return a.id===e&&l?(n=a,o=s.parentChain,!0):!1};return ki({steps:t,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function DA(t,e){e(t);for(let r in t){let n=t[r];n&&(Array.isArray(n)?bd(n,e):typeof n=="object"&&DA(n,e))}}function bd(t,e){for(let r of t)r&&(Array.isArray(r)?bd(r,e):typeof r=="object"&&DA(r,e))}function ef(t,e){if(t.length>e.length)return ef(e,t);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function Ed(t){for(let e of t.results)switch(e.type){case"PRESET_ACTION":t.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":t.onSimpleStepContainer?.(e),Ed({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),Ed({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}function so(t,e){return!t&&!e?!1:!t||!e?!0:Object.keys(YB(t,e)).length>0}function ts({steps:t,topLevel:e=!0,...r}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=r,a=[],s=[],c=[],l=0,u=(p,m)=>{try{let g=Zn.parse(m.value);if(g.type!==p.type){o.warn({parsedCacheEntry:g,command:p},"Not using step cache due to type mismatch"),s.push(m.key);return}p.cache=g.cache,a.push(m.key),c.push(m.uniqueKey)}catch(g){s.push(m.key),o.error({err:g,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let g=XB(p.id,m),h=g.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_ASSERTION")return;s.push(g[0])}};for(let p of t)switch(p.type){case"RESOLVED_MODULE":{l+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=ts({...r,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),s.push(...g),c.push(...h);break}case"SECTION":case"AI_ACTION":{if(l+=p.steps?.length??0,!p.steps?.length)break;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=ts({...r,steps:p.steps,topLevel:!1});a.push(...m),s.push(...g),c.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!du.includes(p.command.type)||(p.command.type==="TYPE"||p.command.type==="MOUSE_DRAG"||p.command.type==="VISUAL_DIFF"||p.command.type==="SCROLL_DOWN"||p.command.type==="SCROLL_UP"||p.command.type==="SCROLL_LEFT"||p.command.type==="SCROLL_RIGHT")&&!p.command.target||"cache"in p.command&&p.command.cache)continue;l++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){l++,d(m.assertion.command,i),l+=m.steps.length;let{cacheKeysHit:g,cacheKeysMissed:h,uniqueKeysHit:f}=ts({...r,steps:m.steps,topLevel:!1});a.push(...g),s.push(...h),c.push(...f)}if(p.elseSteps){l+=p.elseSteps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=ts({...r,steps:p.elseSteps,topLevel:!1});a.push(...m),s.push(...g),c.push(...h)}break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(p)}return e&&l&&s.length>0&&o.warn({totalSteps:l,cacheKeysMissed:s,cacheKeysHit:a,uniqueKeysHit:c,cacheEntriesKeys:Object.values(n).map(p=>p.uniqueKey)},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:s,uniqueKeysHit:c}}function kA(t,e){return e?`${e}:${t}`:t}function XB(t,e){let r=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),t];r.push(i.join(":"))}return r.reverse(),r}function tf(t){let{moduleStepParents:e=[],moduleIdParents:r=[]}=t;if(e.length!==r.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
34
34
  ${JSON.stringify(r)}`);let n=[];return n.push({key:kA(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId}),n}function FA(t){let e=new Set;return bd(t,r=>{if("type"in r&&r.type==="RESOLVED_MODULE"&&"moduleId"in r){let n=r.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function vd({cmd:t,newTarget:e,key:r,logger:n,updatedWithAI:o}){if(t.type==="DRAG")if(r!=="fromTarget"&&r!=="toTarget")n.error({cmd:t,newTarget:e,key:r},"Attempted to apply invalid cache to DRAG command");else{let i=t.cache?.updatedAt;t.cache={...t.cache,[r]:e,updatedAt:i&&!o?i:new Date}}else if(r==="target"&&pu(t)){let i=t.cache?.updatedAt;t.cache={...t.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:t,newTarget:e,key:r},"Invalid target cache application")}function Vl(t,e,r){let n=t.cache&&"memory"in t.cache?t.cache.memory?.traces:void 0;so(n,e)&&(r.info({updatedTraces:e,oldCmd:t},"Wrote new memory to assertion command"),t.cache={...t.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date})}function UA({steps:t}){let e={};return ki({steps:t,onPresetAction:(r,n)=>{let o=r.command;if(!("cache"in o)||!o.cache)return;let i=n.parentChain.filter(c=>c.type==="RESOLVED_MODULE").map(c=>c.id).join(":"),a=kA(o.id,i),s=Zn.parse(o);e[a]=s},onSimpleStepContainer:(r,n)=>{},onConditional:(r,n)=>{}}),e}function jl(t){return{...t,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function JB(t,e){return so(t.memory,e.memory)?{...t,memory:e.memory,updatedAt:e.updatedAt}:t}function rf(t,e){return t?so(t.target.memory,e.target.memory)?{target:{...t.target,memory:e.target.memory},updatedAt:e.updatedAt}:t:{target:jl(e.target),updatedAt:e.updatedAt}}function QB(t,e){let r=Td(t);return r.fromTarget?so(t.fromTarget?.memory,e.fromTarget?.memory)&&(r.fromTarget={...r.fromTarget,memory:e.fromTarget?.memory},r.updatedAt=e.updatedAt):(r.fromTarget=e.fromTarget,r.fromTarget&&(r.fromTarget=jl(r.fromTarget),r.updatedAt=e.updatedAt)),r.toTarget?so(t.toTarget?.memory,e.toTarget?.memory)&&(r.toTarget={...r.toTarget,memory:e.toTarget?.memory},r.updatedAt=e.updatedAt):(r.toTarget=e.toTarget,r.toTarget&&(r.toTarget=jl(r.toTarget),r.updatedAt=e.updatedAt)),r}function BA({newEntries:t,originalCachesMap:e,logger:r}){let n=[];for(let o of t){let i=e[o.key];if(!i||!i.cache){n.push(o);continue}if(o.value.type!==i.type){n.push(o);continue}let a=o.value.cache;if(o.value={...i},!a){n.push(o);continue}if("memory"in a&&a.memory){let s=i.cache&&"memory"in i.cache?i.cache.memory:void 0;so(s,a.memory)&&(o.value.cache=JB(i.cache,a),n.push(o))}else if("target"in a&&a.target.memory){let s=i.cache&&"memory"in i.cache?i.cache.memory:void 0;if(so(s,a.target.memory)){let c=Rr.safeParse(o.value.cache);o.value.cache=rf(c.data,a),n.push(o)}}else if("fromTarget"in a||"toTarget"in a){let s=lh.optional().parse(o.value.cache);if(!s)continue;let c={from:s.fromTarget?.memory,to:s.toTarget?.memory},l={from:i.cache&&"fromTarget"in i.cache?i.cache.fromTarget?.memory:void 0,to:i.cache&&"toTarget"in i.cache?i.cache.toTarget?.memory:void 0};so(l,c)&&(o.value.cache=QB(s,a),n.push(o))}}return n}async function Rd({cacheStorage:t,logger:e,schemaVersion:r,stepLists:n,testId:o}){let i=Td(n.steps),a=Td(n.beforeSteps)??void 0,s=Td(n.afterSteps)??void 0,c={steps:i,beforeSteps:a,afterSteps:s};try{await t.resolveStepCacheEntries({testId:o,stepLists:c,schemaVersion:r,logger:e})}catch(l){throw e.error({err:l},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is a Momentic issue, please contact Support with the following error: ${l}`)}return c}function zA(t){let e=[];for(let r of t){r.sort((a,s)=>a.timestamp-s.timestamp);let n=[],o,i=1;for(let a of r)o&&o.text===a.text&&o.type===a.type&&JSON.stringify(o.args??null)===JSON.stringify(a.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:n.push(o)),o=a,i=1);o&&n.push(o),e.push(n)}return e}import{cloneDeep as Nhe}from"lodash-es";import nf from"semver";function Ad(t,e){if(t!=="0.0.1"&&t!==e[e.length-1].toVersion)throw new Error("Please bump latestSchemaVersion in types package after adding a migration");e.forEach((r,n)=>{if(!nf.valid(r.toVersion)||!nf.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!nf.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(n===0)return;if(e[n-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${n} is not contiguous with previous migration`)})}import ZB from"diff-lines";import ez,{gte as tz}from"semver";function rz(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}async function of({metadata:t,steps:e,logger:r,toVersion:n,migrations:o}){let i=e,{schemaVersion:a,id:s}=t,c=o.findIndex(d=>ez.gt(d.toVersion,a));if(c===-1)return{steps:i,newVersion:a};let l=a;for(let d=c;d<o.length;d++){if(n&&tz(l,n)){r.debug("Stopping migration early because toVersion was reached");break}let p=o[d],m={id:s,migration:p.name,toVersion:p.toVersion};try{i=await HA(i,p),l=p.toVersion}catch(g){throw r.error({err:g,...m},"Migration failed"),new Error(`Step migration ${p.name} failed: ${g}`)}}let u=ZB(JSON.stringify(e,void 0,2),JSON.stringify(i,void 0,2),{n_surrounding:1});return u.trim()&&r.debug({diffs:u,id:s},"Migration diffs"),{newVersion:l,steps:i}}async function HA(t,e){let r=await e.execute(t);for(let n of r)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||rz(i)&&(n[o]=await HA(i,e))}return r}var GA={name:"Migrate API request body types",fromVersion:"0.0.1",toVersion:"0.0.2",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="MOBILE_PRESET_STEP")return e;let r=e.command;if(!r||r.type!=="REQUEST")return e;let n=typeof r.body=="string"&&r.body.length>0?{type:"json",content:r.body}:void 0;return r.body=n,e})};var nz=[GA];Ad(Lh,nz);var jA={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>(t=t.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),t=t.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),t)};var VA={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let r=e.commands,n=r[r.length-1];return n&&n.type!=="SUCCESS"&&r.push({type:"SUCCESS"}),e})};var oz=["target","fromTarget","toTarget"];function $A(t){for(let e of oz){if(t[e]===void 0)continue;let r=t[e];r.elementDescriptor!==void 0?r.type="description":t[e]={type:"description",elementDescriptor:""}}}var WA={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":return $A(e.command),e;case"AI_ACTION":{let r=e.commands;for(let n of r??[])$A(n);return e}default:return e}})};import{v4 as iz}from"uuid";var qA={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=iz()),e;default:return e}})};import{v4 as KA}from"uuid";var YA={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let r=e.command;return r.id=r.id??KA(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(r=>({type:"PRESET_ACTION",command:{...r,id:r.id??KA()}})),delete e.commands),e;default:return e}})};var XA={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let r=e.command;return typeof r.type!="string"||r.type!=="AI_WAIT"||(r.type="AI_ASSERTION",r.timeout||(r.timeout=10)),e}default:return e}})};import{v4 as az}from"uuid";var JA={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>("id"in e&&typeof e.id=="string"||(e.id=az()),e))};import{v4 as QA}from"uuid";var ZA={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let r=e.condition;r.id||(r.id=QA())}return e.id=QA(),e})};var ew={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||typeof r.envKey!="string"||(e.envKey=r.envKey,delete r.envKey),e})};import{v4 as sz}from"uuid";var tw={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=sz()),e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||typeof r.envKey!="string"||(e.envKey=r.envKey,delete r.envKey),e})};var rw={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:r.option},e.option=void 0),e})};var nw={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return r&&ow(r),e})};function ow(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){ow(t[e]);return}if(typeof t[e]!="string")return;let r=t[e];e==="code"?t[e]=r.replace(/inputs\./g,"env."):r.includes("{{")&&r.includes("}}")&&(t[e]=r.replace(/inputs\./g,"env."))})}var iw={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="TAB"||r.url===void 0||(r.action={type:"SUBSTRING",substring:r.url},r.url=void 0),e})};var aw={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="TYPE"?e:r.pressKeysSequentially===void 0?(r.delay=0,e):(r.pressKeysSequentially&&(r.pressKeysSequentially=void 0,r.delay=50),e)})};var sw={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="WAIT_FOR_URL"||r.url===void 0||(r.matcher={type:"GLOB",glob:r.url},r.url=void 0),e})};var lw={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;if(!r)return e;if(r.type==="SELECT_OPTION"){if(r.option===void 0)return e;r.choice={type:"VALUE",value:r.option},r.option=void 0}else if(r.type==="TAB"){if(r.url===void 0)return e;r.action={type:"SUBSTRING",substring:r.url},r.url=void 0}else if(r.type==="WAIT_FOR_URL"){if(r.url===void 0)return e;r.matcher={type:"GLOB",glob:r.url},r.url=void 0}else r.type==="AI_WAIT"&&(r.type="AI_ASSERTION",r.timeout||(r.timeout=10));return e})};var cw={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;return!r||r.type!=="MOCK_ROUTE"&&r.type!=="SET_HEADER"&&r.type!=="RECORD_REQUESTS"&&r.type!=="REGISTER_REQUEST_LISTENER"||(r.type==="REGISTER_REQUEST_LISTENER"||r.type==="RECORD_REQUESTS"?r.requestMatcher={urlMatcher:{type:"REGEX",regex:r.pattern}}:(r.type==="SET_HEADER"||r.type==="MOCK_ROUTE")&&r.urlPattern&&(r.requestMatcher={urlMatcher:{type:"REGEX",regex:r.urlPattern}})),e})};var uw={name:"Migrate API request body types",fromVersion:"1.0.21",toVersion:"1.0.22",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let r=e.command;if(!r||r.type!=="REQUEST")return e;let n=typeof r.body=="string"&&r.body.length>0?{type:"json",content:r.body}:void 0;return r.body=n,e})};var dw={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async t=>t.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var wd=new Set(["CLICK","TYPE","SELECT_OPTION"]),pw={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e.command,n=r?.type,o=r?.elementDescriptor;return(o!==void 0||wd.has(n))&&(r.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,c=a?.type;(s!==void 0||wd.has(c))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,c=s?.elementDescriptor,l=s?.type;(c!==void 0||wd.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||wd.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var mw={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e;return r.status==="FAILURE"&&(r.status="FAILED"),typeof r.commands=="object"&&Array.isArray(r.commands)&&r.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),r}),stopOnFailure:!0};var hw={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async t=>t.map(e=>{let r=e.command,n=r?.type;return n?.startsWith("PRESET_")&&(r.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(l=>{let u=l.type;u?.startsWith("PRESET_")&&(l.type=u.slice(7))})}),e}),stopOnFailure:!0};var gw=[dw,mw,hw,pw,jA,VA,WA,qA,YA,XA,JA,ZA,ew,tw,rw,nw,iw,aw,sw,lw,cw,uw];Ad(_e,gw);async function rs({metadata:t,steps:e,logger:r,toVersion:n}){return await of({metadata:t,steps:e,logger:r,toVersion:n,migrations:gw})}import{diff as qhe}from"deep-object-diff";import{cloneDeep as Yhe}from"lodash-es";import{v4 as lge}from"uuid";import{cloneDeep as cz}from"lodash-es";import vw from"truncate-json";import{v4 as Sw}from"uuid";import{cloneDeep as vge,unset as Rge}from"lodash-es";function fw(t){switch(t.type){case"AI_ACTION":return`AI action: ${tt(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${tt(t.text,100)}`;case"PRESET_ACTION":return ao(t.command);case"MODULE":return`Module ${t.moduleName??t.id}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section ${t.description?`with goal: ${tt(t.description,100)}`:""}`;default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}function lo(t){switch(t.type){case"AI_ACTION":return`AI action: ${tt(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${tt(t.text,100)}`;case"PRESET_ACTION":return ao(t.command);case"MODULE":return`Module: ${t.id}`;case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${t.description?`with goal: ${tt(t.description,100)}`:""}`;default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}function ns(t,e){return t.split(`
35
35
  `).map(r=>" ".repeat(e)+r).join(`
@@ -38,13 +38,13 @@ ${ns(`Number of sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return ao(t.command,!1
38
38
  `)}case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in t&&t.assertionResult&&(e.push(ns("Conditional check:",2)),e.push(ns(af(t.assertionResult),2))),"results"in t&&Array.isArray(t.results)){let r=t.results.length,n="assertionResult"in t&&t.assertionResult?"Branch steps":"Else branch steps";e.push(ns(`${n}: ${r}`,2))}return e.join(`
39
39
  `)}case"SECTION":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`Section${t.description?`with goal: ${t.description}`:""}
40
40
  ${ns(`Number of sub-steps: ${e}`,2)}`}default:return(r=>{throw new Error("You missed a case in the switch above")})(t)}}var yw=1e3,Ew=5e7,uz="[FAILED]";async function bw(t,e,r){if(r){let n=await e.getScreenshot(t,r);if(n)return`data:image/jpeg;base64,${Buffer.from(n).toString("base64")}`}}function dz(t,e){let r=(()=>{switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":return"AI action";case"PRESET_ACTION":return"Preset action";case"MODULE":return"Module";case"CONDITIONAL":return"Conditional step";case"SECTION":return"Section";default:return(i=>{throw new Error("You missed a case in the switch above")})(t)}})();return Rw(t)?t.message||"Section start placeholder":(o=>e?`${e==="start"?"Start":"End"} of ${r}
41
- ${o}`:o)(af(t))}function pz(t,{unflattenedIndex:e,parentStep:r}){if(!(e===void 0||Rw(t))){if(r){let n=`sub-step ${e}`;switch(r.type){case"MODULE":return`${n} within module '${r.moduleName??r.id}'`;case"AI_ACTION":case"AI_ACTION_DYNAMIC":return`${n} within AI action`;case"CONDITIONAL":return`${n} within conditional step`;default:return n}}return`step ${e}`}}function Rw(t){return t.type==="PRESET_ACTION"&&t.command?.type==="SUCCESS"&&!!t.message?.match(/^Starting the [\w- ]+ section$/)}function xd(t,e={}){let r=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:Sw(),message:`Starting the ${t.replace(/-/g," ")} section`,startedAt:r,finishedAt:r,status:"SUCCESS",command:{id:Sw(),type:"SUCCESS"},results:[]}}function Cd(t,e={}){let{index:r,includeDomState:n=!1,header:o,unflattenedIndex:i,parentStep:a,includeUserFacingStepReference:s}=e,c=dz(t,o),l;t.type==="PRESET_ACTION"&&(l=t.results?.[0]?.elementInteracted);let u=t.message!=="Successfully executed preset action."?t.message:void 0,d=c;t.status==="FAILED"&&(d=`${uz} ${d}`);let p={description:d,startedAt:t.startedAt.toISOString(),finishedAt:t.finishedAt.toISOString(),beforeUrl:t.beforeUrl,afterUrl:t.afterUrl,beforeSnapshot:t.beforeSnapshot,afterSnapshot:t.afterSnapshot,elementInteracted:l,message:u,index:r};if(s&&(p.userFacingStepReference=pz(t,{parentStep:a,unflattenedIndex:i})),t.status==="FAILED"&&n)try{let m=DT.array().parse(t.details);for(let g of m)"pageState"in g&&(p.pageState=g.pageState)}catch{}return p}async function Aw(t,e,r,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:s=0,isTopLevelResultList:c=!0,includeUserFacingStepReference:l,parentStep:u}){let d,p=[];for(let m=0;m<r.length;m++){let g=r[m],h=n?m+s:void 0,f=c?m-1:m;switch(g.type){case"PRESET_ACTION":{p.push(Cd(g,{index:h,includeDomState:o,includeUserFacingStepReference:l,header:void 0,unflattenedIndex:f,parentStep:u})),g.status==="FAILED"&&(d=h);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){p.push(Cd(g,{index:n?h:void 0,includeDomState:o,includeUserFacingStepReference:l,header:"start",unflattenedIndex:f,parentStep:u})),s+=1;let{failureIndex:S,results:y}=await Aw(t,e,g.results,{addIndices:n,includeDomState:o,includeUserFacingStepReference:l,flatten:i,maxItemsFromEnd:a,indexOffset:s+m,isTopLevelResultList:!1,parentStep:g});p.push(...y),S!==void 0?d=S:g.status==="FAILED"&&(d=h),s+=y.length,p.push(Cd(g,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:"end"}))}else p.push(Cd(g,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:void 0}));break}default:return(y=>{throw new Error("You missed a case in the switch above")})(g)}}return{results:p,failureIndex:d}}async function os(t,e,r,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,includeUserFacingStepReference:s,flatten:c=!0,maxItemsFromEnd:l=20}){let u=await Aw(t,e,r,{addIndices:o,includeUserFacingStepReference:s,includeDomState:a,flatten:c,maxItemsFromEnd:l,indexOffset:0}),{results:d}=u,{failureIndex:p}=u;p!==void 0&&d.length>0&&(d=d.slice(0,p+1));let m=[],g=0;if(l!==void 0&&d.length>l&&(g=d.length-l),p!==void 0&&p<d.length-1&&t.warn({failureIndex:p,flattenedResultsLength:d.length,lastIndex:d.length-1,isLastIndex:p===d.length-1,offset:g},"PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible"),p!==void 0&&g>p)throw new Error("Failure index is out of bounds");for(let h=g;h<d.length;h++){let f=d[h],S={description:f.description,startedAt:f.startedAt,finishedAt:f.finishedAt,beforeUrl:f.beforeUrl,afterUrl:f.afterUrl,elementInteracted:f.elementInteracted,userFacingStepReference:f.userFacingStepReference,message:f.message,pageState:f.pageState,index:f.index},y,E;(n===void 0||n>0&&h>=d.length-n)&&(f.afterSnapshot&&(E=await bw(t,e,f.afterSnapshot)),i&&f.beforeSnapshot&&(y=await bw(t,e,f.beforeSnapshot))),S.beforeScreenshot=y,S.afterScreenshot=E,m.push(S)}return{results:m,failureIndex:p!==void 0?p-g:void 0}}function is({json:t,keysToRedact:e,maxJsonStringSize:r}){try{if(!t)return t;if(typeof t=="string")return tt(t,r??2e4);if(typeof t=="object"){let{jsonString:n}=vw(JSON.stringify(t,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),r??2e4);return JSON.parse(n)}return t}catch{return t}}function sf(t,e){for(let r=0;r<t.length;r++){let n=t[r];try{if(n.data){let{jsonString:o}=vw(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.details&&(n.details=void 0),n.type){case"PRESET_ACTION":Tw(n);break;case"CONDITIONAL":n.assertionResult&&Tw(n.assertionResult),sf(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{sf(n.results,e);break}default:return(i=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})(n)}}}function Tw(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function _d(t,e){let r=cz(t);if(sf(r,e),r.length>yw)return e.error("Results too long, truncating before insertion"),r.slice(r.length-yw,r.length);let n=JSON.stringify(r);if(n.length>Ew)for(e.error({serializedLength:n.length,resultsArrayLength:r.length},"Database content violation: results too large, truncating before insertion");n.length>Ew;)r.splice(0,1),n=JSON.stringify(r);try{return It.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as Vge}from"lodash-es";var mz=/^(?!.*\S+\s+\S+).*$/,hz=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,gz=/style="([^"]*)/g,fz=/data-[\w-]+/g,Sz=t=>{switch(t.type){case"AI_ASSERTION":return{type:t.type,assertion:t.assertion};case"DRAG":if(t.fromTarget.type==="description")return{type:t.type,description:t.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(t.target?.type==="description")return{type:t.type,description:t.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function ww(t){let e=Sz(t),r=e.type==="AI_ASSERTION"?e.assertion:e.description;return!r||r==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:mz.test(r)&&hz.test(r)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:gz.test(r)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:fz.test(r)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(r)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}import{diff as yz}from"deep-object-diff";import{diff as xw}from"deep-object-diff";import{cloneDeep as Cw}from"lodash-es";import{v4 as lf}from"uuid";async function it(t){let e=new Map,r=new Set,n=_o.parse({steps:t.stepLists.steps??[],beforeSteps:t.stepLists.beforeSteps??void 0,afterSteps:t.stepLists.afterSteps??void 0}),o=Cw(n.steps),i=await Fi({...t,steps:o,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:r}),a={stepsToSave:{steps:i.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:i.cachesToSave,moduleUpdates:i.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let c=Cw(n[s]);if(!c)continue;let l=await Fi({...t,steps:c,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:r});a.cachesToSave.push(...l.cachesToSave),a.moduleUpdates.push(...l.moduleUpdates),a.stepsToSave[s]=l.stepsToSave}return a}async function Fi({steps:t,...e}){let{seenModules:r,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of t)switch(delete u.index,delete u.aiSuggested,u.id=c?lf():u.id,u.type){case"PRESET_ACTION":{let p=u.command;p.id=c?lf():p.id,"cache"in p&&p.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(tf({id:p.id,orgId:n.orgId,testId:n.testId,value:Zn.parse(p),moduleIdParents:o,moduleStepParents:i}))),delete p.cache),p.thoughts&&delete p.thoughts,l.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?lf():u.id,m=u.moduleId;a.has(m)?m=a.get(m):s!==void 0&&(m=await s(u),a.set(u.moduleId,m));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await Fi({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(f),l.cachesToSave=l.cachesToSave.concat(g),r.has(m)||(r.add(m),l.moduleUpdates.push({...fr.parse(u),steps:Qe.array().parse(h),moduleId:m}));let S=sn.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});l.stepsToSave.push(S);break}case"AI_ACTION":{if(!u.steps){l.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await Fi({...e,steps:u.steps});try{u.steps=Ar.array().parse(p)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}l.stepsToSave.push(u),l.cachesToSave=l.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let g of u.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:S}=await Fi({...e,steps:g.steps});p.push({...g,steps:h}),l.cachesToSave=l.cachesToSave.concat(f),l.moduleUpdates=l.moduleUpdates.concat(S)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await Fi({...e,steps:u.elseSteps});m.elseSteps=g,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(f)}l.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:g}=await Fi({...e,steps:u.steps}),h={...u,steps:p};l.moduleUpdates=l.moduleUpdates.concat(g),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(m);break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(u)}return l}async function Md({logger:t,cacheStorage:e,orgId:r,testId:n,originalStepsWithCaches:o,updatedStepsWithCaches:i}){let a=xw(o,i);if(Object.keys(a).length!==0){t.debug("Updating step caches post-success");try{let{cachesToSave:s}=await it({stepLists:i,cacheCreationParams:{testId:n,orgId:r}});await e.saveStepCacheEntries({logger:t,testId:n,entries:s})}catch(s){t.error({err:s},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Pd({logger:t,cacheStorage:e,orgId:r,testId:n,originalStepsWithCaches:o,updatedStepsWithCaches:i}){let a=xw(o,i);if(Object.keys(a).length===0)return;t.debug("Updating memory post-run failure");let s={};for(let u of["steps","beforeSteps","afterSteps"]){let d=o[u];if(!d||!d.length)continue;let p=UA({steps:d});for(let[m,g]of Object.entries(p))s[m]=g}let{cachesToSave:c}=await it({stepLists:i,cacheCreationParams:{testId:n,orgId:r}});t.debug({newEntries:c.length,originalCaches:Object.keys(s).length},"Comparing caches for memory pruning");let l=BA({newEntries:c,originalCachesMap:s,logger:t});if(l.length){t.debug({prunedCaches:l},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:t,testId:n,entries:c})}catch(u){t.error({err:u},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}async function Mw(t,e){let[r,n]=await Promise.all([it({stepLists:{beforeSteps:t.beforeSteps??[],steps:t.steps??[],afterSteps:t.afterSteps??[]}}),it({stepLists:{beforeSteps:e.beforeSteps??[],steps:e.steps??[],afterSteps:e.afterSteps??[]}})]),o=[],i=[],a=["steps","beforeSteps","afterSteps"];for(let s of a){let c=r.stepsToSave[s]??[],l=n.stepsToSave[s]??[];Ez(c,l,s,o,i)}return{additions:o,deletions:i}}function _w(t){let e=new Map;for(let r=0;r<t.length;r++){let n=t[r];n&&e.set(n.id,{step:n,index:r})}return e}function Ez(t,e,r,n,o){let i=_w(t),a=_w(e);for(let[s,{step:c,index:l}]of a){let u=i.get(s);if(!u)n.push({index:l,section:r,step:c});else{let d=yz(u.step,c);Object.keys(d).length>0&&(n.push({index:l,section:r,step:c}),o.push({index:u.index,section:r,step:u.step}))}}for(let[s,{step:c,index:l}]of i)a.has(s)||o.push({index:l,section:r,step:c})}function Pw(t,e){if(!(!t.envs||!t.envs.length)){for(let r of t.envs){let n=r;e in r&&(n[e]&&(r.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}t.envs.some(r=>r.default)||(t.envs[0].default=!0)}}import{cloneDeep as Iw}from"lodash-es";import{z as bz}from"zod";async function Ow({rawSteps:t,metadata:e,logger:r,callbacks:n}){Pw(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await Id({rawSteps:t.steps,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o}),s={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let l=t[c];if(!l)continue;let{resolvedSteps:u}=await Id({rawSteps:l,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o});s[c]=u}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function Ui(t,e,r){let{newVersion:n,steps:o}=await rs({metadata:t,steps:e,logger:r});try{return{steps:Qe.array().parse(o),newVersion:n}}catch(i){let a=new Co(`Failed to parse test steps while migrating test: ${i}`,t.id,"entity",{cause:i});throw i instanceof bz.ZodError?(a.zodIssues=i.issues,r.error({type:"zod",zodIssues:i.issues,newVersion:n,id:t.id},"Failed to parse test steps while migrating test")):r.error({err:i,newVersion:n,id:t.id},"Failed to parse test steps while migrating test"),a}}async function Id({rawSteps:t,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await Ui(e,t,r),s=[];for(let c of a)s.push(await $l({step:c,callbacks:n,logger:r,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function $l({step:t,callbacks:e,logger:r,resolvedModuleCache:n}){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":{let c=t.moduleId,l=n[c];if(l)return{...Iw(l),...t,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:r});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await rs({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:r}),m;try{m=Qe.array().parse(p)}catch(f){throw r.error({type:"zod",err:f,steps:p,newVersion:d,id:c},"Module failed to parse"),f}let g;try{g=await Promise.all(m.map(f=>$l({step:f,callbacks:e,logger:r,resolvedModuleCache:n})))}catch(f){throw r.error({err:f,...t},`Failed to recursively resolve module '${u.name}': ${f}`),f}let h={...u,steps:g};return n[c]=Iw(h),{...h,...t,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of t.blocks){let l=[];for(let u of c.steps)l.push(await $l({step:u,callbacks:e,logger:r,resolvedModuleCache:n}));o.push({...c,steps:l})}let i;if(t.elseSteps){i=[];for(let c of t.elseSteps)i.push(await $l({step:c,callbacks:e,logger:r,resolvedModuleCache:n}))}return{...t,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of t.steps)a.push(await $l({step:c,callbacks:e,logger:r,resolvedModuleCache:n}));return{...t,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{cloneDeep as Tz}from"lodash-es";import{stringify as Lw}from"yaml";async function Nw({test:t,processedModuleNames:e=new Set,createNewCacheIds:r=!1}){let n={id:t.id,name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:t.schemaVersion,advanced:t.advanced,retries:t.retries,envs:t.envs,disabled:t.disabled,labels:t.labels},o={},i=await vz({originalStepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:r}),a={fileType:Se.TEST,...n,beforeSteps:i.beforeSteps&&i.beforeSteps.length>0?i.beforeSteps:void 0,steps:i.steps,afterSteps:i.afterSteps&&i.afterSteps.length>0?i.afterSteps:void 0};return{test:Lw(a),modules:o}}async function vz({originalStepLists:t,modules:e,processedModuleNames:r,createNewCacheIds:n}){let o=Tz(t);Object.values(o).forEach(s=>{Rz(s??[])});let{stepsToSave:i,moduleUpdates:a}=await it({stepLists:o,createNewCacheIds:n});for(let s of a)r.has(s.name)||(e[s.name]=Az(s),r.add(s.name));return i}function Rz(t){ki({steps:t,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function Az(t){let e=fr.parse(t),r={fileType:Se.MODULE,...e,schemaVersion:_e,steps:t.steps};return Lw(r)}async function le(t,e){if(!(t<=0))return new Promise((r,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),r()},t);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Wl({promiseGenerator:t,signal:e,codePath:r,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:r,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${r})`)},5e3);return new Promise((s,c)=>{function l(){clearInterval(a),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",l,{once:!0}),(async()=>{try{s(await t())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function ql({promiseGenerator:t,timeoutMs:e,codePath:r,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",s),!i&&a.abort()},e);o?.addEventListener("abort",s,{once:!0});try{return await Wl({promiseGenerator:t,signal:a.signal,codePath:r,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function Dw(t){let e;return t>10*60*1e3?e=2*60*1e3:t>60*1e3?e=20*1e3:t>10*1e3?e=2*1e3:e=1e3,e}function Od(t){let e=[];for(let r of t)switch(r.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(r);break;case"RESOLVED_MODULE":{let n={...r,type:"MODULE"};e.push(sn.parse(n));break}case"SECTION":{let n={...r,steps:Od(r.steps)};e.push(Qe.parse(n));break}case"CONDITIONAL":{let n={...r,blocks:r.blocks.map(o=>({assertion:o.assertion,steps:Od(o.steps)})),elseSteps:r.elseSteps?Od(r.elseSteps):void 0};e.push(bi.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Ld(t){return Od([t])[0]}import wz from"picomatch";var Nd=(t,e,r)=>{r?.caseInsensitive&&(t=t.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=r?.caseInsensitive?e.url.toLowerCase():e.url;n=t.includes(o);break}case"GLOB":{let o=r?.caseInsensitive?e.glob.toLowerCase():e.glob;n=t===e.glob||wz(o)(t);break}case"REGEX":{n=new RegExp(e.regex).test(t);break}case"DOMAIN":{let o=r?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(t).hostname===o;break}}return r?.negated?!n:n},Dd=(t,e)=>{try{let{hostname:r,pathname:n}=new URL(t),{hostname:o,pathname:i}=new URL(e);return r!==o||n!==i}catch{return!1}},as=t=>{try{return new URL(t),!0}catch{return!1}},kw=t=>!t.toLowerCase().startsWith("http"),ss=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function Bi(t,e){try{return!!new URL(t).origin.trim()}catch(r){return e?.error({url:t,err:r},"Invalid URL in check"),!1}}async function Cz(t){let{logger:e,browserStateStorage:r,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:s,disableCache:c}=t,l=[];if(o.length>0){let{results:d}=await os(e,r,o,{numStepsWithScreenshots:s,addIndices:!1,includeUserFacingStepReference:!0,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});l=d}return await n.getTestResultClassification({results:l,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1,loggerTags:je(e)})}async function Fw(t){let{logger:e,browserStateStorage:r,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:s,numStepsWithScreenshots:c,disableCache:l}=t,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[xd("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=xd("teardown",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...u,m,...o?.afterResults??[]]}else if(u.length<20){let d=(o?.beforeResults??[]).at(-1),p=u.at(0),m=xd("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!r||!u||u.length===0)return{};try{let d=await Cz({logger:e,browserStateStorage:r,generator:n,results:u,error:a,maxItemsFromEnd:s,numStepsWithScreenshots:c,disableCache:l});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}import{v4 as Uw}from"uuid";function cf(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var kd=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:r,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=r,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[r.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:cf({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(Sv(e.type)){this.creditsUsedV2+=1;return}let r=gg(e.type);if(this.creditsUsedV1+=r??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=fg(e.command);this.creditsUsedV1+=n??0}}async flush(e){this.creditsUsedV1>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:Uw(),properties:cf({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:Uw(),properties:cf({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as xz}from"lodash-es";function Fd(t,e){if(t.length===0)return`${e}: (no steps)`;let r=_z(t);r.forEach((o,i)=>{let a=o;a.index=i});let n=["```json",JSON.stringify(r,null,2),"```"].join(`
41
+ ${o}`:o)(af(t))}function pz(t,{unflattenedIndex:e,parentStep:r}){if(!(e===void 0||Rw(t))){if(r){let n=`sub-step ${e}`;switch(r.type){case"MODULE":return`${n} within module '${r.moduleName??r.id}'`;case"AI_ACTION":case"AI_ACTION_DYNAMIC":return`${n} within AI action`;case"CONDITIONAL":return`${n} within conditional step`;default:return n}}return`step ${e}`}}function Rw(t){return t.type==="PRESET_ACTION"&&t.command?.type==="SUCCESS"&&!!t.message?.match(/^Starting the [\w- ]+ section$/)}function xd(t,e={}){let r=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:Sw(),message:`Starting the ${t.replace(/-/g," ")} section`,startedAt:r,finishedAt:r,status:"SUCCESS",command:{id:Sw(),type:"SUCCESS"},results:[]}}function Cd(t,e={}){let{index:r,includeDomState:n=!1,header:o,unflattenedIndex:i,parentStep:a,includeUserFacingStepReference:s}=e,c=dz(t,o),l;t.type==="PRESET_ACTION"&&(l=t.results?.[0]?.elementInteracted);let u=t.message!=="Successfully executed preset action."?t.message:void 0,d=c;t.status==="FAILED"&&(d=`${uz} ${d}`);let p={description:d,startedAt:t.startedAt.toISOString(),finishedAt:t.finishedAt.toISOString(),beforeUrl:t.beforeUrl,afterUrl:t.afterUrl,beforeSnapshot:t.beforeSnapshot,afterSnapshot:t.afterSnapshot,elementInteracted:l,message:u,index:r};if(s&&(p.userFacingStepReference=pz(t,{parentStep:a,unflattenedIndex:i})),t.status==="FAILED"&&n)try{let m=DT.array().parse(t.details);for(let g of m)"pageState"in g&&(p.pageState=g.pageState)}catch{}return p}async function Aw(t,e,r,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:s=0,isTopLevelResultList:c=!0,includeUserFacingStepReference:l,parentStep:u}){let d,p=[];for(let m=0;m<r.length;m++){let g=r[m],h=n?m+s:void 0,f=c?m-1:m;switch(g.type){case"PRESET_ACTION":{p.push(Cd(g,{index:h,includeDomState:o,includeUserFacingStepReference:l,header:void 0,unflattenedIndex:f,parentStep:u})),g.status==="FAILED"&&(d=h);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){p.push(Cd(g,{index:n?h:void 0,includeDomState:o,includeUserFacingStepReference:l,header:"start",unflattenedIndex:f,parentStep:u})),s+=1;let{failureIndex:S,results:y}=await Aw(t,e,g.results,{addIndices:n,includeDomState:o,includeUserFacingStepReference:l,flatten:i,maxItemsFromEnd:a,indexOffset:s+m,isTopLevelResultList:!1,parentStep:g});p.push(...y),S!==void 0?d=S:g.status==="FAILED"&&(d=h),s+=y.length,p.push(Cd(g,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:"end"}))}else p.push(Cd(g,{index:n?s+m:void 0,includeDomState:o,includeUserFacingStepReference:l,parentStep:u,header:void 0}));break}default:return(y=>{throw new Error("You missed a case in the switch above")})(g)}}return{results:p,failureIndex:d}}async function os(t,e,r,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,includeUserFacingStepReference:s,flatten:c=!0,maxItemsFromEnd:l=20}){let u=await Aw(t,e,r,{addIndices:o,includeUserFacingStepReference:s,includeDomState:a,flatten:c,maxItemsFromEnd:l,indexOffset:0}),{results:d}=u,{failureIndex:p}=u;p!==void 0&&d.length>0&&(d=d.slice(0,p+1));let m=[],g=0;if(l!==void 0&&d.length>l&&(g=d.length-l),p!==void 0&&p<d.length-1&&t.warn({failureIndex:p,flattenedResultsLength:d.length,lastIndex:d.length-1,isLastIndex:p===d.length-1,offset:g},"PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible"),p!==void 0&&g>p)throw new Error("Failure index is out of bounds");for(let h=g;h<d.length;h++){let f=d[h],S={description:f.description,startedAt:f.startedAt,finishedAt:f.finishedAt,beforeUrl:f.beforeUrl,afterUrl:f.afterUrl,elementInteracted:f.elementInteracted,userFacingStepReference:f.userFacingStepReference,message:f.message,pageState:f.pageState,index:f.index},y,E;(n===void 0||n>0&&h>=d.length-n)&&(f.afterSnapshot&&(E=await bw(t,e,f.afterSnapshot)),i&&f.beforeSnapshot&&(y=await bw(t,e,f.beforeSnapshot))),S.beforeScreenshot=y,S.afterScreenshot=E,m.push(S)}return{results:m,failureIndex:p!==void 0?p-g:void 0}}function is({json:t,keysToRedact:e,maxJsonStringSize:r}){try{if(!t)return t;if(typeof t=="string")return tt(t,r??2e4);if(typeof t=="object"){let{jsonString:n}=vw(JSON.stringify(t,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),r??2e4);return JSON.parse(n)}return t}catch{return t}}function sf(t,e){for(let r=0;r<t.length;r++){let n=t[r];try{if(n.data){let{jsonString:o}=vw(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.details&&(n.details=void 0),n.type){case"PRESET_ACTION":Tw(n);break;case"CONDITIONAL":n.assertionResult&&Tw(n.assertionResult),sf(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{sf(n.results,e);break}default:return(i=>{throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")})(n)}}}function Tw(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function _d(t,e){let r=cz(t);if(sf(r,e),r.length>yw)return e.error("Results too long, truncating before insertion"),r.slice(r.length-yw,r.length);let n=JSON.stringify(r);if(n.length>Ew)for(e.error({serializedLength:n.length,resultsArrayLength:r.length},"Database content violation: results too large, truncating before insertion");n.length>Ew;)r.splice(0,1),n=JSON.stringify(r);try{return It.array().parse(JSON.parse(n))}catch(o){throw e.error({serialized:n,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as Vge}from"lodash-es";var mz=/^(?!.*\S+\s+\S+).*$/,hz=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,gz=/style="([^"]*)/g,fz=/data-[\w-]+/g,Sz=t=>{switch(t.type){case"AI_ASSERTION":return{type:t.type,assertion:t.assertion};case"DRAG":if(t.fromTarget.type==="description")return{type:t.type,description:t.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(t.target?.type==="description")return{type:t.type,description:t.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function ww(t){let e=Sz(t),r=e.type==="AI_ASSERTION"?e.assertion:e.description;return!r||r==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:mz.test(r)&&hz.test(r)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:gz.test(r)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:fz.test(r)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(r)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}import{diff as yz}from"deep-object-diff";import{diff as xw}from"deep-object-diff";import{cloneDeep as Cw}from"lodash-es";import{v4 as lf}from"uuid";async function it(t){let e=new Map,r=new Set,n=_o.parse({steps:t.stepLists.steps??[],beforeSteps:t.stepLists.beforeSteps??void 0,afterSteps:t.stepLists.afterSteps??void 0}),o=Cw(n.steps),i=await Fi({...t,steps:o,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:r}),a={stepsToSave:{steps:i.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:i.cachesToSave,moduleUpdates:i.moduleUpdates};for(let s of["beforeSteps","afterSteps"]){let c=Cw(n[s]);if(!c)continue;let l=await Fi({...t,steps:c,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:r});a.cachesToSave.push(...l.cachesToSave),a.moduleUpdates.push(...l.moduleUpdates),a.stepsToSave[s]=l.stepsToSave}return a}async function Fi({steps:t,...e}){let{seenModules:r,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of t)switch(delete u.index,delete u.aiSuggested,u.id=c?lf():u.id,u.type){case"PRESET_ACTION":{let p=u.command;p.id=c?lf():p.id,"cache"in p&&p.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(tf({id:p.id,orgId:n.orgId,testId:n.testId,value:Zn.parse(p),moduleIdParents:o,moduleStepParents:i}))),delete p.cache),p.thoughts&&delete p.thoughts,l.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?lf():u.id,m=u.moduleId;a.has(m)?m=a.get(m):s!==void 0&&(m=await s(u),a.set(u.moduleId,m));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await Fi({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(f),l.cachesToSave=l.cachesToSave.concat(g),r.has(m)||(r.add(m),l.moduleUpdates.push({...fr.parse(u),steps:Ze.array().parse(h),moduleId:m}));let S=sn.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});l.stepsToSave.push(S);break}case"AI_ACTION":{if(!u.steps){l.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await Fi({...e,steps:u.steps});try{u.steps=Ar.array().parse(p)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}l.stepsToSave.push(u),l.cachesToSave=l.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let g of u.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:S}=await Fi({...e,steps:g.steps});p.push({...g,steps:h}),l.cachesToSave=l.cachesToSave.concat(f),l.moduleUpdates=l.moduleUpdates.concat(S)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await Fi({...e,steps:u.elseSteps});m.elseSteps=g,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(f)}l.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:g}=await Fi({...e,steps:u.steps}),h={...u,steps:p};l.moduleUpdates=l.moduleUpdates.concat(g),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(m);break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(u)}return l}async function Md({logger:t,cacheStorage:e,orgId:r,testId:n,originalStepsWithCaches:o,updatedStepsWithCaches:i}){let a=xw(o,i);if(Object.keys(a).length!==0){t.debug("Updating step caches post-success");try{let{cachesToSave:s}=await it({stepLists:i,cacheCreationParams:{testId:n,orgId:r}});await e.saveStepCacheEntries({logger:t,testId:n,entries:s})}catch(s){t.error({err:s},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Pd({logger:t,cacheStorage:e,orgId:r,testId:n,originalStepsWithCaches:o,updatedStepsWithCaches:i}){let a=xw(o,i);if(Object.keys(a).length===0)return;t.debug("Updating memory post-run failure");let s={};for(let u of["steps","beforeSteps","afterSteps"]){let d=o[u];if(!d||!d.length)continue;let p=UA({steps:d});for(let[m,g]of Object.entries(p))s[m]=g}let{cachesToSave:c}=await it({stepLists:i,cacheCreationParams:{testId:n,orgId:r}});t.debug({newEntries:c.length,originalCaches:Object.keys(s).length},"Comparing caches for memory pruning");let l=BA({newEntries:c,originalCachesMap:s,logger:t});if(l.length){t.debug({prunedCaches:l},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:t,testId:n,entries:c})}catch(u){t.error({err:u},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}async function Mw(t,e){let[r,n]=await Promise.all([it({stepLists:{beforeSteps:t.beforeSteps??[],steps:t.steps??[],afterSteps:t.afterSteps??[]}}),it({stepLists:{beforeSteps:e.beforeSteps??[],steps:e.steps??[],afterSteps:e.afterSteps??[]}})]),o=[],i=[],a=["steps","beforeSteps","afterSteps"];for(let s of a){let c=r.stepsToSave[s]??[],l=n.stepsToSave[s]??[];Ez(c,l,s,o,i)}return{additions:o,deletions:i}}function _w(t){let e=new Map;for(let r=0;r<t.length;r++){let n=t[r];n&&e.set(n.id,{step:n,index:r})}return e}function Ez(t,e,r,n,o){let i=_w(t),a=_w(e);for(let[s,{step:c,index:l}]of a){let u=i.get(s);if(!u)n.push({index:l,section:r,step:c});else{let d=yz(u.step,c);Object.keys(d).length>0&&(n.push({index:l,section:r,step:c}),o.push({index:u.index,section:r,step:u.step}))}}for(let[s,{step:c,index:l}]of i)a.has(s)||o.push({index:l,section:r,step:c})}function Pw(t,e){if(!(!t.envs||!t.envs.length)){for(let r of t.envs){let n=r;e in r&&(n[e]&&(r.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}t.envs.some(r=>r.default)||(t.envs[0].default=!0)}}import{cloneDeep as Iw}from"lodash-es";import{z as bz}from"zod";async function Ow({rawSteps:t,metadata:e,logger:r,callbacks:n}){Pw(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await Id({rawSteps:t.steps,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o}),s={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let l=t[c];if(!l)continue;let{resolvedSteps:u}=await Id({rawSteps:l,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o});s[c]=u}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function Ui(t,e,r){let{newVersion:n,steps:o}=await rs({metadata:t,steps:e,logger:r});try{return{steps:Ze.array().parse(o),newVersion:n}}catch(i){let a=new Co(`Failed to parse test steps while migrating test: ${i}`,t.id,"entity",{cause:i});throw i instanceof bz.ZodError?(a.zodIssues=i.issues,r.error({type:"zod",zodIssues:i.issues,newVersion:n,id:t.id},"Failed to parse test steps while migrating test")):r.error({err:i,newVersion:n,id:t.id},"Failed to parse test steps while migrating test"),a}}async function Id({rawSteps:t,migrationMetadata:e,logger:r,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await Ui(e,t,r),s=[];for(let c of a)s.push(await $l({step:c,callbacks:n,logger:r,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function $l({step:t,callbacks:e,logger:r,resolvedModuleCache:n}){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":{let c=t.moduleId,l=n[c];if(l)return{...Iw(l),...t,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:r});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await rs({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:r}),m;try{m=Ze.array().parse(p)}catch(f){throw r.error({type:"zod",err:f,steps:p,newVersion:d,id:c},"Module failed to parse"),f}let g;try{g=await Promise.all(m.map(f=>$l({step:f,callbacks:e,logger:r,resolvedModuleCache:n})))}catch(f){throw r.error({err:f,...t},`Failed to recursively resolve module '${u.name}': ${f}`),f}let h={...u,steps:g};return n[c]=Iw(h),{...h,...t,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of t.blocks){let l=[];for(let u of c.steps)l.push(await $l({step:u,callbacks:e,logger:r,resolvedModuleCache:n}));o.push({...c,steps:l})}let i;if(t.elseSteps){i=[];for(let c of t.elseSteps)i.push(await $l({step:c,callbacks:e,logger:r,resolvedModuleCache:n}))}return{...t,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of t.steps)a.push(await $l({step:c,callbacks:e,logger:r,resolvedModuleCache:n}));return{...t,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{cloneDeep as Tz}from"lodash-es";import{stringify as Lw}from"yaml";async function Nw({test:t,processedModuleNames:e=new Set,createNewCacheIds:r=!1}){let n={id:t.id,name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:t.schemaVersion,advanced:t.advanced,retries:t.retries,envs:t.envs,disabled:t.disabled,labels:t.labels},o={},i=await vz({originalStepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:r}),a={fileType:Se.TEST,...n,beforeSteps:i.beforeSteps&&i.beforeSteps.length>0?i.beforeSteps:void 0,steps:i.steps,afterSteps:i.afterSteps&&i.afterSteps.length>0?i.afterSteps:void 0};return{test:Lw(a),modules:o}}async function vz({originalStepLists:t,modules:e,processedModuleNames:r,createNewCacheIds:n}){let o=Tz(t);Object.values(o).forEach(s=>{Rz(s??[])});let{stepsToSave:i,moduleUpdates:a}=await it({stepLists:o,createNewCacheIds:n});for(let s of a)r.has(s.name)||(e[s.name]=Az(s),r.add(s.name));return i}function Rz(t){ki({steps:t,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function Az(t){let e=fr.parse(t),r={fileType:Se.MODULE,...e,schemaVersion:_e,steps:t.steps};return Lw(r)}async function le(t,e){if(!(t<=0))return new Promise((r,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),r()},t);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function Wl({promiseGenerator:t,signal:e,codePath:r,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:r,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${r})`)},5e3);return new Promise((s,c)=>{function l(){clearInterval(a),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",l,{once:!0}),(async()=>{try{s(await t())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function ql({promiseGenerator:t,timeoutMs:e,codePath:r,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",s),!i&&a.abort()},e);o?.addEventListener("abort",s,{once:!0});try{return await Wl({promiseGenerator:t,signal:a.signal,codePath:r,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function Dw(t){let e;return t>10*60*1e3?e=2*60*1e3:t>60*1e3?e=20*1e3:t>10*1e3?e=2*1e3:e=1e3,e}function Od(t){let e=[];for(let r of t)switch(r.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(r);break;case"RESOLVED_MODULE":{let n={...r,type:"MODULE"};e.push(sn.parse(n));break}case"SECTION":{let n={...r,steps:Od(r.steps)};e.push(Ze.parse(n));break}case"CONDITIONAL":{let n={...r,blocks:r.blocks.map(o=>({assertion:o.assertion,steps:Od(o.steps)})),elseSteps:r.elseSteps?Od(r.elseSteps):void 0};e.push(bi.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Ld(t){return Od([t])[0]}import wz from"picomatch";var Nd=(t,e,r)=>{r?.caseInsensitive&&(t=t.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=r?.caseInsensitive?e.url.toLowerCase():e.url;n=t.includes(o);break}case"GLOB":{let o=r?.caseInsensitive?e.glob.toLowerCase():e.glob;n=t===e.glob||wz(o)(t);break}case"REGEX":{n=new RegExp(e.regex).test(t);break}case"DOMAIN":{let o=r?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(t).hostname===o;break}}return r?.negated?!n:n},Dd=(t,e)=>{try{let{hostname:r,pathname:n}=new URL(t),{hostname:o,pathname:i}=new URL(e);return r!==o||n!==i}catch{return!1}},as=t=>{try{return new URL(t),!0}catch{return!1}},kw=t=>!t.toLowerCase().startsWith("http"),ss=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function Bi(t,e){try{return!!new URL(t).origin.trim()}catch(r){return e?.error({url:t,err:r},"Invalid URL in check"),!1}}async function Cz(t){let{logger:e,browserStateStorage:r,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:s,disableCache:c}=t,l=[];if(o.length>0){let{results:d}=await os(e,r,o,{numStepsWithScreenshots:s,addIndices:!1,includeUserFacingStepReference:!0,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});l=d}return await n.getTestResultClassification({results:l,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1,loggerTags:je(e)})}async function Fw(t){let{logger:e,browserStateStorage:r,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:s,numStepsWithScreenshots:c,disableCache:l}=t,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[xd("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=xd("teardown",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...u,m,...o?.afterResults??[]]}else if(u.length<20){let d=(o?.beforeResults??[]).at(-1),p=u.at(0),m=xd("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!r||!u||u.length===0)return{};try{let d=await Cz({logger:e,browserStateStorage:r,generator:n,results:u,error:a,maxItemsFromEnd:s,numStepsWithScreenshots:c,disableCache:l});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}import{v4 as Uw}from"uuid";function cf(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var kd=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:r,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=r,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[r.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:cf({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(Sv(e.type)){this.creditsUsedV2+=1;return}let r=gg(e.type);if(this.creditsUsedV1+=r??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=fg(e.command);this.creditsUsedV1+=n??0}}async flush(e){this.creditsUsedV1>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:Uw(),properties:cf({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:Uw(),properties:cf({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(r=>e.error({err:r},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as xz}from"lodash-es";function Fd(t,e){if(t.length===0)return`${e}: (no steps)`;let r=_z(t);r.forEach((o,i)=>{let a=o;a.index=i});let n=["```json",JSON.stringify(r,null,2),"```"].join(`
42
42
  `);return`${e}:
43
- ${n}`}function _z(t){let e=xz(t);return ki({steps:e,earlyStop:!1,onPresetAction:r=>{uf(r);let n;if(pu(r.command)&&r.command.cache!==void 0){let i=Pz(r.command.cache);i&&"target"in i&&(n=i.target)}let o=r.command;return n!==void 0?o.cache=n:delete o.cache,o.thoughts&&delete o.thoughts,delete o.id,"index"in r&&delete r.index,!1},onConditional:r=>(uf(r),!1),onSimpleStepContainer:r=>{if(r.type==="AI_ACTION"){let n=r,o=r.text;return Object.keys(n).forEach(i=>{delete n[i]}),n.type="AI_ACTION_DYNAMIC",n.text=o,!1}if(uf(r),r.type==="RESOLVED_MODULE"){let n=r;delete n.cacheConfig,delete n.enabled,delete n.defaultCacheKey,delete n.defaultCacheTtl,delete n.defaultCacheAllInvocations,delete n.autoAuth,delete n.advanced}return!1}}),e}function uf(t){let e=t;delete e.aiSuggested,delete e.id,delete e.retries,delete e.skipped}function Mz(t){return t.selector?t.selector:t.generatedSelectors?.[0]}function df(t){let e=Mz(t),r=t.nodeOnlySerializedHtml,n={};return e&&(n.selector=e),r&&(n.nodeOnlySerializedHtml=r),Object.keys(n).length?n:void 0}function Pz(t){if(!t)return;let e={};if("target"in t)return{target:df(t.target)};if("fromTarget"in t||"toTarget"in t){let r=t.fromTarget?df(t.fromTarget):void 0,n=t.toTarget?df(t.toTarget):void 0;return r&&(e.fromTarget=r),n&&(e.toTarget=n),Object.keys(e).length?e:void 0}}function Go({orgId:t,client:e,gitMetadata:r,regenerateCache:n,alwaysSaveCache:o,noCache:i,bustOldestCachePercentage:a}){return i?new sd:new pf(t,e,r,{regenerateCache:n,alwaysSaveCache:o,bustOldestCachePercentage:a})}var pf=class{constructor(e,r,n,o){this.orgId=e;this.client=r;let{regenerateCache:i,alwaysSaveCache:a,bustOldestCachePercentage:s}=o,{gitBranchName:c,gitProtectedBranches:l}=n;this.cacheHeaders=Og(n),this.readCaches=!i;let u=c&&l.includes(c);a||!u?this.writeCaches=!0:this.writeCaches=!1,u||(this.bustOldestCachePercentage=s)}cacheHeaders;readCaches;writeCaches;bustOldestCachePercentage;async saveStepCacheEntries({entries:e,testId:r,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:r},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}let{steps:r,beforeSteps:n,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}if(this.bustOldestCachePercentage!==void 0){let s=Object.entries(i).map(([u,d])=>({key:u,time:d.value.cache?.updatedAt?.getTime()??0}));s.sort((u,d)=>u.time-d.time);let c=s.length,l=Math.max(1,Math.floor(c*this.bustOldestCachePercentage/100));s.slice(0,l).forEach(({key:u})=>{delete i[u]}),e.logger.info({nCachesToBust:l,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:c},"Busted oldest caches")}for(let s of[r,n,o])s&&ts({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await it({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import Iz from"path";var Oz=new md(30,60*1e3),ff="https://api.momentic.ai",hf,zw=t=>{ff=t},Cr=()=>ff,Hw=()=>hf;var ls,gf,Bd,Gw=async t=>{if(hf&&ls&&Bd)return ls;let e=new et({baseUrl:ff,apiKey:t,logger:b});hf=e;try{let r=await e.getAuthInfo();return ls=r.orgId,gf=r.userId,Bd=t,ls}catch(r){throw new Error(`Error checking API key against server: ${r}`)}},xt=()=>{if(!ls)throw new Error("Your organization ID is invalid.");return ls},jo=()=>{if(!gf)throw new Error("Your user ID is invalid.");return gf},xr=()=>{if(!Bd)throw new Error("Your API key is invalid.");return Bd},Sf,mf,zd=(t,e)=>{Sf=t,mf?.abort(),mf=new AbortController;let r=mf.signal,n=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let i=Iz.resolve(t.rootDir,o.envFile);try{if(Ud.lstatSync(i).isSymbolicLink())return;Ud.existsSync(i)&&n.push(i)}catch(a){b.warn({err:a},`Failed to check if env file ${i} exists`)}});try{Lz({filesToWatch:n,revalidator:e,signal:r,project:t})}catch(o){b.error({err:o},"Failed to start config file watchers")}},me=()=>Sf;function Lz({filesToWatch:t,revalidator:e,signal:r,project:n}){b.debug("Starting watch on the following files:"),t.forEach(o=>{b.debug(`- ${o}`)}),t.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(Oz.increment("setLocalProject")&&b.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),Sf=await Promise.resolve(e(n.configFilePath)))};Ud.watchFile(o,{persistent:!1},i);let a=()=>{Ud.unwatchFile(o,i),r.removeEventListener("abort",a)};r.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Oe(t){return function(...e){let r=e[e.length-1],n=t(...e);Promise.resolve(n).catch(r)}}var Yl=Nz();function Kl(t){let e=me(),r=Dt.dirname(e.configFilePath);return Dt.join(r,...t)}function kz(t){let e=me(),r=Dt.dirname(e.configFilePath),n=Dt.relative(r,t);return n?n.split(Dt.sep):[]}function Fz(t,e){let r=dr.statSync(t),n=kz(t);return Ag.parse({name:e,absolutePath:t,relativePath:n.join(Dt.sep),pathSegments:n,isDirectory:r.isDirectory(),size:r.size,createdAt:r.birthtime,modifiedAt:r.mtime,accessedAt:r.atime})}Yl.post("/",Oe(async(t,e,r)=>{let n;try{n=Jv.parse(t.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Kl(n);if(!dr.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(Dt.sep)}`});return}if(!dr.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Dt.sep)}`});return}let a=me(),s=Array.from(a.config.exclude??[]).concat(rd),l=Dz("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=Dt.join(o,d);return Fz(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Yl.put("/",Oe(async(t,e,r)=>{let n;try{n=Qv.parse(t.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Kl(n);if(dr.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(Dt.sep)}`,pathSegments:n});return}dr.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(Dt.sep)}`,pathSegments:n};e.status(201).json(i)}));Yl.patch("/",Oe(async(t,e,r)=>{let n,o;try{let l=Zv.parse(t.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=Kl(n),a=Kl(o);if(!dr.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(Dt.sep)}`});return}if(dr.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(Dt.sep)}`});return}let s=Dt.dirname(a);dr.existsSync(s)||dr.mkdirSync(s,{recursive:!0}),dr.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(Dt.sep)} to ${o.join(Dt.sep)}`,pathSegments:o};e.status(200).json(c)}));Yl.delete("/",Oe(async(t,e,r)=>{let n,o=!0;try{let c=eR.parse(t.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=Kl(n);if(!dr.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(Dt.sep)}`,pathSegments:n});return}if(!dr.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Dt.sep)}`});return}if(o)dr.rmSync(i,{recursive:!0,force:!0});else{if(dr.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}dr.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var yf=Yl;import{Router as WH}from"express";import{diff as Hz}from"deep-object-diff";import pn from"fs";import zi from"path";import cs from"yaml";import{z as $w}from"zod";import{execSync as Uz}from"child_process";function co(t,e){let r=e.hooks?.postSave;if(!r)return;let n;r.includes("$1")?n=r.replaceAll("$1",t):n=`${r} ${t}`,b.debug({postSaveCommand:n},"Executing post-save hook command");try{Uz(n,{encoding:"utf-8"})}catch(o){b.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as jw}from"deep-object-diff";import Nn from"fs";import{cloneDeep as Bz}from"lodash-es";import Xl from"path";import{v4 as zz}from"uuid";import Jl from"yaml";function _r({content:t,schemaVersion:e,momenticFiles:r,project:n,forceSaveOnNoDiffs:o}){let i=r.modules[t.moduleId]?.fullFilePath;if(!i||!Nn.existsSync(i))throw new Error(`Tried to update module ${t.moduleId} that could not be found on disk`);let a=Nn.readFileSync(i,"utf-8"),s=Jl.parse(a),c;if(t.name&&t.name!==s.name){let m=`${ze(t.name)}.module.yaml`;if(c=Xl.join(Xl.dirname(i),m),Nn.existsSync(c))throw new Error(`A conflicting file '${t.name}' already exists at path '${c}'`)}let l={...t,schemaVersion:e},u=Ln({fileType:Se.MODULE,...xg.parse(l),steps:Qe.array().parse(t.steps)}),d=jw(u,s);if(d&&Object.keys(d).length===0&&!o){b.debug(`Skipping save for module ${t.moduleId} since there are no changes`);return}let p=Jl.stringify(u);Nn.writeFileSync(i,p,"utf-8"),c&&Nn.renameSync(i,c),co(c||i,n.config)}function Vw({moduleId:t,content:e,momenticFiles:r,project:n,logger:o}){let i=r.modules[t]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${t} that could not be found on disk`);let a=uo(i,o),s={...a,...e},c=Ln({fileType:Se.MODULE,...xg.parse(s),steps:a.steps}),l=jw(c,a);if(l&&Object.keys(l).length===0){b.debug(`Skipping save for module ${t} since there are no changes`);return}let u=Jl.stringify(c);Nn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${ze(e.name)}.module.yaml`;if(d=Xl.join(Xl.dirname(i),p),Nn.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);Nn.renameSync(i,d)}co(d||i,n.config)}async function Hd({name:t,description:e,enabled:r,steps:n,folder:o,project:i}){let a=ze(t),s=Xl.join(o,`${a}.module.yaml`),c=zz(),{stepsToSave:l}=await it({stepLists:{steps:n}}),u={fileType:Se.MODULE,schemaVersion:_e,moduleId:c,name:t,description:e,enabled:r,steps:l.steps},d=Jl.stringify(u);return Nn.writeFileSync(s,d,"utf-8"),co(s,i.config),{moduleId:c,name:t,description:e,enabled:r,steps:n}}function uo(t,e){let r=Nn.readFileSync(t,"utf-8"),n=Jl.parse(r);try{return sg.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:t,moduleContents:r},`${t} does not parse as a valid Momentic module`),o}}async function dn(t,e,r,n){let o=uo(t.fullFilePath,r),{resolvedSteps:i}=await Id({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:r,callbacks:{onFetchModule:async({id:s})=>{let c=e.modules[s]?.fullFilePath;if(c)return uo(c,r)}}}),a={...o,steps:i};return n&&(n[t.id]=Bz(a)),a}async function Gd(t,e){let r={};return await Promise.all(Object.values(t.modules).map(async n=>{await dn(n,t,e,r)})),Array.from(Object.values(r))}async function Ww({test:t,name:e,folder:r}){let n=await Nw({test:t});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${ze(e)}.test.yaml`,a=zi.join(r,i);return pn.writeFileSync(a,n.test,"utf-8"),a}function Ef(t,e,r){let n=zi.join(r.rootDir,t);if(!pn.existsSync(n))throw new Error(`Test not found at path '${t}' in project '${r.rootDir}'`);let o=pn.readFileSync(n,"utf-8"),i=cs.parse(o),a,s;if(e.name&&e.name!==i.name){let p=`${ze(e.name)}.test.yaml`;if(a=zi.join(zi.dirname(t),p),s=zi.join(r.rootDir,a),pn.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let c={...i,...e},l=Gr.parse(c),u={fileType:Se.TEST,...Gr.parse(l),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=cs.stringify(u);return pn.writeFileSync(n,d,"utf-8"),s&&pn.renameSync(n,s),co(n,r.config),{newRelativeTestPath:a}}function Er({relativeTestPath:t,steps:e,schemaVersion:r,project:n,forceSaveOnNoDiffs:o}){let i=zi.join(n.rootDir,t);if(!pn.existsSync(i))throw new Error(`Test not found at path '${t}' in project '${n.rootDir}'`);let a=pn.readFileSync(i,"utf-8"),s=cs.parse(a),c=Gr.parse({...s,schemaVersion:r}),l=Qe.array().or($w.undefined()).parse(e.beforeSteps),u=Qe.array().parse(e.steps),d=Qe.array().or($w.undefined()).parse(e.afterSteps),p=Ln({fileType:Se.TEST,...c,beforeSteps:l&&l.length>0?l:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=Hz(p,s);if(m&&Object.keys(m).length===0&&!o){b.debug(`Skipping save for test ${c.name} since there are no changes`);return}let g=cs.stringify(p);pn.writeFileSync(i,g,"utf-8"),b.debug(`Saving test ${c.name} to ${i}`),co(i,n.config)}function Ql(t,e){let r=zi.join(e.rootDir,t);if(!r)throw new Error(`Could not find test with path ${t} in Momentic project (${e.rootDir})`);let n;try{n=pn.readFileSync(r,"utf8"),n=n.replace(/\r\n|\r/g,`
44
- `)}catch(i){throw new Error(`Could not read test file ${r}: ${i}`)}let o;try{o=cs.parse(n)}catch(i){throw new Error(`Could not parse test file ${r} as YAML: ${i}`)}return Xt.parse(o)}function Hi(t,e,r){let n=r.project.rootDir,o;try{o=pn.readFileSync(t,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=cs.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${t} is missing steps`);return i}async function pt(t,e,r){let n=Hi(t,e,r),o;try{o=Gr.parse(n)}catch(a){throw new Error(`Test ${t} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await Ow({rawSteps:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:s})=>{let c=r.modules[a]?.fullFilePath;if(c)return uo(c,s)}}});return i}import Gz from"@dotenvx/dotenvx";import jz from"fs";import qw from"path";function jd(t,e){return(t.config.environments??[]).map(r=>Gi(r.name,t,e))}function Kw(t){return t.includes("${")?t.replace(/\$\{([^}]+)\}/g,(e,r)=>{let n=r.match(/^([A-Za-z_][A-Za-z0-9_]*)(?:(:-|-)([\s\S]*))?$/);if(!n)return process.env[r]||"";let o=n[1];if(!o)return"";let i=n[2],a=n[3],s=process.env[o];return i===":-"?s&&s!==""?s:a||"":i==="-"?s!==void 0?s:a||"":s||""}):t}function Vz(t){let{envVariables:e,project:r}=t;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let s=Kw(i);s&&(n[o]=s);continue}let a;try{a=jz.readFileSync(qw.resolve(r.rootDir,i.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${s}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${s}`)}else n[o]=a}return Object.keys(n).length>0&&b.debug(n,"Set environment variables with interpolation from project configuration"),n}function $z(t){let{project:e,envFile:r,logger:n}=t,o={};if(!r)return o;let i=Gz.config({path:qw.resolve(e.rootDir,r),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug(o,"Set environment variables from .env file"),o}function Gi(t,e,r){let n=(e.config.environments??[]).find(c=>c.name===t);if(!n)throw new Error(`Environment ${t} not found in local project configuration file`);if(!n.baseUrl)throw new Error(`Browser environment ${t} does not have a baseUrl configured`);let o={[Rt]:Kw(n.baseUrl)},i=Vz({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=$z({project:e,envFile:n.envFile,logger:r});return Object.assign(o,a),n.inheritFromShell&&(r.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:t,variables:o,browser:n.browser}}import{existsSync as qz,readFileSync as Kz,readdirSync as Yz,writeFileSync as Xz}from"fs";import{glob as Jz}from"glob";import ji,{dirname as Yw}from"path";import{cwd as Tf}from"process";import Xw from"yaml";import{z as We}from"zod";import Wz from"zod";var Vd=["**/*.test.yaml","**/*.module.yaml"],bf=Wz.string().refine(t=>/^[a-zA-Z0-9-]+$/.test(t)),$d=15;var us="momentic.config.yaml",vf="momentic.workspace.yaml",Qz=We.object({projects:We.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),Zz=We.union([We.string(),We.object({fromFile:We.string(),json:We.boolean().optional()})]),eH=We.object({name:bf,baseUrl:We.string().optional().describe("Optional for mobile tests"),envFile:We.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:We.record(We.string(),Zz).optional(),inheritFromShell:We.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Ai.optional().describe("NB: most things should use project-level configuration only")}),tH=We.object({postSave:We.string().optional()}),rH=We.object({name:bf,include:We.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:We.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:We.string().optional(),reporterDir:We.string().optional(),outputDir:We.string().optional(),recordVideo:We.boolean().optional(),retries:We.number().optional().describe("number of retries per test"),parallel:We.number().optional().describe("degree of parallelism"),environments:We.array(eH).optional(),gitMainBranch:We.string().optional(),gitProtectedBranches:We.string().array().optional(),ai:_g.optional(),browser:Ai.optional(),emulator:dg.optional(),advanced:Mg.optional(),displayRoot:We.string().optional().describe("relative path from project root to use as the Repository root"),hooks:tH.optional()});function Jw(t,e){let r;try{r=Kz(t,"utf-8")}catch(o){b.warn(`Could not read possible Momentic ${e} file at ${t}: ${o}`);return}let n;try{if(n=Xw.parse(r),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){b.warn(`Possible Momentic ${e} file at ${t} does not parse as valid YAML: ${o}`);return}return n}function Rf(t){let e=Jw(t,"project configuration");if(e!==void 0)try{return rH.parse(e)}catch(r){b.warn(`Possible Momentic project configuration file at ${t} does not adhere to the required schema: ${r}`);return}}function nH(t){let e=Jw(t,"workspace configuration");if(e!==void 0)try{return Qz.parse(e)}catch(r){b.warn(`Possible Momentic workspace configuration file at ${t} does not adhere to the required schema: ${r}`);return}}function oH(){let t=[],e=Tf(),r=ji.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=ji.basename(e);if(td.includes(i))return b.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),t;for(let a of Yz(e))if(a.endsWith(us)){let s=ji.join(e,a),c=Rf(s);c&&t.push({configFilePath:s,config:c,rootDir:Yw(s)})}if(t.length)return t;if(e=ji.dirname(e),e===r)break}return t}async function _t(t={}){let{configFilePath:e,nameFilter:r}=t,n=await Af(e);if(r&&(n=n.filter(o=>o.config.name===r)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
45
- ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return b.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function iH(t){let e=nH(t);if(!e||!e.projects||!e.projects.length)return;let r=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${us}`)),n=AbortSignal.timeout(2e3),o;try{o=await Jz(r,{absolute:!1,cwd:Tf(),dotRelative:!1,maxDepth:$d,nodir:!0,signal:n})}catch(a){throw b.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${vf} is misconfigured.`),a}let i=[];for(let a of o){let s=ji.join(Tf(),a),c=Rf(s);c&&i.push({configFilePath:s,config:c,rootDir:Yw(s)})}return i}async function Af(t){if(t){t=ji.resolve(t);let r=Rf(t);return r||(console.error(`No valid Momentic project file found at ${t}.`),process.exit(1)),[{config:r,configFilePath:t,rootDir:ji.dirname(t)}]}if(qz(vf)){let r=await iH(vf);if(r)return r}return oH()}function $o(t,e){let r=Xw.stringify(t);Xz(e,r)}import Zw from"fs";import{glob as aH}from"glob";import Zl from"path";import sH from"yaml";import{z as Qw}from"zod";var eC=!1,lH=Qw.object({fileType:Qw.nativeEnum(Se)});async function ee(t,e=!1){let r={project:t,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=t.config.include??Vd,o=Array.from(t.config.exclude??[]).concat(rd),i=AbortSignal.timeout(5e3),a;try{a=await aH(n,{absolute:!1,cwd:t.rootDir,ignore:o,dotRelative:!1,maxDepth:$d,nodir:!0,signal:i})}catch(s){throw b.error({err:s},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:s})}for(let s of a){let c=cH(t.rootDir,s,r,e?Pn:b);c&&(r.duplicateEntities[c.id]=c.paths)}return eC=!0,r}function cH(t,e,r,n){let o=Zl.join(t,e),i=uH(o,n);if(!i)return;let a=dH(i,o,n);if(!a)return;let s=lH.safeParse(a);if(s.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=pH(o,n);if(!l)return;let u=mH(e,o,l);switch(c){case Se.TEST:try{return hH(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case Se.MODULE:try{return gH(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case Se.MOBILE_TEST:try{return SH(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case Se.MOBILE_MODULE:try{return fH(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function uH(t,e){try{return Zw.readFileSync(t,"utf-8")}catch(r){e.warn(`Could not read possible Momentic file at ${t}, skipping: ${r}`);return}}function dH(t,e,r){try{let n=sH.parse(t);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){r.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function pH(t,e){try{return Zw.statSync(t)}catch(r){e.warn(`Skipping path '${t}' because it could not be stat, skipping: ${r}`);return}}function mH(t,e,r){return{relativePath:t,fullFilePath:e,platformSep:Zl.sep,fullPathSegments:e.split(Zl.sep),relativePathSegments:t.split(Zl.sep),fileName:Zl.basename(e),lastModified:r.mtime,createdAt:r.birthtime}}function hH(t,e,r,n,o){let i=Gr.parse(t),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,n]}}return e.tests[i.id]={type:Se.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...r},a}function gH(t,e,r,n,o){let i=fr.parse(t),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:Se.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...r};let s=r.fileName.replace(".module.yaml","");return!eC&&ze(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function fH(t,e,r,n,o){let i=Xu.parse(t),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=r.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:Se.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...r},a}function SH(t,e,r,n,o){let i=Va.parse(t),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=r.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:Se.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...r},a}import ds from"fs";import wf from"path";import{z as Cf}from"zod";var tC="golden/visual-diff",rC="reports",nC="test-results";var yH=Cf.object({width:Cf.number(),height:Cf.number()}),ps=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,r){let n=wf.join(e.rootDir,e.config.goldenFileDir??tC);this.defaultGoldenScreenshotDir=n,this.regenerateGoldenFiles=r}async prepareGoldenScreenshotForComparison(e,r,n){if(r.screenshot?.data?.startsWith("https://")){let a=await fetch(r.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:r.screenshot.width,height:r.screenshot.height}}let o=r.screenshot?.data;o||(o=wf.join(this.defaultGoldenScreenshotDir,`${r.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ds.mkdirSync(wf.dirname(o),{recursive:!0}),ds.writeFileSync(o,n.buffer),ds.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(ds.existsSync(o)){let a=ds.readFileSync(o),s=yH.parse(JSON.parse(ds.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new M("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};import{execFile as EH}from"node:child_process";import{promisify as bH}from"node:util";import TH from"simple-git";var Ye=TH(),oC=bH(EH);async function vH(t){let e=await rt(t,Ye.raw(["config","--list"])),r={};if(!e)return r;for(let n of e.split(`
46
- `)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();r[i]=a}return r}async function RH(t,e,r){try{let o=r["github.user"]||void 0;if(o)return o}catch{}let n;try{if(e?.startsWith("http://")||e?.startsWith("https://"))n=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(n=e.slice(o+1,i))}}catch{}if(n=n?.toLowerCase(),!!n){try{if(e?.startsWith("git@")&&n?.includes("github")){let{stdout:o,stderr:i}=await oC("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await oC("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function AH(t,e,r){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return RH(t,e,r);if(o)return}catch{}}function Wd(t){if(t.startsWith("git@")){let e=t.split(":");if(e.length===2){let r=e[1].replace(".git","").split("/");if(r.length===2){let n=r[0],o=r[1];return`${n}/${o}`}}}else if(t.startsWith("http")||t.startsWith("https")){let r=new URL(t).pathname.split("/").filter(Boolean);if(r.length>=2){let n=r[0],o=r[1].replace(".git","");return`${n}/${o}`}}}async function rt(t,e){try{return(await e).trim()}catch(r){if(r instanceof Error&&r.message.includes("not a git repository"))return;t.error({err:r},"Failed to run git command");return}}function wH(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function CH(t){let[e,r,n]=await Promise.all([rt(t,Ye.show(["--no-patch","--format=%ci"])),rt(t,Ye.show(["-s","--pretty=%B"])),rt(t,Ye.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function xH(t){let[e,r,n]=await Promise.all([rt(t,Ye.listRemote(["--get-url","origin"])),rt(t,Ye.show(["-s","--pretty=%B"])),rt(t,Ye.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:r,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function _H(t){let[e,r,n,o]=await Promise.all([rt(t,Ye.show(["--no-patch","--format=%ci"])),rt(t,Ye.listRemote(["--get-url","origin"])),rt(t,Ye.show(["-s","--pretty=%B"])),rt(t,Ye.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??r,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),c=i?Wd(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:i,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:a?c:void 0,gitlabProjectPath:s?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function MH(t){let[e,r,n]=await Promise.all([rt(t,Ye.show(["--no-patch","--format=%ci"])),rt(t,Ye.show(["-s","--pretty=%B"])),rt(t,Ye.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Wd(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function PH(t){let[e,r,n]=await Promise.all([rt(t,Ye.show(["--no-patch","--format=%ci"])),rt(t,Ye.show(["-s","--pretty=%B"])),rt(t,Ye.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Wd(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function IH(t,e){let[r,n,o,i,a,s,c,l,u]=await Promise.all([rt(t,Ye.revparse(["HEAD"])),rt(t,Ye.revparse(["--short","HEAD"])),rt(t,Ye.revparse(["--abbrev-ref","HEAD"])),rt(t,Ye.listRemote(["--get-url","origin"])),rt(t,Ye.show(["--no-patch","--format=%ci"])),rt(t,Ye.show(["-s","--pretty=%B"])),rt(t,Ye.show(["-s","--pretty=%an"])),e?rt(t,Ye.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),vH(t)]),d=l?await rt(t,Ye.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Wd(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,S=u["user.username"]||void 0,y=await AH(t,i,u)??S??void 0;return{ciProvider:"none",gitCommitSha:r,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:y,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function OH(){let t=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:t?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:t?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function LH(t){let e=t.config.gitProtectedBranches??[];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function po(t,e){let r=wH();if(!r)return IH(t,e);switch(r){case"GithubActions":return CH(t);case"GitlabCI":return xH(t);case"CircleCI":return _H(t);case"Buildkite":return MH(t);case"AzureDevOps":return PH(t);case"GCPCloudBuild":return OH()}}async function NH(t,e,r,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(r,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){t.warn({err:i},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let i=await e.getCommitFromGitlab(r,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){t.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(r,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){t.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function DH(t,e,r,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(r,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){t.warn({err:a},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let a=await e.getCommitFromGithub(r,n,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}catch(a){t.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(r,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){t.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function kH(t,e,r){try{if(r.githubRepository){let[n,o]=r.githubRepository.split("/");return await DH(t,e,n,o,r)}else if(r.gitlabProjectPath)return await NH(t,e,r.gitlabProjectPath,r)}catch(n){t.warn({err:n},"Failed to get remote git metadata")}return r}async function Vr(t,e,r){let n=await LH(r),o=await po(t,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await kH(t,e,i);return{...n,...o,...a}}async function iC(){try{return!!(await Ye.show(["--no-patch","--format=%ci"])).trim()}catch{return null}}import{diff as Qbe}from"deep-object-diff";import{cloneDeep as eTe}from"lodash-es";import{v4 as pTe}from"uuid";import hTe from"yaml";import MTe from"yaml";import ITe from"zod";import{randomUUID as FH}from"crypto";import Wo from"fs";import ms from"path";var aC=new Set([".DS_Store","__MACOSX"]),sC={status:(t,e)=>{if(t.status===e.status)return t.status;if(t.status==="FAILED"||e.status==="FAILED")return"FAILED";if(t.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(t.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(t.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(t.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${t.status} and ${e.status}`)},startedAt:(t,e)=>t.startedAt<e.startedAt?t.startedAt:e.startedAt,updatedAt:(t,e)=>t.updatedAt>e.updatedAt?t.updatedAt:e.updatedAt,finishedAt:(t,e)=>!t.finishedAt||!e.finishedAt?new Date:t.finishedAt>e.finishedAt?t.finishedAt:e.finishedAt,gitCommitTimestamp:(t,e)=>{if(!(!t&&!e)){if(!t.gitCommitTimestamp||!e.gitCommitTimestamp||t.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${t.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return t.gitCommitTimestamp}},pipelineId:(t,e)=>t.pipelineId===e.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:t.startedAt<e.startedAt?e.pipelineId:t.pipelineId,labels:(t,e)=>{let r=new Set([...t.labels??[],...e.labels??[]]);return Array.from(r)}};function UH(t,e,r){if(sC[r]){let i=sC[r];return i(t,e)}let n=t[r],o=e[r];if(n!==o)throw new Error(`Metadata values for key "${r}" do not match: "${n}" vs "${o}"`);return n}var xf=class extends Error{constructor(e,r){let n=`${e} contains invalid Momentic results: ${r}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function lC(t,e){try{let r=ms.join(e,"metadata.json");return ld.parse(JSON.parse(Wo.readFileSync(r,"utf-8")))}catch{throw new xf(t,e)}}function cC(t,e,r){let n=FH(),o=t.child({runGroupId:n});Wo.rmSync(e,{recursive:!0,force:!0});let i=Wo.readdirSync(r).filter(c=>!aC.has(c)).map(c=>ms.join(r,c));if(i.length===0)throw new Error(`No run groups found in results path: ${r}`);Wo.mkdirSync(e,{recursive:!0});let a={...lC(r,i[0]),id:n};for(let c of i){let l=ms.join(c,"runs");if(!Wo.existsSync(l))continue;let u=lC(r,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=UH(a,u,m)}let d=Wo.readdirSync(l);for(let p of d){if(aC.has(p))continue;let m=ms.join(l,p),g=ms.join(e,"runs",p);Wo.cpSync(m,g,{recursive:!0})}}let s=ms.join(e,"metadata.json");Wo.writeFileSync(s,JSON.stringify(a,null,2))}import uC from"adm-zip";import _f from"fs";import qd from"path";function BH(t){let e=new uC,r=qd.join(t,"metadata.json"),n=ld.parse(JSON.parse(_f.readFileSync(r,"utf-8")));e.addLocalFile(r);for(let o of _f.readdirSync(qd.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new uC(qd.join(t,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(qd.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Kd(t){let{client:e,consoleLogger:r,resultsPath:n}=t;if(!_f.existsSync(n)){r.warn("Results path does not exist, skipping upload.");return}let o=new gd(e);try{let{runGroupId:i,buffer:a}=BH(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;r.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",r.error(`Failed to upload test results: ${a}.`);return}}import zH from"adm-zip";import Ht from"fs";import Mr from"path";var ec=class t{constructor(e){this.filePath=e;Ht.rmSync(this.filePath,{recursive:!0,force:!0}),Ht.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new t(Mr.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){Ht.mkdirSync(Mr.join(this.filePath,e),{recursive:!0})}readFile(e){let r=Mr.join(this.filePath,e);if(Ht.existsSync(r))return Ht.readFileSync(r)}storeFile(e){let{name:r,contents:n}=e,o=Mr.join(this.filePath,r);try{Ht.writeFileSync(o,n)}catch{}}createFileStream(e){let r=Mr.join(this.filePath,e);return Ht.createWriteStream(r)}createRunArchive(e){return new Mf(Mr.join(this.filePath,"runs"),e)}},Mf=class{constructor(e,r){this.filePath=e;this.tempPath=Mr.join(e,`temp-storage-${r}`),this.finalPath=Mr.join(e,`${r}.zip`),Ht.rmSync(this.tempPath,{recursive:!0,force:!0}),Ht.rmSync(this.finalPath,{recursive:!0,force:!0}),Ht.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let r=Mr.join(this.tempPath,e);if(Ht.existsSync(r))return Ht.readFileSync(r)}mkdir(e){Ht.mkdirSync(Mr.join(this.tempPath,e),{recursive:!0})}cd(e){return new ec(Mr.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:r,contents:n}=e,o=Mr.join(this.tempPath,r);Ht.writeFileSync(o,n)}createFileStream(e){let r=Mr.join(this.tempPath,e);return Ht.createWriteStream(r)}close(){let e=new zH;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let r=e.toBuffer();Ht.writeFileSync(this.finalPath,r),Ht.rmSync(this.tempPath,{recursive:!0,force:!0})}};import HH from"adm-zip";import{randomUUID as GH}from"crypto";import Ot from"fs";import Gt from"path";function hC(t){try{return Ot.existsSync(t)?JSON.parse(Ot.readFileSync(t,"utf-8")):void 0}catch{return}}function dC(t){return Ot.existsSync(t)?Ot.readFileSync(t,"utf-8").split(`
47
- `).map(r=>r.trim()).filter(r=>r.length>0):[]}function jH(t,e){let r=t.attemptIdToAttemptNumber.get(e);if(r)return Gt.join(t.inflatedPath,"attempts",r);let n=Gt.join(t.inflatedPath,"attempts");if(!Ot.existsSync(n))return;let o=Ot.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of o){let a=Gt.join(n,i,"metadata.json"),s=hC(a);if(typeof s!="object"||s===null)continue;let c=s.id;if(typeof c=="string"&&c===e)return t.attemptIdToAttemptNumber.set(e,i),Gt.join(n,i)}}function pC(t,e,r){let n=Gt.join(t,"attempts");if(!Ot.existsSync(n))return;let o=Ot.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of o){let a=Gt.join(n,i,"assets",`${e}.${r}`);if(Ot.existsSync(a))return a}}var Yd=class{constructor(e,r,n){this.outputDir=e;this.runId=r;this.runAttemptId=n;this.runsDir=Gt.join(e,"runs"),this.zipPath=Gt.join(this.runsDir,`${r}.zip`)}inflatedByRunId=new Map;zipPath;runsDir;ensureInflatedRun(e){let r=this.inflatedByRunId.get(e);if(r)return r;if(e!==this.runId||!Ot.existsSync(this.zipPath))return;let n=Gt.join(this.runsDir,`temp-unzipped-${e}-${GH()}`);Ot.mkdirSync(n,{recursive:!0}),new HH(this.zipPath).extractAllTo(n,!0);let i={runId:e,zipPath:this.zipPath,inflatedPath:n,attemptIdToAttemptNumber:new Map};return this.inflatedByRunId.set(e,i),i}close(){for(let e of this.inflatedByRunId.values())Ot.rmSync(e.inflatedPath,{recursive:!0,force:!0});this.inflatedByRunId.clear()}getAttemptDir(){let e=this.ensureInflatedRun(this.runId);if(e)return jH(e,this.runAttemptId)}listVideoAssetPaths(){let e=this.getAttemptDir();if(!e)return[];let r=Gt.join(e,"assets");return Ot.existsSync(r)?Ot.readdirSync(r,{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>Gt.join(r,o.name)).filter(o=>{let i=Gt.extname(o).toLowerCase();return i===".webm"||i===".mp4"}):[]}readAttemptAssetText(e,r){let n=this.getAttemptDir();if(!n)return;let o=Gt.join(n,"assets",`${e}.${r}`);if(Ot.existsSync(o))try{return Ot.readFileSync(o,"utf-8")}catch{return}}async getConsoleLogsForRunAttempt(e,r,n){if(r!==this.runId||n!==this.runAttemptId)return;let o=this.getAttemptDir();if(!o)return;let i=hC(Gt.join(o,"console.json")),a=yg.safeParse(i);return a.success?a.data:void 0}async getNetworkLogsForRunAttempt(e,r,n){if(r!==this.runId||n!==this.runAttemptId)return;let o=this.getAttemptDir();if(!o)return;let i=Gt.join(o,"assets","har-pages.log"),a=Gt.join(o,"assets","har-entries.log"),s={};for(let u of dC(i)){let d=Ol.safeParse(mC(u));d.success&&(s[d.data.id]=d.data)}let c={},l=dC(a);for(let u=0;u<l.length;u++){let d=l[u],p=Ll.safeParse(mC(d));if(!p.success)continue;let m=`${p.data.startedDateTime}-${u}`;c[m]=p.data}if(Object.keys(c).length!==0)return bg(s,c)}async getHtmlSnapshot(e,r){let n=this.readAttemptAssetText(r,"html");if(n)return n;let o=this.ensureInflatedRun(this.runId);if(!o)return;let i=pC(o.inflatedPath,r,"html");if(i)try{return Ot.readFileSync(i,"utf-8")}catch{return}}async getA11yTreeSnapshot(e,r){let n=this.readAttemptAssetText(r,"xml");if(n)return n;let o=this.ensureInflatedRun(this.runId);if(!o)return;let i=pC(o.inflatedPath,r,"xml");if(i)try{return Ot.readFileSync(i,"utf-8")}catch{return}}async getScreenshot(e,r){if(!this.ensureInflatedRun(this.runId))return;let o=this.getAttemptDir(),i=o?Gt.join(o,"assets",`${r}.jpeg`):void 0;if(i)try{return Ot.readFileSync(i)}catch{return}}};function mC(t){try{return JSON.parse(t)}catch{return}}import{hostname as VH}from"os";var $H="2.29.4",tc=Xa({app:"desktop-server",hostname:VH(),disableConsoleLogs:!0}).child({cliVersion:$H});(async()=>{try{let t=await po(tc);t.gitBranchName&&tc.addBinding("branch",t.gitBranchName)}catch{}})();var gC=WH();gC.get("/",async(t,e)=>{let r=me(),n=Hw();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Vr(tc,n,r);e.status(200).json(o)});var Pf=gC;import rY from"events";import EL,{Router as nY}from"express";import oY from"http";import iY from"path";import{Server as cK}from"socket.io";var qH=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async()=>{e.info({sessionId:n},"Cancel event received");let o=r.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},fC={event:"cancel",createHandler:qH};var KH=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async(o,i)=>{let a=r.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:l},"Fetched a11y tree from the browser"),i({a11yTree:l})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},SC={event:"fetchA11yTree",createHandler:KH};var YH=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async(o,i)=>{let a=r.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=await s.html();i({html:c})}catch(c){e.error({err:c},"Error fetching DOM from the browser"),c.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:c.message})}}},yC={event:"fetchDom",createHandler:YH};var XH=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),r.removeSession(n,e)}},EC={event:"disconnect",createHandler:XH};function mn(t){let{result:e,nestedResults:r}=t;if(!t.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=JH(r);QH(e,n,o);let i=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await ZH(i,e,n,o)}catch(a){t.logger.error({result:t.result,err:a},"Error hoisting scalar result metadata")}})())}function JH(t){let e=t[0],r;for(;;){switch(e.type){case"PRESET_ACTION":{r=e;break}case"CONDITIONAL":r=t[0];break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){r=e;break}e=e.results[0];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(r)break}let n=t[t.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:r,lastMetadata:o}}function QH(t,e,r){e&&(t.beforeUrl=e.beforeUrl),r&&(t.afterUrl=r.afterUrl,t.data=r.data,r.status!=="SUCCESS"&&(t.message=r.message))}async function ZH(t,e,r,n){await Promise.allSettled(t),r&&(e.beforeSnapshot=r.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as u1}from"crypto";import{faker as e1}from"@faker-js/faker";import t1 from"assert";import r1 from"axios";import*as n1 from"child_process";import o1 from"moment";import*as i1 from"otpauth";import a1 from"pg";async function bC(t){let e;try{e=new URL(t.url).hostname}catch{}let r=[];return t.headers.getSetCookie()?.forEach(n=>{let o=Ju(n,e);r.push(...o)}),r}function s1(t,e){if(!t&&!e)return;let r;if(t){let{url:o,options:i}=t;r=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:r,response:n}}async function l1(t,e){switch(t){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let r=[];return e.headers.forEach((o,i)=>{r.push([i,o])}),{status:e.status,headers:r,body:await e.text()}}else throw new Error("Result is not a Response object")}}var c1=Object.getPrototypeOf(async function(){}).constructor;async function TC(t,e,r){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:s}=e.bindings,c=e.tools,l={},u=(E,T)=>{o[E]=T,l[E]=T},d={},p=(E,T)=>{o[E]=T,d[E]=T},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new c1("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(r1,o1,c.fakerInstance??e1,t1,a1,m,g,i1,n1,bC,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,T=>c.sms.send(T),T=>c.sms.fetchLatest(T),c.email,c.sms,c.ai,s1(a,s),...Object.values(i??{}))),f=!0,S,y;try{let E=await $(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});S=await l1(e.options.responseSerialization??"RAW",E)}catch(E){r.error({err:E,env:o,evalCode:n},`[${t}] Error executing code: ${E}`),f=!1,E instanceof zo?y=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:y=E instanceof Error?E.message:`${E}`}return{result:S,variableUpdates:l,persistentVariableUpdates:d,success:f,error:y}}async function vC({code:t,fragment:e,context:r,localTools:n,logger:o,signal:i,timeoutMs:a=ko,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=u1(),p=await TC(d,{code:t,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...r.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return b.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as d1,randomUUID as p1}from"crypto";import m1 from"fetch-retry";var h1=m1(global.fetch,{retries:3,retryOn:function(t,e,r){return!!(e!==null||r&&r.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),RC=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,AC=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function wC({orgId:t,code:e,fragment:r,context:n,timeoutMs:o=ko,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!RC)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!AC)throw new Error("Missing lambda auth secret.");let h=d1("sha256",AC).update(t).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let S={id:p1(),orgId:t,momenticLambdaAuthHash:h,code:e,fragment:r,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(p=await $(h1(RC,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);m=void 0;break}catch(y){m=y}}if(m)throw s.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=Dv.parse(await p.json())}catch(S){throw new Error(`Code evaluation server returned invalid response: ${S}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function qo(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await wC(t);else if(t.localTools)e=await vC({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let r=`Failed to evaluate code:
43
+ ${n}`}function _z(t){let e=xz(t);return ki({steps:e,earlyStop:!1,onPresetAction:r=>{uf(r);let n;if(pu(r.command)&&r.command.cache!==void 0){let i=Pz(r.command.cache);i&&"target"in i&&(n=i.target)}let o=r.command;return n!==void 0?o.cache=n:delete o.cache,o.thoughts&&delete o.thoughts,delete o.id,"index"in r&&delete r.index,!1},onConditional:r=>(uf(r),!1),onSimpleStepContainer:r=>{if(r.type==="AI_ACTION"){let n=r,o=r.text;return Object.keys(n).forEach(i=>{delete n[i]}),n.type="AI_ACTION_DYNAMIC",n.text=o,!1}if(uf(r),r.type==="RESOLVED_MODULE"){let n=r;delete n.cacheConfig,delete n.enabled,delete n.defaultCacheKey,delete n.defaultCacheTtl,delete n.defaultCacheAllInvocations,delete n.autoAuth,delete n.advanced}return!1}}),e}function uf(t){let e=t;delete e.aiSuggested,delete e.id,delete e.retries,delete e.skipped}function Mz(t){return t.selector?t.selector:t.generatedSelectors?.[0]}function df(t){let e=Mz(t),r=t.nodeOnlySerializedHtml,n={};return e&&(n.selector=e),r&&(n.nodeOnlySerializedHtml=r),Object.keys(n).length?n:void 0}function Pz(t){if(!t)return;let e={};if("target"in t)return{target:df(t.target)};if("fromTarget"in t||"toTarget"in t){let r=t.fromTarget?df(t.fromTarget):void 0,n=t.toTarget?df(t.toTarget):void 0;return r&&(e.fromTarget=r),n&&(e.toTarget=n),Object.keys(e).length?e:void 0}}function Go({orgId:t,client:e,gitMetadata:r,regenerateCache:n,alwaysSaveCache:o,noCache:i,bustOldestCachePercentage:a}){return i?new sd:new pf(t,e,r,{regenerateCache:n,alwaysSaveCache:o,bustOldestCachePercentage:a})}var pf=class{constructor(e,r,n,o){this.orgId=e;this.client=r;let{regenerateCache:i,alwaysSaveCache:a,bustOldestCachePercentage:s}=o,{gitBranchName:c,gitProtectedBranches:l}=n;this.cacheHeaders=Og(n),this.readCaches=!i;let u=c&&l.includes(c);a||!u?this.writeCaches=!0:this.writeCaches=!1,u||(this.bustOldestCachePercentage=s)}cacheHeaders;readCaches;writeCaches;bustOldestCachePercentage;async saveStepCacheEntries({entries:e,testId:r,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:r},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}let{steps:r,beforeSteps:n,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}if(this.bustOldestCachePercentage!==void 0){let s=Object.entries(i).map(([u,d])=>({key:u,time:d.value.cache?.updatedAt?.getTime()??0}));s.sort((u,d)=>u.time-d.time);let c=s.length,l=Math.max(1,Math.floor(c*this.bustOldestCachePercentage/100));s.slice(0,l).forEach(({key:u})=>{delete i[u]}),e.logger.info({nCachesToBust:l,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:c},"Busted oldest caches")}for(let s of[r,n,o])s&&ts({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await it({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import Iz from"path";var Oz=new md(30,60*1e3),ff="https://api.momentic.ai",hf,zw=t=>{ff=t},Cr=()=>ff,Hw=()=>hf;var ls,gf,Bd,Gw=async t=>{if(hf&&ls&&Bd)return ls;let e=new et({baseUrl:ff,apiKey:t,logger:b});hf=e;try{let r=await e.getAuthInfo();return ls=r.orgId,gf=r.userId,Bd=t,ls}catch(r){throw new Error(`Error checking API key against server: ${r}`)}},xt=()=>{if(!ls)throw new Error("Your organization ID is invalid.");return ls},jo=()=>{if(!gf)throw new Error("Your user ID is invalid.");return gf},xr=()=>{if(!Bd)throw new Error("Your API key is invalid.");return Bd},Sf,mf,zd=(t,e)=>{Sf=t,mf?.abort(),mf=new AbortController;let r=mf.signal,n=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let i=Iz.resolve(t.rootDir,o.envFile);try{if(Ud.lstatSync(i).isSymbolicLink())return;Ud.existsSync(i)&&n.push(i)}catch(a){b.warn({err:a},`Failed to check if env file ${i} exists`)}});try{Lz({filesToWatch:n,revalidator:e,signal:r,project:t})}catch(o){b.error({err:o},"Failed to start config file watchers")}},me=()=>Sf;function Lz({filesToWatch:t,revalidator:e,signal:r,project:n}){b.debug("Starting watch on the following files:"),t.forEach(o=>{b.debug(`- ${o}`)}),t.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(Oz.increment("setLocalProject")&&b.warn(`A file change under the ${n.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),Sf=await Promise.resolve(e(n.configFilePath)))};Ud.watchFile(o,{persistent:!1},i);let a=()=>{Ud.unwatchFile(o,i),r.removeEventListener("abort",a)};r.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Oe(t){return function(...e){let r=e[e.length-1],n=t(...e);Promise.resolve(n).catch(r)}}var Yl=Nz();function Kl(t){let e=me(),r=Dt.dirname(e.configFilePath);return Dt.join(r,...t)}function kz(t){let e=me(),r=Dt.dirname(e.configFilePath),n=Dt.relative(r,t);return n?n.split(Dt.sep):[]}function Fz(t,e){let r=dr.statSync(t),n=kz(t);return Ag.parse({name:e,absolutePath:t,relativePath:n.join(Dt.sep),pathSegments:n,isDirectory:r.isDirectory(),size:r.size,createdAt:r.birthtime,modifiedAt:r.mtime,accessedAt:r.atime})}Yl.post("/",Oe(async(t,e,r)=>{let n;try{n=Jv.parse(t.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Kl(n);if(!dr.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(Dt.sep)}`});return}if(!dr.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Dt.sep)}`});return}let a=me(),s=Array.from(a.config.exclude??[]).concat(rd),l=Dz("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=Dt.join(o,d);return Fz(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Yl.put("/",Oe(async(t,e,r)=>{let n;try{n=Qv.parse(t.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Kl(n);if(dr.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(Dt.sep)}`,pathSegments:n});return}dr.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(Dt.sep)}`,pathSegments:n};e.status(201).json(i)}));Yl.patch("/",Oe(async(t,e,r)=>{let n,o;try{let l=Zv.parse(t.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=Kl(n),a=Kl(o);if(!dr.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(Dt.sep)}`});return}if(dr.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(Dt.sep)}`});return}let s=Dt.dirname(a);dr.existsSync(s)||dr.mkdirSync(s,{recursive:!0}),dr.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(Dt.sep)} to ${o.join(Dt.sep)}`,pathSegments:o};e.status(200).json(c)}));Yl.delete("/",Oe(async(t,e,r)=>{let n,o=!0;try{let c=eR.parse(t.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=Kl(n);if(!dr.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(Dt.sep)}`,pathSegments:n});return}if(!dr.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Dt.sep)}`});return}if(o)dr.rmSync(i,{recursive:!0,force:!0});else{if(dr.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}dr.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var yf=Yl;import{Router as WH}from"express";import{diff as Hz}from"deep-object-diff";import pn from"fs";import zi from"path";import cs from"yaml";import{z as $w}from"zod";import{execSync as Uz}from"child_process";function co(t,e){let r=e.hooks?.postSave;if(!r)return;let n;r.includes("$1")?n=r.replaceAll("$1",t):n=`${r} ${t}`,b.debug({postSaveCommand:n},"Executing post-save hook command");try{Uz(n,{encoding:"utf-8"})}catch(o){b.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as jw}from"deep-object-diff";import Nn from"fs";import{cloneDeep as Bz}from"lodash-es";import Xl from"path";import{v4 as zz}from"uuid";import Jl from"yaml";function _r({content:t,schemaVersion:e,momenticFiles:r,project:n,forceSaveOnNoDiffs:o}){let i=r.modules[t.moduleId]?.fullFilePath;if(!i||!Nn.existsSync(i))throw new Error(`Tried to update module ${t.moduleId} that could not be found on disk`);let a=Nn.readFileSync(i,"utf-8"),s=Jl.parse(a),c;if(t.name&&t.name!==s.name){let m=`${ze(t.name)}.module.yaml`;if(c=Xl.join(Xl.dirname(i),m),Nn.existsSync(c))throw new Error(`A conflicting file '${t.name}' already exists at path '${c}'`)}let l={...t,schemaVersion:e},u=Ln({fileType:Se.MODULE,...xg.parse(l),steps:Ze.array().parse(t.steps)}),d=jw(u,s);if(d&&Object.keys(d).length===0&&!o){b.debug(`Skipping save for module ${t.moduleId} since there are no changes`);return}let p=Jl.stringify(u);Nn.writeFileSync(i,p,"utf-8"),c&&Nn.renameSync(i,c),co(c||i,n.config)}function Vw({moduleId:t,content:e,momenticFiles:r,project:n,logger:o}){let i=r.modules[t]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${t} that could not be found on disk`);let a=uo(i,o),s={...a,...e},c=Ln({fileType:Se.MODULE,...xg.parse(s),steps:a.steps}),l=jw(c,a);if(l&&Object.keys(l).length===0){b.debug(`Skipping save for module ${t} since there are no changes`);return}let u=Jl.stringify(c);Nn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${ze(e.name)}.module.yaml`;if(d=Xl.join(Xl.dirname(i),p),Nn.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);Nn.renameSync(i,d)}co(d||i,n.config)}async function Hd({name:t,description:e,enabled:r,steps:n,folder:o,project:i}){let a=ze(t),s=Xl.join(o,`${a}.module.yaml`),c=zz(),{stepsToSave:l}=await it({stepLists:{steps:n}}),u={fileType:Se.MODULE,schemaVersion:_e,moduleId:c,name:t,description:e,enabled:r,steps:l.steps},d=Jl.stringify(u);return Nn.writeFileSync(s,d,"utf-8"),co(s,i.config),{moduleId:c,name:t,description:e,enabled:r,steps:n}}function uo(t,e){let r=Nn.readFileSync(t,"utf-8"),n=Jl.parse(r);try{return sg.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:t,moduleContents:r},`${t} does not parse as a valid Momentic module`),o}}async function dn(t,e,r,n){let o=uo(t.fullFilePath,r),{resolvedSteps:i}=await Id({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:r,callbacks:{onFetchModule:async({id:s})=>{let c=e.modules[s]?.fullFilePath;if(c)return uo(c,r)}}}),a={...o,steps:i};return n&&(n[t.id]=Bz(a)),a}async function Gd(t,e){let r={};return await Promise.all(Object.values(t.modules).map(async n=>{await dn(n,t,e,r)})),Array.from(Object.values(r))}async function Ww({test:t,name:e,folder:r}){let n=await Nw({test:t});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${ze(e)}.test.yaml`,a=zi.join(r,i);return pn.writeFileSync(a,n.test,"utf-8"),a}function Ef(t,e,r){let n=zi.join(r.rootDir,t);if(!pn.existsSync(n))throw new Error(`Test not found at path '${t}' in project '${r.rootDir}'`);let o=pn.readFileSync(n,"utf-8"),i=cs.parse(o),a,s;if(e.name&&e.name!==i.name){let p=`${ze(e.name)}.test.yaml`;if(a=zi.join(zi.dirname(t),p),s=zi.join(r.rootDir,a),pn.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let c={...i,...e},l=Gr.parse(c),u={fileType:Se.TEST,...Gr.parse(l),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=cs.stringify(u);return pn.writeFileSync(n,d,"utf-8"),s&&pn.renameSync(n,s),co(n,r.config),{newRelativeTestPath:a}}function Er({relativeTestPath:t,steps:e,schemaVersion:r,project:n,forceSaveOnNoDiffs:o}){let i=zi.join(n.rootDir,t);if(!pn.existsSync(i))throw new Error(`Test not found at path '${t}' in project '${n.rootDir}'`);let a=pn.readFileSync(i,"utf-8"),s=cs.parse(a),c=Gr.parse({...s,schemaVersion:r}),l=Ze.array().or($w.undefined()).parse(e.beforeSteps),u=Ze.array().parse(e.steps),d=Ze.array().or($w.undefined()).parse(e.afterSteps),p=Ln({fileType:Se.TEST,...c,beforeSteps:l&&l.length>0?l:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=Hz(p,s);if(m&&Object.keys(m).length===0&&!o){b.debug(`Skipping save for test ${c.name} since there are no changes`);return}let g=cs.stringify(p);pn.writeFileSync(i,g,"utf-8"),b.debug(`Saving test ${c.name} to ${i}`),co(i,n.config)}function Ql(t,e){let r=zi.join(e.rootDir,t);if(!r)throw new Error(`Could not find test with path ${t} in Momentic project (${e.rootDir})`);let n;try{n=pn.readFileSync(r,"utf8"),n=n.replace(/\r\n|\r/g,`
44
+ `)}catch(i){throw new Error(`Could not read test file ${r}: ${i}`)}let o;try{o=cs.parse(n)}catch(i){throw new Error(`Could not parse test file ${r} as YAML: ${i}`)}return Xt.parse(o)}function Hi(t,e,r){let n=r.project.rootDir,o;try{o=pn.readFileSync(t,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=cs.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${t} is missing steps`);return i}async function pt(t,e,r){let n=Hi(t,e,r),o;try{o=Gr.parse(n)}catch(a){throw new Error(`Test ${t} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await Ow({rawSteps:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:s})=>{let c=r.modules[a]?.fullFilePath;if(c)return uo(c,s)}}});return i}import Gz from"@dotenvx/dotenvx";import jz from"fs";import qw from"path";function jd(t,e){return(t.config.environments??[]).map(r=>Gi(r.name,t,e))}function Kw(t){return t.includes("${")?t.replace(/\$\{([^}]+)\}/g,(e,r)=>{let n=r.match(/^([A-Za-z_][A-Za-z0-9_]*)(?:(:-|-)([\s\S]*))?$/);if(!n)return process.env[r]||"";let o=n[1];if(!o)return"";let i=n[2],a=n[3],s=process.env[o];return i===":-"?s&&s!==""?s:a||"":i==="-"?s!==void 0?s:a||"":s||""}):t}function Vz(t){let{envVariables:e,project:r}=t;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let s=Kw(i);s&&(n[o]=s);continue}let a;try{a=jz.readFileSync(qw.resolve(r.rootDir,i.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${s}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${s}`)}else n[o]=a}return Object.keys(n).length>0&&b.debug(n,"Set environment variables with interpolation from project configuration"),n}function $z(t){let{project:e,envFile:r,logger:n}=t,o={};if(!r)return o;let i=Gz.config({path:qw.resolve(e.rootDir,r),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return n.debug(o,"Set environment variables from .env file"),o}function Gi(t,e,r){let n=(e.config.environments??[]).find(c=>c.name===t);if(!n)throw new Error(`Environment ${t} not found in local project configuration file`);if(!n.baseUrl)throw new Error(`Browser environment ${t} does not have a baseUrl configured`);let o={[Rt]:Kw(n.baseUrl)},i=Vz({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=$z({project:e,envFile:n.envFile,logger:r});return Object.assign(o,a),n.inheritFromShell&&(r.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:t,variables:o,browser:n.browser}}import{existsSync as qz,readFileSync as Kz,readdirSync as Yz,writeFileSync as Xz}from"fs";import{glob as Jz}from"glob";import ji,{dirname as Yw}from"path";import{cwd as Tf}from"process";import Xw from"yaml";import{z as qe}from"zod";import Wz from"zod";var Vd=["**/*.test.yaml","**/*.module.yaml"],bf=Wz.string().refine(t=>/^[a-zA-Z0-9-]+$/.test(t)),$d=15;var us="momentic.config.yaml",vf="momentic.workspace.yaml",Qz=qe.object({projects:qe.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),Zz=qe.union([qe.string(),qe.object({fromFile:qe.string(),json:qe.boolean().optional()})]),eH=qe.object({name:bf,baseUrl:qe.string().optional().describe("Optional for mobile tests"),envFile:qe.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:qe.record(qe.string(),Zz).optional(),inheritFromShell:qe.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Ai.optional().describe("NB: most things should use project-level configuration only")}),tH=qe.object({postSave:qe.string().optional()}),rH=qe.object({name:bf,include:qe.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:qe.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:qe.string().optional(),reporterDir:qe.string().optional(),outputDir:qe.string().optional(),recordVideo:qe.boolean().optional(),retries:qe.number().optional().describe("number of retries per test"),parallel:qe.number().optional().describe("degree of parallelism"),environments:qe.array(eH).optional(),gitMainBranch:qe.string().optional(),gitProtectedBranches:qe.string().array().optional(),ai:_g.optional(),browser:Ai.optional(),emulator:dg.optional(),advanced:Mg.optional(),displayRoot:qe.string().optional().describe("relative path from project root to use as the Repository root"),hooks:tH.optional()});function Jw(t,e){let r;try{r=Kz(t,"utf-8")}catch(o){b.warn(`Could not read possible Momentic ${e} file at ${t}: ${o}`);return}let n;try{if(n=Xw.parse(r),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){b.warn(`Possible Momentic ${e} file at ${t} does not parse as valid YAML: ${o}`);return}return n}function Rf(t){let e=Jw(t,"project configuration");if(e!==void 0)try{return rH.parse(e)}catch(r){b.warn(`Possible Momentic project configuration file at ${t} does not adhere to the required schema: ${r}`);return}}function nH(t){let e=Jw(t,"workspace configuration");if(e!==void 0)try{return Qz.parse(e)}catch(r){b.warn(`Possible Momentic workspace configuration file at ${t} does not adhere to the required schema: ${r}`);return}}function oH(){let t=[],e=Tf(),r=ji.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=ji.basename(e);if(td.includes(i))return b.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),t;for(let a of Yz(e))if(a.endsWith(us)){let s=ji.join(e,a),c=Rf(s);c&&t.push({configFilePath:s,config:c,rootDir:Yw(s)})}if(t.length)return t;if(e=ji.dirname(e),e===r)break}return t}async function _t(t={}){let{configFilePath:e,nameFilter:r}=t,n=await Af(e);if(r&&(n=n.filter(o=>o.config.name===r)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
45
+ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return b.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function iH(t){let e=nH(t);if(!e||!e.projects||!e.projects.length)return;let r=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${us}`)),n=AbortSignal.timeout(2e3),o;try{o=await Jz(r,{absolute:!1,cwd:Tf(),dotRelative:!1,maxDepth:$d,nodir:!0,signal:n})}catch(a){throw b.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${vf} is misconfigured.`),a}let i=[];for(let a of o){let s=ji.join(Tf(),a),c=Rf(s);c&&i.push({configFilePath:s,config:c,rootDir:Yw(s)})}return i}async function Af(t){if(t){t=ji.resolve(t);let r=Rf(t);return r||(console.error(`No valid Momentic project file found at ${t}.`),process.exit(1)),[{config:r,configFilePath:t,rootDir:ji.dirname(t)}]}if(qz(vf)){let r=await iH(vf);if(r)return r}return oH()}function $o(t,e){let r=Xw.stringify(t);Xz(e,r)}import Zw from"fs";import{glob as aH}from"glob";import Zl from"path";import sH from"yaml";import{z as Qw}from"zod";var eC=!1,lH=Qw.object({fileType:Qw.nativeEnum(Se)});async function te(t,e=!1){let r={project:t,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=t.config.include??Vd,o=Array.from(t.config.exclude??[]).concat(rd),i=AbortSignal.timeout(5e3),a;try{a=await aH(n,{absolute:!1,cwd:t.rootDir,ignore:o,dotRelative:!1,maxDepth:$d,nodir:!0,signal:i})}catch(s){throw b.error({err:s},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:s})}for(let s of a){let c=cH(t.rootDir,s,r,e?Pn:b);c&&(r.duplicateEntities[c.id]=c.paths)}return eC=!0,r}function cH(t,e,r,n){let o=Zl.join(t,e),i=uH(o,n);if(!i)return;let a=dH(i,o,n);if(!a)return;let s=lH.safeParse(a);if(s.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=pH(o,n);if(!l)return;let u=mH(e,o,l);switch(c){case Se.TEST:try{return hH(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case Se.MODULE:try{return gH(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case Se.MOBILE_TEST:try{return SH(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case Se.MOBILE_MODULE:try{return fH(a,r,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function uH(t,e){try{return Zw.readFileSync(t,"utf-8")}catch(r){e.warn(`Could not read possible Momentic file at ${t}, skipping: ${r}`);return}}function dH(t,e,r){try{let n=sH.parse(t);if(typeof n!="object"||n===null)throw new Error("The YAML document should parse as a map with key-value pairs");return n}catch(n){r.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function pH(t,e){try{return Zw.statSync(t)}catch(r){e.warn(`Skipping path '${t}' because it could not be stat, skipping: ${r}`);return}}function mH(t,e,r){return{relativePath:t,fullFilePath:e,platformSep:Zl.sep,fullPathSegments:e.split(Zl.sep),relativePathSegments:t.split(Zl.sep),fileName:Zl.basename(e),lastModified:r.mtime,createdAt:r.birthtime}}function hH(t,e,r,n,o){let i=Gr.parse(t),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,n]}}return e.tests[i.id]={type:Se.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...r},a}function gH(t,e,r,n,o){let i=fr.parse(t),a;if(e.modules[i.moduleId]){let c=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}e.modules[i.moduleId]={type:Se.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...r};let s=r.fileName.replace(".module.yaml","");return!eC&&ze(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function fH(t,e,r,n,o){let i=Xu.parse(t),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=r.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:Se.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...r},a}function SH(t,e,r,n,o){let i=Va.parse(t),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=r.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:Se.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,labels:i.labels,...r},a}import ds from"fs";import wf from"path";import{z as Cf}from"zod";var tC="golden/visual-diff",rC="reports",nC="test-results";var yH=Cf.object({width:Cf.number(),height:Cf.number()}),ps=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,r){let n=wf.join(e.rootDir,e.config.goldenFileDir??tC);this.defaultGoldenScreenshotDir=n,this.regenerateGoldenFiles=r}async prepareGoldenScreenshotForComparison(e,r,n){if(r.screenshot?.data?.startsWith("https://")){let a=await fetch(r.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:r.screenshot.width,height:r.screenshot.height}}let o=r.screenshot?.data;o||(o=wf.join(this.defaultGoldenScreenshotDir,`${r.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ds.mkdirSync(wf.dirname(o),{recursive:!0}),ds.writeFileSync(o,n.buffer),ds.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(ds.existsSync(o)){let a=ds.readFileSync(o),s=yH.parse(JSON.parse(ds.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new M("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};import{execFile as EH}from"node:child_process";import{promisify as bH}from"node:util";import TH from"simple-git";var Xe=TH(),oC=bH(EH);async function vH(t){let e=await rt(t,Xe.raw(["config","--list"])),r={};if(!e)return r;for(let n of e.split(`
46
+ `)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();r[i]=a}return r}async function RH(t,e,r){try{let o=r["github.user"]||void 0;if(o)return o}catch{}let n;try{if(e?.startsWith("http://")||e?.startsWith("https://"))n=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(n=e.slice(o+1,i))}}catch{}if(n=n?.toLowerCase(),!!n){try{if(e?.startsWith("git@")&&n?.includes("github")){let{stdout:o,stderr:i}=await oC("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await oC("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function AH(t,e,r){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return RH(t,e,r);if(o)return}catch{}}function Wd(t){if(t.startsWith("git@")){let e=t.split(":");if(e.length===2){let r=e[1].replace(".git","").split("/");if(r.length===2){let n=r[0],o=r[1];return`${n}/${o}`}}}else if(t.startsWith("http")||t.startsWith("https")){let r=new URL(t).pathname.split("/").filter(Boolean);if(r.length>=2){let n=r[0],o=r[1].replace(".git","");return`${n}/${o}`}}}async function rt(t,e){try{return(await e).trim()}catch(r){if(r instanceof Error&&r.message.includes("not a git repository"))return;t.error({err:r},"Failed to run git command");return}}function wH(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function CH(t){let[e,r,n]=await Promise.all([rt(t,Xe.show(["--no-patch","--format=%ci"])),rt(t,Xe.show(["-s","--pretty=%B"])),rt(t,Xe.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function xH(t){let[e,r,n]=await Promise.all([rt(t,Xe.listRemote(["--get-url","origin"])),rt(t,Xe.show(["-s","--pretty=%B"])),rt(t,Xe.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:r,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function _H(t){let[e,r,n,o]=await Promise.all([rt(t,Xe.show(["--no-patch","--format=%ci"])),rt(t,Xe.listRemote(["--get-url","origin"])),rt(t,Xe.show(["-s","--pretty=%B"])),rt(t,Xe.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??r,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),c=i?Wd(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:i,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:a?c:void 0,gitlabProjectPath:s?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function MH(t){let[e,r,n]=await Promise.all([rt(t,Xe.show(["--no-patch","--format=%ci"])),rt(t,Xe.show(["-s","--pretty=%B"])),rt(t,Xe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Wd(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function PH(t){let[e,r,n]=await Promise.all([rt(t,Xe.show(["--no-patch","--format=%ci"])),rt(t,Xe.show(["-s","--pretty=%B"])),rt(t,Xe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Wd(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:r,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function IH(t,e){let[r,n,o,i,a,s,c,l,u]=await Promise.all([rt(t,Xe.revparse(["HEAD"])),rt(t,Xe.revparse(["--short","HEAD"])),rt(t,Xe.revparse(["--abbrev-ref","HEAD"])),rt(t,Xe.listRemote(["--get-url","origin"])),rt(t,Xe.show(["--no-patch","--format=%ci"])),rt(t,Xe.show(["-s","--pretty=%B"])),rt(t,Xe.show(["-s","--pretty=%an"])),e?rt(t,Xe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),vH(t)]),d=l?await rt(t,Xe.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Wd(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,S=u["user.username"]||void 0,y=await AH(t,i,u)??S??void 0;return{ciProvider:"none",gitCommitSha:r,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:y,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function OH(){let t=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:t?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:t?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function LH(t){let e=t.config.gitProtectedBranches??[];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function po(t,e){let r=wH();if(!r)return IH(t,e);switch(r){case"GithubActions":return CH(t);case"GitlabCI":return xH(t);case"CircleCI":return _H(t);case"Buildkite":return MH(t);case"AzureDevOps":return PH(t);case"GCPCloudBuild":return OH()}}async function NH(t,e,r,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(r,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){t.warn({err:i},"Failed to get merge base commit from Gitlab")}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName)try{let i=await e.getCommitFromGitlab(r,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){t.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(r,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){t.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function DH(t,e,r,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(r,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){t.warn({err:a},"Failed to get merge base commit from GitHub")}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let a=await e.getCommitFromGithub(r,n,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}catch(a){t.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(r,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){t.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function kH(t,e,r){try{if(r.githubRepository){let[n,o]=r.githubRepository.split("/");return await DH(t,e,n,o,r)}else if(r.gitlabProjectPath)return await NH(t,e,r.gitlabProjectPath,r)}catch(n){t.warn({err:n},"Failed to get remote git metadata")}return r}async function Vr(t,e,r){let n=await LH(r),o=await po(t,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await kH(t,e,i);return{...n,...o,...a}}async function iC(){try{return!!(await Xe.show(["--no-patch","--format=%ci"])).trim()}catch{return null}}import{diff as Qbe}from"deep-object-diff";import{cloneDeep as eTe}from"lodash-es";import{v4 as pTe}from"uuid";import hTe from"yaml";import MTe from"yaml";import ITe from"zod";import{randomUUID as FH}from"crypto";import Wo from"fs";import ms from"path";var aC=new Set([".DS_Store","__MACOSX"]),sC={status:(t,e)=>{if(t.status===e.status)return t.status;if(t.status==="FAILED"||e.status==="FAILED")return"FAILED";if(t.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(t.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(t.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(t.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${t.status} and ${e.status}`)},startedAt:(t,e)=>t.startedAt<e.startedAt?t.startedAt:e.startedAt,updatedAt:(t,e)=>t.updatedAt>e.updatedAt?t.updatedAt:e.updatedAt,finishedAt:(t,e)=>!t.finishedAt||!e.finishedAt?new Date:t.finishedAt>e.finishedAt?t.finishedAt:e.finishedAt,gitCommitTimestamp:(t,e)=>{if(!(!t&&!e)){if(!t.gitCommitTimestamp||!e.gitCommitTimestamp||t.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${t.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return t.gitCommitTimestamp}},pipelineId:(t,e)=>t.pipelineId===e.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:t.startedAt<e.startedAt?e.pipelineId:t.pipelineId,labels:(t,e)=>{let r=new Set([...t.labels??[],...e.labels??[]]);return Array.from(r)}};function UH(t,e,r){if(sC[r]){let i=sC[r];return i(t,e)}let n=t[r],o=e[r];if(n!==o)throw new Error(`Metadata values for key "${r}" do not match: "${n}" vs "${o}"`);return n}var xf=class extends Error{constructor(e,r){let n=`${e} contains invalid Momentic results: ${r}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function lC(t,e){try{let r=ms.join(e,"metadata.json");return ld.parse(JSON.parse(Wo.readFileSync(r,"utf-8")))}catch{throw new xf(t,e)}}function cC(t,e,r){let n=FH(),o=t.child({runGroupId:n});Wo.rmSync(e,{recursive:!0,force:!0});let i=Wo.readdirSync(r).filter(c=>!aC.has(c)).map(c=>ms.join(r,c));if(i.length===0)throw new Error(`No run groups found in results path: ${r}`);Wo.mkdirSync(e,{recursive:!0});let a={...lC(r,i[0]),id:n};for(let c of i){let l=ms.join(c,"runs");if(!Wo.existsSync(l))continue;let u=lC(r,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let m=p;a[m]=UH(a,u,m)}let d=Wo.readdirSync(l);for(let p of d){if(aC.has(p))continue;let m=ms.join(l,p),g=ms.join(e,"runs",p);Wo.cpSync(m,g,{recursive:!0})}}let s=ms.join(e,"metadata.json");Wo.writeFileSync(s,JSON.stringify(a,null,2))}import uC from"adm-zip";import _f from"fs";import qd from"path";function BH(t){let e=new uC,r=qd.join(t,"metadata.json"),n=ld.parse(JSON.parse(_f.readFileSync(r,"utf-8")));e.addLocalFile(r);for(let o of _f.readdirSync(qd.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new uC(qd.join(t,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(qd.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Kd(t){let{client:e,consoleLogger:r,resultsPath:n}=t;if(!_f.existsSync(n)){r.warn("Results path does not exist, skipping upload.");return}let o=new gd(e);try{let{runGroupId:i,buffer:a}=BH(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;r.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",r.error(`Failed to upload test results: ${a}.`);return}}import zH from"adm-zip";import Ht from"fs";import Mr from"path";var ec=class t{constructor(e){this.filePath=e;Ht.rmSync(this.filePath,{recursive:!0,force:!0}),Ht.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new t(Mr.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){Ht.mkdirSync(Mr.join(this.filePath,e),{recursive:!0})}readFile(e){let r=Mr.join(this.filePath,e);if(Ht.existsSync(r))return Ht.readFileSync(r)}storeFile(e){let{name:r,contents:n}=e,o=Mr.join(this.filePath,r);try{Ht.writeFileSync(o,n)}catch{}}createFileStream(e){let r=Mr.join(this.filePath,e);return Ht.createWriteStream(r)}createRunArchive(e){return new Mf(Mr.join(this.filePath,"runs"),e)}},Mf=class{constructor(e,r){this.filePath=e;this.tempPath=Mr.join(e,`temp-storage-${r}`),this.finalPath=Mr.join(e,`${r}.zip`),Ht.rmSync(this.tempPath,{recursive:!0,force:!0}),Ht.rmSync(this.finalPath,{recursive:!0,force:!0}),Ht.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let r=Mr.join(this.tempPath,e);if(Ht.existsSync(r))return Ht.readFileSync(r)}mkdir(e){Ht.mkdirSync(Mr.join(this.tempPath,e),{recursive:!0})}cd(e){return new ec(Mr.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:r,contents:n}=e,o=Mr.join(this.tempPath,r);Ht.writeFileSync(o,n)}createFileStream(e){let r=Mr.join(this.tempPath,e);return Ht.createWriteStream(r)}close(){let e=new zH;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let r=e.toBuffer();Ht.writeFileSync(this.finalPath,r),Ht.rmSync(this.tempPath,{recursive:!0,force:!0})}};import HH from"adm-zip";import{randomUUID as GH}from"crypto";import Ot from"fs";import Gt from"path";function hC(t){try{return Ot.existsSync(t)?JSON.parse(Ot.readFileSync(t,"utf-8")):void 0}catch{return}}function dC(t){return Ot.existsSync(t)?Ot.readFileSync(t,"utf-8").split(`
47
+ `).map(r=>r.trim()).filter(r=>r.length>0):[]}function jH(t,e){let r=t.attemptIdToAttemptNumber.get(e);if(r)return Gt.join(t.inflatedPath,"attempts",r);let n=Gt.join(t.inflatedPath,"attempts");if(!Ot.existsSync(n))return;let o=Ot.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of o){let a=Gt.join(n,i,"metadata.json"),s=hC(a);if(typeof s!="object"||s===null)continue;let c=s.id;if(typeof c=="string"&&c===e)return t.attemptIdToAttemptNumber.set(e,i),Gt.join(n,i)}}function pC(t,e,r){let n=Gt.join(t,"attempts");if(!Ot.existsSync(n))return;let o=Ot.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of o){let a=Gt.join(n,i,"assets",`${e}.${r}`);if(Ot.existsSync(a))return a}}var Yd=class{constructor(e,r,n){this.outputDir=e;this.runId=r;this.runAttemptId=n;this.runsDir=Gt.join(e,"runs"),this.zipPath=Gt.join(this.runsDir,`${r}.zip`)}inflatedByRunId=new Map;zipPath;runsDir;ensureInflatedRun(e){let r=this.inflatedByRunId.get(e);if(r)return r;if(e!==this.runId||!Ot.existsSync(this.zipPath))return;let n=Gt.join(this.runsDir,`temp-unzipped-${e}-${GH()}`);Ot.mkdirSync(n,{recursive:!0}),new HH(this.zipPath).extractAllTo(n,!0);let i={runId:e,zipPath:this.zipPath,inflatedPath:n,attemptIdToAttemptNumber:new Map};return this.inflatedByRunId.set(e,i),i}close(){for(let e of this.inflatedByRunId.values())Ot.rmSync(e.inflatedPath,{recursive:!0,force:!0});this.inflatedByRunId.clear()}getAttemptDir(){let e=this.ensureInflatedRun(this.runId);if(e)return jH(e,this.runAttemptId)}listVideoAssetPaths(){let e=this.getAttemptDir();if(!e)return[];let r=Gt.join(e,"assets");return Ot.existsSync(r)?Ot.readdirSync(r,{withFileTypes:!0}).filter(o=>o.isFile()).map(o=>Gt.join(r,o.name)).filter(o=>{let i=Gt.extname(o).toLowerCase();return i===".webm"||i===".mp4"}):[]}readAttemptAssetText(e,r){let n=this.getAttemptDir();if(!n)return;let o=Gt.join(n,"assets",`${e}.${r}`);if(Ot.existsSync(o))try{return Ot.readFileSync(o,"utf-8")}catch{return}}async getConsoleLogsForRunAttempt(e,r,n){if(r!==this.runId||n!==this.runAttemptId)return;let o=this.getAttemptDir();if(!o)return;let i=hC(Gt.join(o,"console.json")),a=yg.safeParse(i);return a.success?a.data:void 0}async getNetworkLogsForRunAttempt(e,r,n){if(r!==this.runId||n!==this.runAttemptId)return;let o=this.getAttemptDir();if(!o)return;let i=Gt.join(o,"assets","har-pages.log"),a=Gt.join(o,"assets","har-entries.log"),s={};for(let u of dC(i)){let d=Ol.safeParse(mC(u));d.success&&(s[d.data.id]=d.data)}let c={},l=dC(a);for(let u=0;u<l.length;u++){let d=l[u],p=Ll.safeParse(mC(d));if(!p.success)continue;let m=`${p.data.startedDateTime}-${u}`;c[m]=p.data}if(Object.keys(c).length!==0)return bg(s,c)}async getHtmlSnapshot(e,r){let n=this.readAttemptAssetText(r,"html");if(n)return n;let o=this.ensureInflatedRun(this.runId);if(!o)return;let i=pC(o.inflatedPath,r,"html");if(i)try{return Ot.readFileSync(i,"utf-8")}catch{return}}async getA11yTreeSnapshot(e,r){let n=this.readAttemptAssetText(r,"xml");if(n)return n;let o=this.ensureInflatedRun(this.runId);if(!o)return;let i=pC(o.inflatedPath,r,"xml");if(i)try{return Ot.readFileSync(i,"utf-8")}catch{return}}async getScreenshot(e,r){if(!this.ensureInflatedRun(this.runId))return;let o=this.getAttemptDir(),i=o?Gt.join(o,"assets",`${r}.jpeg`):void 0;if(i)try{return Ot.readFileSync(i)}catch{return}}};function mC(t){try{return JSON.parse(t)}catch{return}}import{hostname as VH}from"os";var $H="2.29.5",tc=Xa({app:"desktop-server",hostname:VH(),disableConsoleLogs:!0}).child({cliVersion:$H});(async()=>{try{let t=await po(tc);t.gitBranchName&&tc.addBinding("branch",t.gitBranchName)}catch{}})();var gC=WH();gC.get("/",async(t,e)=>{let r=me(),n=Hw();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Vr(tc,n,r);e.status(200).json(o)});var Pf=gC;import rY from"events";import EL,{Router as nY}from"express";import oY from"http";import iY from"path";import{Server as cK}from"socket.io";var qH=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async()=>{e.info({sessionId:n},"Cancel event received");let o=r.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},fC={event:"cancel",createHandler:qH};var KH=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async(o,i)=>{let a=r.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:l},"Fetched a11y tree from the browser"),i({a11yTree:l})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},SC={event:"fetchA11yTree",createHandler:KH};var YH=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async(o,i)=>{let a=r.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=await s.html();i({html:c})}catch(c){e.error({err:c},"Error fetching DOM from the browser"),c.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:c.message})}}},yC={event:"fetchDom",createHandler:YH};var XH=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),r.removeSession(n,e)}},EC={event:"disconnect",createHandler:XH};function mn(t){let{result:e,nestedResults:r}=t;if(!t.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=JH(r);QH(e,n,o);let i=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await ZH(i,e,n,o)}catch(a){t.logger.error({result:t.result,err:a},"Error hoisting scalar result metadata")}})())}function JH(t){let e=t[0],r;for(;;){switch(e.type){case"PRESET_ACTION":{r=e;break}case"CONDITIONAL":r=t[0];break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){r=e;break}e=e.results[0];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(r)break}let n=t[t.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:r,lastMetadata:o}}function QH(t,e,r){e&&(t.beforeUrl=e.beforeUrl),r&&(t.afterUrl=r.afterUrl,t.data=r.data,r.status!=="SUCCESS"&&(t.message=r.message))}async function ZH(t,e,r,n){await Promise.allSettled(t),r&&(e.beforeSnapshot=r.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import{randomUUID as u1}from"crypto";import{faker as e1}from"@faker-js/faker";import t1 from"assert";import r1 from"axios";import*as n1 from"child_process";import o1 from"moment";import*as i1 from"otpauth";import a1 from"pg";async function bC(t){let e;try{e=new URL(t.url).hostname}catch{}let r=[];return t.headers.getSetCookie()?.forEach(n=>{let o=Ju(n,e);r.push(...o)}),r}function s1(t,e){if(!t&&!e)return;let r;if(t){let{url:o,options:i}=t;r=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:r,response:n}}async function l1(t,e){switch(t){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let r=[];return e.headers.forEach((o,i)=>{r.push([i,o])}),{status:e.status,headers:r,body:await e.text()}}else throw new Error("Result is not a Response object")}}var c1=Object.getPrototypeOf(async function(){}).constructor;async function TC(t,e,r){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:s}=e.bindings,c=e.tools,l={},u=(E,T)=>{o[E]=T,l[E]=T},d={},p=(E,T)=>{o[E]=T,d[E]=T},m;n.includes("Octokit")&&(m=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new c1("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(r1,o1,c.fakerInstance??e1,t1,a1,m,g,i1,n1,bC,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,T=>c.sms.send(T),T=>c.sms.fetchLatest(T),c.email,c.sms,c.ai,s1(a,s),...Object.values(i??{}))),f=!0,S,y;try{let E=await $(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});S=await l1(e.options.responseSerialization??"RAW",E)}catch(E){r.error({err:E,env:o,evalCode:n},`[${t}] Error executing code: ${E}`),f=!1,E instanceof zo?y=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:y=E instanceof Error?E.message:`${E}`}return{result:S,variableUpdates:l,persistentVariableUpdates:d,success:f,error:y}}async function vC({code:t,fragment:e,context:r,localTools:n,logger:o,signal:i,timeoutMs:a=ko,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=u1(),p=await TC(d,{code:t,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...r.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return b.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as d1,randomUUID as p1}from"crypto";import m1 from"fetch-retry";var h1=m1(global.fetch,{retries:3,retryOn:function(t,e,r){return!!(e!==null||r&&r.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),RC=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,AC=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function wC({orgId:t,code:e,fragment:r,context:n,timeoutMs:o=ko,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!RC)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!AC)throw new Error("Missing lambda auth secret.");let h=d1("sha256",AC).update(t).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let S={id:p1(),orgId:t,momenticLambdaAuthHash:h,code:e,fragment:r,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(p=await $(h1(RC,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);m=void 0;break}catch(y){m=y}}if(m)throw s.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=Dv.parse(await p.json())}catch(S){throw new Error(`Code evaluation server returned invalid response: ${S}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function qo(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await wC(t);else if(t.localTools)e=await vC({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let r=`Failed to evaluate code:
48
48
  ${e.error}
49
49
  Code received:
50
50
  ${t.code}`;throw t.logger.error({err:e.error,code:t.code,env:t.context.toObjectCopy()},r),new Error(r)}if(e.variableUpdates)for(let[r,n]of Object.entries(e.variableUpdates))t.context.setVariable(r,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await t.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[r,n]of Object.entries(e.persistentVariableUpdates))t.context.setVariable(r,n)}return e.result}import{set as g1}from"lodash-es";async function pr(t){let{orgId:e,s:r,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=ko,allowUndefined:c=!1}=t,l=/{{(.*?)}}/g,u=r.matchAll(l),d=r;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),g;try{g=await qo({orgId:e,code:m,fragment:!0,context:n,timeoutMs:s,logger:o,retries:a,localTools:t.localTools,signal:i})}catch(f){throw o.error({err:f,value:r},"Error evaluating template string"),f}if(g===void 0&&!c)throw new M("UserConfigurationError",`Template fragment '${m}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function Xd(t){return CC(t)}async function CC({obj:t,bannedKeys:e,allowList:r,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let s in t){if(e.includes(s))continue;let c=!1;if(r)if(r.includes(s))c=!0;else continue;let l=t[s],u=[...o,s];if(typeof l=="string"&&l.includes("{{")){let d=await pr({s:l,context:n,...a});if(l===d)continue;i.push({path:u,original:l}),t[s]=d}else typeof l=="object"&&l!==null&&!Array.isArray(l)&&await CC({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:r,...a})}return i}function xC(t,e){for(let{path:r,original:n}of e)g1(t,r,n)}import f1 from"fetch-retry";var oAe=process.env.MAILINATOR_API_KEY,iAe=f1(global.fetch,{retryOn:function(t,e,r){return t>3?!1:!!(e!==null||r&&r.status>=400)},retryDelay:function(t){return 500}});import{hostname as Tq}from"os";var If={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[E.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var T={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=y(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=y(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=E.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch{}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:h}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&h===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return T.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||n?.parentNode,n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var R={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(R.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=A;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`// src/html/constants.ts
@@ -4341,7 +4341,7 @@ ${c}`,{errOptions:{cause:t}})}if(i.includes("element is not visible")){let c="Th
4341
4341
  writable: false,
4342
4342
  configurable: false,
4343
4343
  });`),`${r}
4344
- //# sourceURL=momentic-injected/extra-scripts.js`}function Zf(t){let e=[],r="";for(let n of t)n==="+"&&r?(e.push(r),r=""):r+=n;return e.push(r),e}var sG=["clipboard-read","clipboard-write","microphone","camera","geolocation","local-network-access"],lG=["local-network-access"];function ax(t){return wr?t.filter(e=>!lG.includes(e)):t}function sx(t){return ax(t||sG)}function lx(t){return t.parentFrame!==void 0}async function cx(t){try{return await cG(t)}catch(e){t.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function cG({locator:t,logger:e}){let[r,n]=await t.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:de}),o=await gn(t,e,500),i=await t.boundingBox({timeout:de});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(r)try{let c=t.page().locator(`label[for=${JSON.stringify(r)}]`);return await c.waitFor({state:"visible",timeout:de}),{locator:c,relativePoint:void 0}}catch{}let a=await t.evaluate(c=>{let l=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let m={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},g=l._MOMENTIC_FEATURE_FLAGS?.[Jd],h=c.getAttribute(mo),f=!g&&h?hn(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:m,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:de});if(a.type==="error")throw new Error(a.error);let s=t.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:de}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var dx=["date","datetime-local","month","time","week"],ux={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function px(t){try{await $(uG(t),{milliseconds:ce})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function uG({root:t,text:e,options:r,logger:n,callbacks:o}){let i=(await Mt({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:de,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!ux[i])return;ux[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),r.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as br}from"zod";var mx=br.object({doubleClick:br.boolean().optional(),rightClick:br.boolean().optional(),force:br.boolean().optional(),waitForDownload:br.boolean().optional(),delayMs:br.number().optional(),downloadTimeoutMs:br.number().optional(),relativePosition:br.object({x:br.number(),y:br.number()}).optional()}),hCe=br.object({repeat:br.number().optional(),convertMeta:br.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:br.number().optional()});async function np({locator:t,callbacks:e,logger:r,timeoutMs:n=de}){try{await eS(e,n);let o=t.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let m=window.getComputedStyle(d,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,l),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await $(o,{milliseconds:n}),!0}catch(o){return r.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function eS(t,e=de){let r=await t.state.getRoot();await Mt({root:r,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:t.waitForPageLoad,codePath:"removing element highlights"})}async function tS(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return Wi({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async r=>gx({...t,targetingResult:r,useVisualClick:e})})}async function hG(t,e){let{redirectionAttempts:r=0}=e;if(r>=2)throw t;try{return await gG(t,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:t},"Error handling click error, rethrowing original error"),t):n}}async function gG(t,e){let{logger:r,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(t.message.includes("label")&&t.message.includes("for=")&&t.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:de});if(!i)throw t;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:de}),r.warn({err:t},"Attempting locator redirection due to input being covered by label"),gx({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw r.error({err:t},"Click error does not match any known recoverable patterns, rethrowing"),t}async function fG(t){let{logger:e,targetingResult:r,position:n,options:o}=t,i=mx.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await EG({targetingResult:r,position:n,options:o,logger:e,isAndroid:t.isAndroid});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function SG(t){let{actionSource:e,targetingResult:r,options:n,logger:o}=t,i=t.targetingResult.locator,a=n?.relativePosition??t.position;if(e==="click"&&!a){let l=await cx({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||r.hints?.force||!1;s&&!a&&r.hints?.relativeXYToLocator&&(a=r.hints.relativeXYToLocator);let c=i.toString();o.info({locator:c,position:a},"Locator click");try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:ce,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:ce,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(TG(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),hG(u,{...t,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function gx(t){let{options:e,logger:r,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=t,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Of;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof mG.TimeoutError?new M("ActionFailureError",`Download did not complete in ${u}ms`):new M("ActionFailureError",`Download failed: ${d.message}`)}})());try{await np({locator:a.locator,callbacks:n,logger:r,timeoutMs:de})}catch(u){r.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await fG(t):l=(await SG(t)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new M("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");r.info("Waiting for download to start and complete");let u=await $(s,{milliseconds:e.downloadTimeoutMs??Of});if(u instanceof Error)throw u;return{downloadedFile:await bG(u,o.createIsolatedFolder,r),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function yG(t,e){let r=await t.locator.boundingBox({timeout:ce});if(!r){let i=await gn(t.locator,e,500);throw new M("ActionFailureError",`${Eh}${i?`: ${i}`:""}`)}if(t.hints?.relativeXYToLocator){let i=r.x+t.hints.relativeXYToLocator.x,a=r.y+t.hints.relativeXYToLocator.y;return[{x:i,y:a},"targeting hint"]}let n=r.x+r.width/2,o=r.y+r.height/2;return[{x:n,y:o},"halfway point"]}async function EG({options:t,targetingResult:e,position:r,logger:n}){let o,i,a;if(t?.relativePosition){let u=await e.locator.boundingBox({timeout:ce}),d=t.relativePosition.x,p=t.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(t.relativePosition.x,u.width))),u?.height&&(p=Math.max(0,Math.min(t.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+p,a="relative position from user"}else if(r){let u=await e.locator.boundingBox({timeout:ce});o=(u?.x??0)+r.x,i=(u?.y??0)+r.y,a="predefined position"}else{let[u,d]=await yG(e,n);o=u.x,i=u.y,a=d}let s=e.locator.page(),c=t?.rightClick?"right":"left",l=t?.delayMs??25;return t?.doubleClick?await s.mouse.dblclick(o,i,{button:c,delay:l}):await s.mouse.click(o,i,{button:c,delay:l}),{clickX:o,clickY:i,reason:a}}async function bG(t,e,r){r.info("Download detected, saving file to disk");let n=await t.path(),o=Gf(t.suggestedFilename()),i=e();await t.saveAs(pG(i,o)),hx(n,{force:!0}),setTimeout(()=>{hx(i,{recursive:!0,force:!0})},5*60*1e3);let a=BC(dG(i),o);return r.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function TG(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as vG}from"os";var RG={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function AG(){let t=vG();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function fx(t){return JSON.stringify(t.split("+").sort())}function op(t,e){let r=AG(),n=fx(t);for(let o of Object.values(RG))if(Object.values(o).some(i=>fx(i)===n))return o[r];return process.platform==="darwin"&&!e?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function rS({frame:t,page:e,deltaX:r,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!r&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(t)await Mt({root:t,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[r,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:Ne,codePath:"scrolling page"});else{let d=e.viewportSize()||Kt,p=await Mt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:Ne,codePath:"computing page height"}),[m,g,h]=await Mt({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let S=f.getBoundingClientRect();return[f.scrollTop,S.x,S.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:Ne,codePath:"computing active element position"});await e.mouse.wheel((r??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<Ne;){a?.throwIfAborted();let S=await $(e.evaluate(()=>document.body.scrollHeight),{milliseconds:de}),[y,E,T]=await $(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let w=v.getBoundingClientRect();return[v.scrollTop,w.x,w.y]}),{milliseconds:de});if(S===p&&y===m&&E===g&&T===h)break;p=S,m=y,g=E,h=T,await le(Lt)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function nS(t,e){let r,n;for(let o=0;o<4;o++)try{return r=t.pages(),await Promise.all(r.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await le(Lt)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}async function oS(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,isAndroid:a,hoverDurationMs:s}=t;if(a){await wG(t);return}await e.mouse.move(i.x,i.y),await e.mouse.down(),await e.mouse.move(r+i.x,n+i.y,{steps:o}),await le(s??Vi),await e.mouse.up()}async function Sx({page:t,fromTarget:e,toTarget:r,stepCount:n,dragDurationMs:o,hoverDurationMs:i}){let a=await r.boundingBox({timeout:ce});if(!a)throw new M("ActionFailureError","Could not get bounding box of 'to' target element");let s=await e.boundingBox({timeout:ce});if(!s)throw new M("ActionFailureError","Could not get bounding box of 'from' target element");let c=a.x+a.width/2,l=a.y+a.height/2,u=s.x+s.width/2,d=s.y+s.height/2;await oS({page:t,deltaX:c-u,deltaY:l-d,steps:n,dragDurationMs:o,hoverDurationMs:i,visualTarget:{x:u,y:d},isAndroid:!0})}async function yx(t,e,r,n){await t.mouse.move(e.x,e.y,{steps:3}),await t.mouse.down(),await t.mouse.move(r.x,r.y,{steps:3}),await le(Math.min(n.hoverDurationMs??500,Qd)),await t.mouse.up()}async function wG(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,dragDurationMs:a,hoverDurationMs:s}=t,c=Math.max(1,o??1),l=i.x,u=i.y,d=i.x+r,p=i.y+n;await e.evaluate(async({startX:m,startY:g,endX:h,endY:f,stepCount:S,dragDurationMs:y,hoverDurationMs:E})=>{let T=document.elementFromPoint(m,g)??document.body??document.documentElement,w=window._momenticMobileUtilities.dispatchTouch;w(T,"touchstart",m,g);for(let C=1;C<=S;C+=1){let _=m+(h-m)*C/S,N=g+(f-g)*C/S;w(T,"touchmove",_,N),await new Promise(U=>setTimeout(U,Math.floor((y??500)/S)))}E&&await new Promise(C=>setTimeout(C,E)),w(T,"touchend",h,f)},{startX:l,startY:u,endX:d,endY:p,stepCount:c,dragDurationMs:a,hoverDurationMs:s})}import{randomUUID as LG}from"crypto";import{cloneDeep as sS}from"lodash-es";function Jo(t,e){let r=t.findIndex(n=>n===e);if(!(r===-1||!t[r+1]))return t[r+1]}import{createHash as CG}from"crypto";var xG="v1";function iS(t,e){if(t.tagName.toLowerCase()==="svg"&&!MG(t))try{let r=Ex(t,e),n=_G(JSON.stringify(r));return{version:xG,json:r,hash:n}}catch{return}}function _G(t){return CG("md5").update(t).digest("hex")}function Ex(t,e){let r=t.tagName.toLowerCase(),n=PG(t);if(r==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:r,props:n,children:[]};for(let i of t.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=Ex(a,e);s&&o.children.push(s)}}return o}function MG(t){let e=t.computedStyles.display,r=t.computedStyles.visibility,n=t.computedStyles.opacity;return e==="none"||r==="hidden"||n==="0"}function PG(t){let e={},r=t.attributes;for(let n of Object.keys(r))$r.visualAttributesForSvgSerialization.includes(n)&&(e[n]=r[n]);return r.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=r.id),e}var qi={r:147,g:196,b:125,a:.55},Tx={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:qi,paddingColor:qi,borderColor:qi,marginColor:qi,eventTargetColor:qi,shapeColor:qi,shapeMarginColor:qi,showInfo:!0,showAccessibilityInfo:!0};function vx({snapshot:t,devicePixelRatio:e,computedStylesToFetch:r,logger:n}){let o=t.strings,i=t.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=IG({allDocuments:i,stringConstants:o,computedStylesToFetch:r,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function IG({allDocuments:t,stringConstants:e,computedStylesToFetch:r,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=t[o],l=c.layout,u={};l.nodeIndex.forEach((C,_)=>{u[C]=_});let d=l.styles,p=l.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],S=m.parentIndex??[],y=m.nodeName??[],E=m.nodeType??[],T=m.pseudoType??{index:[],value:[]},v=m.inputChecked??{index:[]},w=e[c.frameId];for(let C=0;C<h.length;C++){let _=h[C],N=E[C],U=f[C]??[],j=S[C]!==void 0&&S[C]>=0?S[C]:void 0,O=j!==void 0?h[j]:void 0,B=O!==void 0?a[O]:void 0,W=T.index.indexOf(C),q=W!==-1?e[T.value[W]]:void 0,ve=u[C],Y;ve?Y=p[ve]??[]:Y=[];let st=y[C]!==void 0?e[y[C]]?.toLowerCase():void 0;if(!st){s.warn({backendNodeId:_,frameId:w,frameIndex:o,nodeBounds:Y},"DOM node has no tag name");continue}let Le={backendNodeId:_,psuedoType:q,nodeType:N,frameIndex:o,parentFrameId:w,ownedFrameId:void 0,bounds:{x:Y[0]??null,y:Y[1]??null,width:Y[2]??null,height:Y[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:O??null,tagName:st,parent:B??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};B&&B.childrenBackendIds.push(_);let gt=g.index.indexOf(C);if(gt!==-1){let Ge=g.value[gt];i[Ge]=Le;let se=t[Ge]?.frameId;Le.ownedFrameId=se!==void 0?e[se]:void 0}for(let Ge of Object.keys(Le.bounds)){let se=Ge;Le.bounds[se]!==null&&(Le.bounds[se]/=n)}let rr=ve!==void 0?d[ve]??[]:[];for(let Ge=0;Ge<rr.length&&!(Ge>=r.length);Ge++){let se=rr[Ge];if(se===void 0||isNaN(se))continue;let qe=e[se];if(qe===void 0)continue;let tn=r[Ge];Le.computedStyles[tn]=qe}for(let Ge=0;Ge<U.length;Ge+=2){let se=U[Ge],qe=U[Ge+1];if(!se||!qe)continue;let tn=e[se],ga=e[qe];!tn||!ga||(Le.attributes[tn]=ga)}v.index.includes(C)&&(Le.attributes.checked="true"),a[Le.backendNodeId]=Le}return a[h[0]]}function aS(t,e){if(t.mPathSelector)return t.mPathSelector;let r=t.parent,n;if(!r)n=t.tagName;else if(t.tagName==="body")n="body";else{let i=r.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(t.backendNodeId),a=` > ${t.tagName}:nth-child(${i+1})`;n=`${aS(r,e)}${a}`}return t.mPathSelector=n,n}function bx(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var OG=["html","#document","#document-fragment"];function Rx({node:t,domGraph:e}){let r=[],n=t,o=bx(t,e);if(!o)return[t.tagName];let i=()=>{if(n=o,o=bx(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,OG.includes(n.tagName)){i();continue}if(n.tagName==="body")r.push("body");else{let c=!1,l=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){r.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return r.reverse()}function Ax(t,e){let r=t.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?r=r.frameLocator(a):r=r.locator(a)}}if(n.length&&(r=r.locator(n.join(" > "))),"owner"in r)throw new Error("Final locator from mpath is a frame locator");return r}async function wx(t,e){await t.send({method:"DOM.getDocument",params:{depth:0},timeout:Ne});let r=await t.send({method:"DOM.requestNode",params:{objectId:e},timeout:Ne}),o=(await t.send({method:"DOM.getAttributes",params:{nodeId:r.nodeId},timeout:Ne})).attributes,i=Jo(o,mo);if(!i)throw new Error(`Could not find attribute ${mo} for object ${e}`);return i}var NG=["focusable","keyshortcuts","controls","live","relevant","orientation"],DG=["selected","readonly","modal","required","invalid"],kG=["id","name","role","content"],Cx=["absolute","fixed","sticky"],FG=["i","label"],UG=["path"],BG=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator","LabelText"],Mx=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Px=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],zG=["menulistpopup","statictext","inlinetextbox"],HG=80,xx=100,Ix=50,uS=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],GG=["cite"],jG={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},VG={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},_x={indentLevel:0},lS=class t{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(r=>{r.name==="keyshortcuts"?this.dataMomenticId=parseInt(r.value.value):this.properties[r.name]=r.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let r=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(r&&r.length<Ix?r:""),this.role=this.role||(e.domNode.attributes.role??""),KG(this.properties,e.domNode,e.importantProperties)}XG(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&UG.includes(this.domNode.tagName)&&!this.domNode.attributes["aria-label"]||this.ignoredReasons.some(n=>Px.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>kx(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Fx(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&FG.includes(this.domNode.tagName)||BG.includes(this.role.toLowerCase())||this.domNode?.computedStyles["background-image"]&&this.domNode?.computedStyles["background-image"]!=="none"&&this.children.length===0||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||$r.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let r=this.properties.class;return typeof r=="string"&&r.split(" ").some(n=>Dx(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")||this.children.some(n=>n.isIneligible())?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isIneligible(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=_x){let r=Object.assign({},_x,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=r,l=sS(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===m&&(m="")}let f=uS.includes(this.role)||GG.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
4344
+ //# sourceURL=momentic-injected/extra-scripts.js`}function Zf(t){let e=[],r="";for(let n of t)n==="+"&&r?(e.push(r),r=""):r+=n;return e.push(r),e}var sG=["clipboard-read","clipboard-write","microphone","camera","geolocation","local-network-access"],lG=["local-network-access"];function ax(t){return wr?t.filter(e=>!lG.includes(e)):t}function sx(t){return ax(t||sG)}function lx(t){return t.parentFrame!==void 0}async function cx(t){try{return await cG(t)}catch(e){t.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function cG({locator:t,logger:e}){let[r,n]=await t.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:de}),o=await gn(t,e,500),i=await t.boundingBox({timeout:de});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||n!=="input")return;if(r)try{let c=t.page().locator(`label[for=${JSON.stringify(r)}]`);return await c.waitFor({state:"visible",timeout:de}),{locator:c,relativePoint:void 0}}catch{}let a=await t.evaluate(c=>{let l=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let m={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},g=l._MOMENTIC_FEATURE_FLAGS?.[Jd],h=c.getAttribute(mo),f=!g&&h?hn(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:m,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:de});if(a.type==="error")throw new Error(a.error);let s=t.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:de}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var dx=["date","datetime-local","month","time","week"],ux={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function px(t){try{await $(uG(t),{milliseconds:ce})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function uG({root:t,text:e,options:r,logger:n,callbacks:o}){let i=(await Mt({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:de,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!ux[i])return;ux[i].test(e)&&n.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),r.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as br}from"zod";var mx=br.object({doubleClick:br.boolean().optional(),rightClick:br.boolean().optional(),force:br.boolean().optional(),waitForDownload:br.boolean().optional(),delayMs:br.number().optional(),downloadTimeoutMs:br.number().optional(),relativePosition:br.object({x:br.number(),y:br.number()}).optional()}),hCe=br.object({repeat:br.number().optional(),convertMeta:br.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:br.number().optional()});async function np({locator:t,callbacks:e,logger:r,timeoutMs:n=de}){try{await eS(e,n);let o=t.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let m=window.getComputedStyle(d,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,l),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await $(o,{milliseconds:n}),!0}catch(o){return r.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function eS(t,e=de){let r=await t.state.getRoot();await Mt({root:r,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:t.waitForPageLoad,codePath:"removing element highlights"})}async function tS(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return Wi({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async r=>gx({...t,targetingResult:r,useVisualClick:e})})}async function hG(t,e){let{redirectionAttempts:r=0}=e;if(r>=2)throw t;try{return await gG(t,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:t},"Error handling click error, rethrowing original error"),t):n}}async function gG(t,e){let{logger:r,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(t.message.includes("label")&&t.message.includes("for=")&&t.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:de});if(!i)throw t;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:de}),r.warn({err:t},"Attempting locator redirection due to input being covered by label"),gx({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw r.error({err:t},"Click error does not match any known recoverable patterns, rethrowing"),t}async function fG(t){let{logger:e,targetingResult:r,position:n,options:o}=t,i=mx.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await EG({targetingResult:r,position:n,options:o,logger:e,isAndroid:t.isAndroid});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function SG(t){let{actionSource:e,targetingResult:r,options:n,logger:o}=t,i=t.targetingResult.locator,a=n?.relativePosition??t.position;if(e==="click"&&!a){let l=await cx({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||r.hints?.force||!1;s&&!a&&r.hints?.relativeXYToLocator&&(a=r.hints.relativeXYToLocator);let c=i.toString();o.info({locator:c,position:a},"Locator click");try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:ce,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:ce,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(TG(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),hG(u,{...t,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function gx(t){let{options:e,logger:r,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=t,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Of;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof mG.TimeoutError?new M("ActionFailureError",`Download did not complete in ${u}ms`):new M("ActionFailureError",`Download failed: ${d.message}`)}})());try{await np({locator:a.locator,callbacks:n,logger:r,timeoutMs:de})}catch(u){r.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await fG(t):l=(await SG(t)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new M("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");r.info("Waiting for download to start and complete");let u=await $(s,{milliseconds:e.downloadTimeoutMs??Of});if(u instanceof Error)throw u;return{downloadedFile:await bG(u,o.createIsolatedFolder,r),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function yG(t,e){let r=await t.locator.boundingBox({timeout:ce});if(!r){let i=await gn(t.locator,e,500);throw new M("ActionFailureError",`${Eh}${i?`: ${i}`:""}`)}if(t.hints?.relativeXYToLocator){let i=r.x+t.hints.relativeXYToLocator.x,a=r.y+t.hints.relativeXYToLocator.y;return[{x:i,y:a},"targeting hint"]}let n=r.x+r.width/2,o=r.y+r.height/2;return[{x:n,y:o},"halfway point"]}async function EG({options:t,targetingResult:e,position:r,logger:n}){let o,i,a;if(t?.relativePosition){let u=await e.locator.boundingBox({timeout:ce}),d=t.relativePosition.x,p=t.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(t.relativePosition.x,u.width))),u?.height&&(p=Math.max(0,Math.min(t.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+p,a="relative position from user"}else if(r){let u=await e.locator.boundingBox({timeout:ce});o=(u?.x??0)+r.x,i=(u?.y??0)+r.y,a="predefined position"}else{let[u,d]=await yG(e,n);o=u.x,i=u.y,a=d}let s=e.locator.page(),c=t?.rightClick?"right":"left",l=t?.delayMs??25;return t?.doubleClick?await s.mouse.dblclick(o,i,{button:c,delay:l}):await s.mouse.click(o,i,{button:c,delay:l}),{clickX:o,clickY:i,reason:a}}async function bG(t,e,r){r.info("Download detected, saving file to disk");let n=await t.path(),o=Gf(t.suggestedFilename()),i=e();await t.saveAs(pG(i,o)),hx(n,{force:!0}),setTimeout(()=>{hx(i,{recursive:!0,force:!0})},5*60*1e3);let a=BC(dG(i),o);return r.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function TG(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as vG}from"os";var RG={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function AG(){let t=vG();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function fx(t){return JSON.stringify(t.split("+").sort())}function op(t,e){let r=AG(),n=fx(t);for(let o of Object.values(RG))if(Object.values(o).some(i=>fx(i)===n))return o[r];return process.platform==="darwin"&&!e?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function rS({frame:t,page:e,deltaX:r,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!r&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(t)await Mt({root:t,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[r,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:Ne,codePath:"scrolling page"});else{let d=e.viewportSize()||Kt,p=await Mt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:Ne,codePath:"computing page height"}),[m,g,h]=await Mt({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let S=f.getBoundingClientRect();return[f.scrollTop,S.x,S.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:Ne,codePath:"computing active element position"});await e.mouse.wheel((r??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<Ne;){a?.throwIfAborted();let S=await $(e.evaluate(()=>document.body.scrollHeight),{milliseconds:de}),[y,E,T]=await $(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let w=v.getBoundingClientRect();return[v.scrollTop,w.x,w.y]}),{milliseconds:de});if(S===p&&y===m&&E===g&&T===h)break;p=S,m=y,g=E,h=T,await le(Lt)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function nS(t,e){let r,n;for(let o=0;o<4;o++)try{return r=t.pages(),await Promise.all(r.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await le(Lt)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}async function oS(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,isAndroid:a,hoverDurationMs:s}=t;if(a){await wG(t);return}await e.mouse.move(i.x,i.y),await e.mouse.down(),await e.mouse.move(r+i.x,n+i.y,{steps:o}),await le(s??Vi),await e.mouse.up()}async function Sx({page:t,fromTarget:e,toTarget:r,stepCount:n,dragDurationMs:o,hoverDurationMs:i}){let a=await r.boundingBox({timeout:ce});if(!a)throw new M("ActionFailureError","Could not get bounding box of 'to' target element");let s=await e.boundingBox({timeout:ce});if(!s)throw new M("ActionFailureError","Could not get bounding box of 'from' target element");let c=a.x+a.width/2,l=a.y+a.height/2,u=s.x+s.width/2,d=s.y+s.height/2;await oS({page:t,deltaX:c-u,deltaY:l-d,steps:n,dragDurationMs:o,hoverDurationMs:i,visualTarget:{x:u,y:d},isAndroid:!0})}async function yx(t,e,r,n){await t.mouse.move(e.x,e.y,{steps:3}),await t.mouse.down(),await t.mouse.move(r.x,r.y,{steps:3}),await le(Math.min(n.hoverDurationMs??500,Qd)),await t.mouse.up()}async function wG(t){let{page:e,deltaX:r,deltaY:n,steps:o,visualTarget:i,dragDurationMs:a,hoverDurationMs:s}=t,c=Math.max(1,o??1),l=i.x,u=i.y,d=i.x+r,p=i.y+n;await e.evaluate(async({startX:m,startY:g,endX:h,endY:f,stepCount:S,dragDurationMs:y,hoverDurationMs:E})=>{let T=document.elementFromPoint(m,g)??document.body??document.documentElement,w=window._momenticMobileUtilities.dispatchTouch;w(T,"touchstart",m,g);for(let C=1;C<=S;C+=1){let _=m+(h-m)*C/S,N=g+(f-g)*C/S;w(T,"touchmove",_,N),await new Promise(U=>setTimeout(U,Math.floor((y??500)/S)))}E&&await new Promise(C=>setTimeout(C,E)),w(T,"touchend",h,f)},{startX:l,startY:u,endX:d,endY:p,stepCount:c,dragDurationMs:a,hoverDurationMs:s})}import{randomUUID as LG}from"crypto";import{cloneDeep as sS}from"lodash-es";function Jo(t,e){let r=t.findIndex(n=>n===e);if(!(r===-1||!t[r+1]))return t[r+1]}import{createHash as CG}from"crypto";var xG="v1";function iS(t,e){if(t.tagName.toLowerCase()==="svg"&&!MG(t))try{let r=Ex(t,e),n=_G(JSON.stringify(r));return{version:xG,json:r,hash:n}}catch{return}}function _G(t){return CG("md5").update(t).digest("hex")}function Ex(t,e){let r=t.tagName.toLowerCase(),n=PG(t);if(r==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:r,props:n,children:[]};for(let i of t.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=Ex(a,e);s&&o.children.push(s)}}return o}function MG(t){let e=t.computedStyles.display,r=t.computedStyles.visibility,n=t.computedStyles.opacity;return e==="none"||r==="hidden"||n==="0"}function PG(t){let e={},r=t.attributes;for(let n of Object.keys(r))$r.visualAttributesForSvgSerialization.includes(n)&&(e[n]=r[n]);return r.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=r.id),e}var qi={r:147,g:196,b:125,a:.55},Tx={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:qi,paddingColor:qi,borderColor:qi,marginColor:qi,eventTargetColor:qi,shapeColor:qi,shapeMarginColor:qi,showInfo:!0,showAccessibilityInfo:!0};function vx({snapshot:t,devicePixelRatio:e,computedStylesToFetch:r,logger:n}){let o=t.strings,i=t.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=IG({allDocuments:i,stringConstants:o,computedStylesToFetch:r,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function IG({allDocuments:t,stringConstants:e,computedStylesToFetch:r,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=t[o],l=c.layout,u={};l.nodeIndex.forEach((C,_)=>{u[C]=_});let d=l.styles,p=l.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],S=m.parentIndex??[],y=m.nodeName??[],E=m.nodeType??[],T=m.pseudoType??{index:[],value:[]},v=m.inputChecked??{index:[]},w=e[c.frameId];for(let C=0;C<h.length;C++){let _=h[C],N=E[C],U=f[C]??[],j=S[C]!==void 0&&S[C]>=0?S[C]:void 0,O=j!==void 0?h[j]:void 0,B=O!==void 0?a[O]:void 0,W=T.index.indexOf(C),q=W!==-1?e[T.value[W]]:void 0,ve=u[C],Y;ve?Y=p[ve]??[]:Y=[];let st=y[C]!==void 0?e[y[C]]?.toLowerCase():void 0;if(!st){s.warn({backendNodeId:_,frameId:w,frameIndex:o,nodeBounds:Y},"DOM node has no tag name");continue}let Le={backendNodeId:_,psuedoType:q,nodeType:N,frameIndex:o,parentFrameId:w,ownedFrameId:void 0,bounds:{x:Y[0]??null,y:Y[1]??null,width:Y[2]??null,height:Y[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:O??null,tagName:st,parent:B??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};B&&B.childrenBackendIds.push(_);let gt=g.index.indexOf(C);if(gt!==-1){let Ge=g.value[gt];i[Ge]=Le;let se=t[Ge]?.frameId;Le.ownedFrameId=se!==void 0?e[se]:void 0}for(let Ge of Object.keys(Le.bounds)){let se=Ge;Le.bounds[se]!==null&&(Le.bounds[se]/=n)}let rr=ve!==void 0?d[ve]??[]:[];for(let Ge=0;Ge<rr.length&&!(Ge>=r.length);Ge++){let se=rr[Ge];if(se===void 0||isNaN(se))continue;let Ke=e[se];if(Ke===void 0)continue;let tn=r[Ge];Le.computedStyles[tn]=Ke}for(let Ge=0;Ge<U.length;Ge+=2){let se=U[Ge],Ke=U[Ge+1];if(!se||!Ke)continue;let tn=e[se],ga=e[Ke];!tn||!ga||(Le.attributes[tn]=ga)}v.index.includes(C)&&(Le.attributes.checked="true"),a[Le.backendNodeId]=Le}return a[h[0]]}function aS(t,e){if(t.mPathSelector)return t.mPathSelector;let r=t.parent,n;if(!r)n=t.tagName;else if(t.tagName==="body")n="body";else{let i=r.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(t.backendNodeId),a=` > ${t.tagName}:nth-child(${i+1})`;n=`${aS(r,e)}${a}`}return t.mPathSelector=n,n}function bx(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var OG=["html","#document","#document-fragment"];function Rx({node:t,domGraph:e}){let r=[],n=t,o=bx(t,e);if(!o)return[t.tagName];let i=()=>{if(n=o,o=bx(o,e),!o&&n.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,OG.includes(n.tagName)){i();continue}if(n.tagName==="body")r.push("body");else{let c=!1,l=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){r.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return r.reverse()}function Ax(t,e){let r=t.locator("html"),n=[];for(let o=0;o<e.length;o++){let i=e[o];if(n.push(i),i.startsWith("iframe")){let a=n.join(" > ");n=[],o<e.length-1?r=r.frameLocator(a):r=r.locator(a)}}if(n.length&&(r=r.locator(n.join(" > "))),"owner"in r)throw new Error("Final locator from mpath is a frame locator");return r}async function wx(t,e){await t.send({method:"DOM.getDocument",params:{depth:0},timeout:Ne});let r=await t.send({method:"DOM.requestNode",params:{objectId:e},timeout:Ne}),o=(await t.send({method:"DOM.getAttributes",params:{nodeId:r.nodeId},timeout:Ne})).attributes,i=Jo(o,mo);if(!i)throw new Error(`Could not find attribute ${mo} for object ${e}`);return i}var NG=["focusable","keyshortcuts","controls","live","relevant","orientation"],DG=["selected","readonly","modal","required","invalid"],kG=["id","name","role","content"],Cx=["absolute","fixed","sticky"],FG=["i","label"],UG=["path"],BG=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator","LabelText"],Mx=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Px=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],zG=["menulistpopup","statictext","inlinetextbox"],HG=80,xx=100,Ix=50,uS=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],GG=["cite"],jG={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},VG={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},_x={indentLevel:0},lS=class t{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;flagNotActionableNodes;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,this.flagNotActionableNodes=e.flagNotActionableNodes,e.properties&&e.properties.forEach(r=>{r.name==="keyshortcuts"?this.dataMomenticId=parseInt(r.value.value):this.properties[r.name]=r.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let r=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(r&&r.length<Ix?r:""),this.role=this.role||(e.domNode.attributes.role??""),KG(this.properties,e.domNode,e.importantProperties)}XG(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&UG.includes(this.domNode.tagName)&&!this.domNode.attributes["aria-label"]||this.ignoredReasons.some(n=>Px.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>kx(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Fx(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&FG.includes(this.domNode.tagName)||BG.includes(this.role.toLowerCase())||this.domNode?.computedStyles["background-image"]&&this.domNode?.computedStyles["background-image"]!=="none"&&this.children.length===0||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||$r.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let r=this.properties.class;return typeof r=="string"&&r.split(" ").some(n=>Dx(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")||this.children.some(n=>n.isIneligible())?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isIneligible(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=_x){let r=Object.assign({},_x,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=r,l=sS(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===m&&(m="")}let f=uS.includes(this.role)||GG.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
4345
4345
  `;let S=`${u}<${p}`;!a&&!f&&(S+=` id="${this.id}"`);let y=s??!1;if((l.multiline||l.contenteditable)&&this.children.length>0&&(y=!0),d&&d!=="generic"&&d!==p&&!(jG[d]??[]).includes(p)&&(S+=` role=${JSON.stringify(d)}`),m&&(S+=` name=${JSON.stringify(m)}`),this.content&&!y&&(S+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isIneligible()&&(S+=` ${$r.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let v=this.domNode.bounds,w=Math.round(v.x??0),C=Math.round(v.y??0),_=Math.round((v.x??0)+(v.width??0)),N=Math.round((v.y??0)+(v.height??0));S+=` bounds=[${w} ${C} ${_} ${N}]`}let E=Date.now();if(Object.keys(l).length>0&&!i){if(Date.now()-E>1e3)throw new Error(`Serialization for the HTML element with tag ${p} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(l).forEach(([v,w])=>{if(!NG.includes(v)){{if(DG.includes(v)&&(!w||w==="false"))return;if(v==="value"&&y&&(l.type==="text"||this.role==="textbox"))return;if(v==="level"&&`${w}`=="1")return;if(v==="url"&&l.src&&p==="img")return;if(v==="url"&&l.href&&p==="a")return;if(v==="editable"&&w==="plaintext")return;if(v==="type"&&w===p)return;if(c&&!VG[v])return}typeof w=="string"?S+=` ${v}="${tt(w,xx,!0)}"`:typeof w=="boolean"?w?S+=` ${v}`:S+=` ${v}={false}`:typeof w<"u"&&(S+=` ${v}={${tt(JSON.stringify(w),xx,!0)}}`)}})}if(p==="::before"||p==="::after"){let v="";for(let w of this.children)v+=w.serialize({...e,indentLevel:n,neighbors:0});return v}let T=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||T)S+=` />
4346
4346
  `;else{let v="";for(let C of this.children)v+=C.serialize({...e,indentLevel:n+2,neighbors:0});let w=v.trim();w.length<=HG&&!w.includes(`
4347
4347
  `)?S+=`>${w}</${p}>
@@ -4353,7 +4353,7 @@ ${C||""}`}return S}shallowClone(){let e=new t({id:this.id,role:this.role,name:th
4353
4353
  //# sourceURL=momentic-injected/browser-scripts.js`}),this.context.addInitScript({content:Qf(i,this.userBrowserSettings.disableFullStory)}),this.exposeRecordingBindings());let s=d=>this.handleNewPageEvent(d);this.context.on("page",s),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",s)});let c=!1;if(n){let d=async()=>{let p=Date.now();try{await Promise.all([this.page.addScriptTag({content:`${If.htmlUtilsLibJs}
4354
4354
  //# sourceURL=momentic-injected/browser-scripts.js`}),this.page.addScriptTag({content:Qf(i,this.userBrowserSettings.disableFullStory)})])}catch(m){if(m instanceof Error&&m.message.includes("Content Security Policy"))this.logger.warn({err:m},"Content Security Policy error from adding Momentic scripts, reloading page instead"),c=!0;else throw m}(o??{})["add-init-scripts"]=Date.now()-p};a.push(d())}if(!this.properties.systemDevicePixelRatio)if(process.env.MOMENTIC_LOCAL_DEV==="1"&&gj()==="darwin"&&cj("system_profiler SPDisplaysDataType").toString().includes("Retina"))b.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2;else{let d=async()=>{let p=Date.now();this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio),(o??{})["fetch-dpr"]=Date.now()-p};a.push(d())}let l=Date.now();await $(Promise.all(a),{milliseconds:this.pageLoadTimeout,message:"Timed out attaching Chrome permissions and initialization scripts",signal:this.abortSignal});let u=Date.now();(o??{})["ops-attach"]=u-l,c&&await this.page.reload(),this.cdpClient=await ip.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),(o??{})["cdp-init"]=Date.now()-u,await this.initializeScreencast(),this.stateManager=new lp({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let r=e.sessionId,n=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=n,this.clientCallbacks?.onScreencastFrame?.(n,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:r}})}catch{}})()})}))}static async init(e){let r=await ix(e),n=new t(r);return await n.initialize({grantPermissions:!0,permissionsToGrant:e.userBrowserSettings.grantedPermissions,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:r,enricher:n,userBrowserSettings:o,properties:i,logger:a,timingRecorder:s}){let c=e.pages()[0];if(!c)throw new Error("No page found in existing context");let l=c.viewportSize();if(!l){let p=Date.now();l=await c.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})),s["eval-viewport"]=Date.now()-p}let u=c?.url(),d=new t({browser:e.browser(),context:e,page:c,baseUrl:u,logger:a,storage:r,enricher:n,userBrowserSettings:o,viewport:l,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0,timingRecorder:s}),d}async handleAvailableTabsChangeHelper(){try{let e=await nS(this.context,{getTitles:!0}),r=this.page.url();this.clientCallbacks?.onTabsChange?.(e,r)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,r){let n=hS(),o=`${e}-${n}`,i=Date.now(),a=!1,s=new AbortController;this.pageLoadAbortControllers.add(s);let c=async()=>{try{await $(r(),{signal:s.signal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&!this.closed&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],this.pageLoadAbortControllers.delete(s),a=!0}};this.pageLoadPromises[o]=c().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let r=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let i=n[o];if(!(!i||i.isClosed()||!Bi(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>r())}handleNewPageEvent(e){let r=e.url();this.logger.info({url:r},"Detected new page event, registering handlers and waiting for load to complete");try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let r=hS(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableConsoleLogs&&e.on("console",a=>{jC(e,o,this.debugData,a,this.logger)});let i=async()=>{!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableNetworkLogs&&(WC(this.logger,r,this.clientCallbacks?.onNetworkPage,e),!this.harBatcher&&this.clientCallbacks?.onNetworkLogs&&(this.harBatcher=Kx(this.clientCallbacks.onNetworkLogs)),await e.route("**/*",async(a,s)=>{await $f({pageId:r,route:a,request:s,onHarEntry:(c,l)=>{this.harBatcher?.fetch({[c]:l}).catch(()=>{})},logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks,isBrowserClosed:()=>this.closed})}),await e.route("**/*",JC(this.customHeaders,this.logger))),wr&&await e.route("**/*",nc),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}handleFrameNavigationEvent(e){let r=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${r.slice(0,50)} (${n})`;if(!r||r==="about:blank"||!Bi(r))return;let i=this.recentFrameNavigations[o];if(i&&Date.now()-i<1e3)return;this.recentFrameNavigations[o]=Date.now();let a=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(c){this.logger.warn({err:c},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(s){s.name!=="AbortError"&&this.logger.warn({err:s,url:r,codePath:o},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>a())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let n={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(n[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},n)}catch(r){this.logger.warn({err:r},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){this.abortSignal=void 0,this.debugData.logsPerPage=[],this.pageLoadPromises={},await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await $(eS(this.getBrowserCallbacks()),{milliseconds:de})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0,this.cleanedUp=!0;try{this.pageLoadAbortListenerCleanup?.(),this.pageLoadAbortListenerCleanup=void 0,this.pageLoadAbortControllers.forEach(e=>e.abort()),this.pageLoadAbortControllers.clear(),this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.cleanedUp||this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,r,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<hs;){a++,n?.throwIfAborted();try{if(await Mt({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:de,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(i++,i>=3){r.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await le(Lt),a%2===0&&r.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),Mt({root:e,fn:()=>{let r=window;if(!r?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return r.getFullHtmlTree()},arg:void 0,timeout:ce,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,r=[],n=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{n.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),r.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of r)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:r=1,stabilizeBeforeScreenshot:n=!1}=e,o=this.page.url();n&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:r});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(r<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await le(Vi),this.screenshot({...e,retries:r-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),n&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:r,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:r,optimizeForSpeed:!0},timeout:o??Ne}),c=Buffer.from(s.data,"base64"),l=await Jx.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(l.bitmap.width!==u||l.bitmap.height!==d)&&(c=await l.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&pj(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:ce});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:g,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");m=Math.floor(m),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let S=await Jx.fromBuffer(c),y=S.bitmap.width,E=S.bitmap.height;m=Math.max(0,Math.min(m,y-1)),g=Math.max(0,Math.min(g,E-1)),h=Math.max(1,Math.min(h,y-m)),f=Math.max(1,Math.min(f,E-g)),c=await S.crop({x:m,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(S){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${g}) with size (${h}, ${f}): ${S}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:r=!1,loadTimeoutMs:n=this.pageLoadTimeout}){kw(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();r||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"}),i=!0;break}catch(l){if(a=l,this.abortSignal?.throwIfAborted(),this.logger.warn({err:l},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await le(Lt),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:de})}if(!i)throw new M("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if(DC.has(s))throw new M("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);await this.fixViewportForNewHeadless()}async type(e,r={},n=!1){await this.directTypeHelper(e,r,n)}async getActiveElementHandle(e){return e.evaluateHandle(()=>document.activeElement)}async getActiveElement(e){try{return await Mt({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]");let o=!1,i=window.getSelection();i&&!i.isCollapsed&&i.toString().trim().length>0&&(o=!0);let a=document.activeElement;return a&&"selectionStart"in a&&typeof a.selectionStart=="number"&&typeof a.selectionEnd=="number"&&a.selectionStart!==a.selectionEnd&&(o=!0),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n,hasTextSelected:o}:{hasTextSelected:o}},arg:void 0,timeout:de,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(r){this.logger.warn({err:r},"Failed to get active element");return}}async directTypeHelper(e,r={},n=!1){let o=await this.getActivePageOrFrame();await px({root:o,text:e,options:r,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let s=Date.now();for(;Date.now()-s<this.smartWaitingTimeout&&(!i||i.tag==="body");)await le(Vi),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}let a=i?.tag==="input"||i?.tag==="textarea";if(r.clearContent)if(a||r.forceClearContent)if(this.properties.isAndroid&&!a&&i?.textContent){this.logger.info("Clearing content using backspaces");let s=0,c=i.textContent?.length;for(;c&&s<50;){s++;let l=[...Array(c)].map(()=>"Backspace").join("+");await this.page.keyboard.press(l),i=await this.getActiveElement(o),c=i?.textContent?.length}c&&this.logger.warn("Content still remains after clearing existing")}else this.properties.isAndroid?await this.page.keyboard.press("Control+A"):process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25);else this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...");await this.page.keyboard.type(e,{delay:r.delay??$E}),r.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:Ne})}catch(r){this.logger.warn({err:r},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async n=>{let o=n.scrollTop;n.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=n.scrollTop;if(a===o)break;o=a,await new Promise(s=>setTimeout(s,250))}},void 0,{timeout:Ne})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:r}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(r.locator),!0}catch(r){return this.logger.debug({err:r,id:e},"Failed to highlight target"),!1}}async highlight(e){return np({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let r=new URL(e).origin;if(r==="null")return;this.originsVisited.add(r)}catch(r){this.logger.warn({err:r},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),r=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;r.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:r},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:r},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(r),r=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:de}),this.originsVisited.delete(o);let r=this.context.pages().indexOf(this.page),n=[...this.context.pages()];for(let o=0;o<n.length;o++){let i=n[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await GC(i,this.logger),o!==r&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let r=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);r=r.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:de});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:de,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(s){this.logger.warn({err:s,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await HC(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let r=0,n=null;for(;r<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await zC(this.page,this.logger),o}catch(o){if(n=o,r++,r<=2){this.logger.warn({err:o,retryCount:r,maxRetries:2},`Error saving auth state, retrying (${r}/2)...`);let i=Math.pow(2,r)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new M("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return nS(this.context,e)}saveA11yDetailsToCache(e,r){r.content=e.content,r.name=e.name,r.role=e.role,r.numChildren=e.children.length,delete r.serializedForm,delete r.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:r,locator:n,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,r),r.frameCache=this.stateManager.saveAutoFrameCacheDetails(r.frameCache),n)try{let s=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});s?(r.generatedSelectors=s.generatedSelectors,r.serializedHtml=s.serializedHtml,r.nodeOnlySerializedHtml=s.nodeOnlySerializedHtml,r.hybridSelector=s.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(s){if(s instanceof Rn)throw a.warn({err:s},"Cache attributes disqualify found element"),s;a.warn({err:s},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:r,locator:n,logger:a,boundingBox:o})}catch(s){a.debug({err:s},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:r,logger:n,boundingBox:o}){if(!r)return{scrollPerformed:!1};if(!Nf.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(r),o||(o=await r.boundingBox({timeout:ce})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:s=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let l=await this.screenshot({locator:r,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(l),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({logger:e,locator:r,requirements:n}){let o={},i=!!n?.position&&n.position!=="irrelevant",a=!!n?.shape&&n.shape!=="irrelevant";if(i||a){let s=await r.boundingBox({timeout:ce});if(!s||!s.width||!s.height)throw new M("ActionFailureError","Element does not have a bounding box as required");a&&(o.shape={width:s.width,height:s.height,tolerance:n.shape}),i&&(o.position={x1:s.x,y1:s.y,x2:s.x+s.width,y2:s.y+s.height,tolerance:n.position})}if(n?.text){let s=await r.textContent({timeout:ce});o.text=s?.trim()}if(n?.attributes&&n.attributes.length>0){let s={};for(let c of n.attributes){let l=c.trim().toLowerCase();if(!(!l||$r.bannedAiRequiredCacheAttributes.includes(l)))try{let u=await r.getAttribute(l,{timeout:ce});u!==null&&(s[c]=u)}catch(u){e.warn({err:u,attr:c},"Failed to fetch required attribute, continuing...")}}o.attributes=s}return o}async getAdditionalElementDetails({mainLocator:e,additionalElement:r,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[r.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let s=await this.fetchHtmlAttributes({locator:a,logger:o});if(!s?.generatedSelectors||s.generatedSelectors.length===0)return;let c={selectors:s.generatedSelectors};return r.requirements&&(c.requirements=await this.getElementRequiredValues({logger:o,locator:a,requirements:r.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:r,additionalElements:n,root:o,logger:i}){let a=new Set,s=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let l=await this.getAdditionalElementDetails({mainLocator:r,additionalElement:c,root:o,logger:i});if(a.add(c.id),!l)continue;s.push(l)}catch(l){this.logger.warn({err:l,additionalElement:c},"Failed to fetch additional element details, continuing...")}return s}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:r,additionalElements:n,target:o,locator:i,root:a,logger:s}){if(r)try{o.requirements=await this.getElementRequiredValues({logger:s,locator:i,requirements:r})}catch(c){s.warn({err:c},"Failed to generate required values for target")}n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:s}))}async createTargetFromA11yId({id:e,description:r,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:s}){if(e<0)throw new M("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new M("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let l=this.stateManager.frameConfig,u,d,p,m;if(this.userBrowserSettings.autoExpandIframes&&!l&&c.parentFrame){let y=c.parentFrame,{cache:E,config:T}=await this.stateManager.getAutoFrameDetailsFromHandle(y);d=E,p=T,u=T.frame,m="auto iframe"}else c.parentFrame&&l?(p=l,u=await this.getActivePageOrFrame(),m="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),m="should not be possible");let g=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:r??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:je(i),frameCache:d},f,S=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:Vx(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),S=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:s,target:h,root:u,locator:g,logger:i}));try{return{resolution:{locator:g,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,frameConfigSource:m}}finally{S&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,r,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:s}=n;if(r.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(r.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){m=f,await le(Lt,a)}if(!g)throw m}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let l=Date.now(),u=0,d=0,p;for(;Date.now()-l<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let m=u===2||Date.now()-l>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:r,primaryOnly:!0,shouldLogOnFailure:m,logger:i,allowNotActionableNodesOverride:s,signal:a});break}catch(g){if(g instanceof ml)break;if(g instanceof Rn){if(d++,d>2)throw i.error({err:g},"Got multiple cache disqualification errors, giving up"),g;i.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await le(Lt,a)}a?.throwIfAborted(),m&&i.warn({err:g},`Could not resolve target using primary cache only (x${u})`),await le(Lt,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:r,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:s}),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:r.targetSource,targetUpdateTime:r.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:r,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a,shouldLogOnFailure:s}){let c=[],l,u=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),d;if(r.generatedSelectors||r.hybridSelector){let p;try{p=await this.resolveTargetWithPrimaryMethods({root:e,target:r,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:s})}catch(m){d=m,m instanceof kr&&(c.push(...m.decisions),l=m.cacheMissReason)}if(p)return{...p,pageState:void 0,decisions:[...c,...p.decisions]};n||(c.push({type:"CSS_SELECTOR",matched:!1,reason:d?.message,selectors:ic(r.generatedSelectors??[])}),r.generatedSelectors=void 0,r.hybridSelector=void 0)}if(n)throw d;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let p=await this.resolveTargetWithSecondaryMethods({root:e,tree:u,target:r,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(p)return r.targetSource="HEURISTIC_HEALED",r.targetUpdateTime=new Date().toISOString(),r.targetUpdateLoggerTags=je(o),p;l=l??"secondary-resolution-failed"}throw new kr("Could not find any relevant node given target",c,l)}async resolveTargetWithPrimaryMethods({root:e,target:r,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i}){if(!r.nodeOnlySerializedHtml)throw new ml("Insufficient data to resolve target using primary methods (missing node HTML)");let a={x:0,y:0};if(lx(e)){let w=await(await e.frameElement()).boundingBox();w&&(a=w)}let s=i?n:Pn,c=this.userControlledBrowserSettings.hybridSelectorMode,l={ldistThreshold:Lf,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?r.boundingBox:void 0,requirements:r.requirements,additionalElements:r.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},rootBoundingBox:a},{css:u,hybrid:d}=await Mt({fn:w=>window.evaluatePrimaryCaches(w),arg:{cssParams:{selectors:r.generatedSelectors??[],cachedElementSerialized:r.nodeOnlySerializedHtml,opts:l},hybridParams:c&&r.hybridSelector?{nodes:r.hybridSelector,cachedElementSerialized:r.nodeOnlySerializedHtml,opts:l}:void 0},root:e,timeout:ce,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),p,m,g=[];if(c==="prefer"&&d?.result){p=d.result;let w={type:"HYBRID_SELECTOR",matched:!0,logs:d.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};g.push(w),m="HYBRID_SELECTOR"}else if(u?.result){p=u.result;let w=`${p.workingSelectors.length} CSS selectors matched the following element: ${p.serializedElement}`,C=p.workingSelectors.slice(0,5);g.push({type:"CSS_SELECTOR",matched:!0,logs:u.logs,reason:w,selectors:C}),n.debug({reason:w,workingSelectors:C},"Resolved with CSS selectors"),m="CSS_SELECTOR"}else throw g.push({type:"CSS_SELECTOR",matched:!1,reason:u.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:u.logs}),d&&g.push({type:"HYBRID_SELECTOR",matched:!1,reason:d.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:d.logs}),u?.error&&n.error({err:new Error(u.error)},"Cache evaluation errored unexpectedly (CSS)"),d?.error&&n.error({err:new Error(d.error)},"Cache evaluation errored unexpectedly (Hybrid)"),new kr("Cache evaluation failed",g,u.cacheMissReason);let h,f,S;if(this.userBrowserSettings.visualActions){let w=p.mPath;if(!w)throw new Error("Found element did not have an mPath despite using visual actions");let C=w.join(" > ");h=e.locator(C),f=this.stateManager.getNodeUsingMPathSelector(C)}else if(p.dataMomenticId!==void 0)S=parseInt(p.dataMomenticId),f=this.stateManager.dataMomenticIdToNodeMap[S],"workingSelectors"in p?h=e.locator(p.workingSelectors[0]):h=e.locator(hn(S));else throw new M("InternalWebAgentError","Received an element resolution result with no identifying attributes");c&&r.hybridSelector&&(d?.logs.length===1?s.warn({hybridResult:d,cssResult:u,hybridMode:c},"Hybrid selector resolution rejected, continuing..."):d?.result?u?.result&&d?.result&&d.result.serializedElement!==u.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(u.result.mPath)!==JSON.stringify(d.result.mPath)?n.warn({originalCache:r,hybridResult:d,cssResult:u,hybridMode:c,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):u.result.dataMomenticId!==d.result.dataMomenticId&&n.warn({originalCache:r,hybridResult:d,cssResult:u,hybridMode:c,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):s.warn({originalCache:r,hybridResult:d,cssResult:u,hybridMode:c},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let[y,E]=await Promise.all([h.textContent({timeout:de}),h.evaluate(w=>w.getBoundingClientRect(),{timeout:de})]);if((y??"")!==(p.textContent??""))throw n.warn({currentTextContent:y,originalTextContent:p.textContent},"Retrying cache resolution because element's text content has changed since resolution"),new Error("Element's text has changed since cache was resolved");if(Math.abs(E.height-p.boundingBox.height)>1||Math.abs(E.width-p.boundingBox.width)>1||Math.abs(E.x-p.boundingBox.x)>1||Math.abs(E.y-p.boundingBox.y)>1)throw n.warn({currentBoundingBox:E,originalBoundingBox:p.boundingBox},"Retrying cache resolution because element's bounding box has changed since resolution"),new Error("Element's bounding box has changed since cache was resolved");let T=ic(r);await this.updateCacheWithNewNodeDetails({node:f,target:r,locator:h,logger:n,startingBoundingBox:p.boundingBox,allowNotActionableNodesOverride:o});let v=gS(T,r);return v&&Object.keys(v).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=je(n),r.cacheResolutionUpdateSource=m),{a11yNode:f,displayString:p.serializedElement,locator:h,decisions:g}}async resolveHardcodedCssSelector(e){let{ctx:r,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),c=Date.now(),l=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),l++;let p=s.locator(n),m;try{return await p.waitFor({state:"attached",timeout:de}),m=await gn(p,o,500)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),r?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:d,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:p,displayString:m,decisions:d}}catch(g){let h=g.message;u=new M("ActionFailureError",`CSS selector '${n}' failed to resolve after ${l} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await le(Lt,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:r,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let s=await a.locator.boundingBox({timeout:ce});if(!s){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:l,width:u,height:d}=s;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!r||!n||!c||!l){this.logger.debug({oldX:r,oldY:n,newX:c,newY:l,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-r)>100||Math.abs(l-n)>100){this.logger.debug({newX:c,newY:l,oldX:r,oldY:n,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:r,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(r.nodeOnlySerializedHtml&&r.nodeOnlySerializedHtml.trim().length<NC){let l="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:l})}else if(r.nodeOnlySerializedHtml&&r.nodeOnlySerializedHtml.length>50)try{let l=await Mt({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:r.nodeOnlySerializedHtml},timeout:Ne,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(Lf*r.nodeOnlySerializedHtml.length);if(l&&l.closestDistance&&l.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${l.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:l.closestDistance,closestElement:l.closestNodeSerialized})}else{if(l?.error)throw new Error(l.error);if(l?.dataMomenticId||l?.mPathSelector){let d=l.dataMomenticId?parseInt(l.dataMomenticId):void 0,p,m;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(hn(d));else if(l.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(l.mPathSelector),m=e.locator(l.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=l.closestNodeSerialized??await gn(m,o,500)??"unknown element";o.warn({result:l,originalTarget:r,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=ic(r);await this.updateCacheWithNewNodeDetails({node:p,target:r,locator:m,logger:o,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:a});let f=gS(h,r);return f&&Object.keys(f).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=je(o),r.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:l},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:l.logs,distance:l.closestDistance,closestElement:g,savedElement:r.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(l)}`)}}catch(l){o.info({err:l},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${l}`})}let s=r.screenshotUrl,c=r.role??"";if(s&&Nf.includes(c))try{let l=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:r,screenshotUrl:s,signal:i,allowNotActionableNodesOverride:a});return{...l,decisions:[...n,...l.decisions],pageState:void 0}}catch(l){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${l}`,elementImageUrl:s}),o.warn({err:l},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({screenshotUrl:e,oldTarget:r,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),l=yj(),u=await this.enricher.runTemplateMatching({id:l,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),m=d.boundingBox?.width,g=d.boundingBox?.height;if(!m||!g)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],S=ic(r);await this.updateCacheWithNewNodeDetails({target:r,node:f,locator:p,allowNotActionableNodesOverride:o});let y=gS(S,r);return y&&Object.keys(y).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=je(this.logger),r.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:l,diffs:y,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,r,n={}){await this.highlight(r.locator);let o=await r.locator.getAttribute("type",{timeout:de})??"",i=dx.some(a=>a===o.toLowerCase());return await tS({targetingResult:r,options:{force:n.force,relativePosition:n.relativePosition},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks(),isAndroid:this.properties.isAndroid??!1}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,r,n={}){return tS({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:r,browserCallbacks:this.getBrowserCallbacks(),isAndroid:this.properties.isAndroid??!1})}async waitForUrl({beforeUrl:e,matcher:r},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),Nd(s,r,n)){a=!0;break}await le(Lt,this.abortSignal)}if(!a)throw new M("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${Sd(r)} in ${o}ms.
4355
4355
  Current tab: ${s}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,r,n={}){let o=n.steps??5,i=Math.min(n.hoverDurationMs??500,Ne);if(await this.highlight(e),this.properties.isAndroid){await Sx({page:this.page,fromTarget:e,toTarget:r,stepCount:o,dragDurationMs:n.dragDurationMs??1e3,hoverDurationMs:i}),await this.highlight(r);return}await this.hover({locator:e}),await this.page.mouse.down();let a=await r.boundingBox({timeout:ce});if(!a)throw new M("ActionFailureError","Could not get bounding box of target element");let s=a.x+a.width/2,c=a.y+a.height/2;await this.page.mouse.move(s,c,{steps:o}),await le(i),await this.highlight(r),await this.page.mouse.up()}async mouseDrag(e,r,n,o){o&&await this.hover({locator:o}),await this.page.mouse.down();let i;if(o){let a=await o.boundingBox({timeout:ce});a&&(i={x:a.x+a.width/2,y:a.y+a.height/2})}i||(this.logger.warn("Could not get starting position from fromTarget, falling back to (0,0)"),i={x:0,y:0}),await this.page.mouse.move(i.x+e,i.y+r,{steps:n}),await le(Vi),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await Wi({func:async r=>{await this.scrollIntoViewIfNeeded(r.locator);let n=await r.locator.boundingBox({timeout:ce});if(!n)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(n.x+n.width/2,n.y+n.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await Wi({func:r=>r.locator.focus({timeout:Ne}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let r=await this.getActivePageOrFrame();await Mt({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:r,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:de,codePath:"blurring the active element"});return}await this.highlight(e.locator),await Wi({func:r=>r.locator.blur({timeout:Ne}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,r,n=!1){await this.highlight(e.locator),await Wi({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(r.type==="INDEX"){let i=Number(r.index);if(isNaN(i))throw new M("UserConfigurationError",`Page index ${r.index} is not a number`)}await o.locator.selectOption({value:r.type==="VALUE"?r.value:void 0,label:r.type==="LABEL"?r.label:void 0,index:r.type==="INDEX"?Number(r.index):void 0},{force:n,timeout:ce})},targetingResult:e})}async press(e,r){let n=r.repeat??1;if(r.convertMeta){let o=op(e,this.properties.isAndroid);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:r.delayMs??0})}async keyDown(e,r){if(r.convertMeta){let n=op(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Zf(e))await this.page.keyboard.down(n)}async keyUp(e,r){if(r.convertMeta){let n=op(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of Zf(e))await this.page.keyboard.up(n)}async refresh(e){let r=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:r});break}catch(i){this.logger.warn({err:i,attempt:n},`Failed to reload page${n<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:r=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i,shouldLogOnFailure:a}=e,s=e.abortSignal??this.abortSignal,c=!i,l=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:Pn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:s});let d=0,p;for(;d<r;){d++;try{return await $(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:s,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:l,flagNotActionableNodes:c}),{milliseconds:this.pageLoadTimeout*d,signal:s,message:"Getting browser state took too long"})}catch(m){if(s?.throwIfAborted(),p=m instanceof Error?m.message:`${m}`,d>=r)throw m;u.warn({err:m,url:this.url()},"Error getting a11y tree, retrying...")}}throw new M("ActionFailureError",`Getting page content failed after ${r} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[r,n,o,i,a]=await Mt({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:ce,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:r,lowerBound:r+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:r=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},s=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let l=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",l);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,r,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",l),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,r,n,o){let i=!1,a=Date.now(),s,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},l=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await le(Vi,this.abortSignal),s)try{let d=await this.screenshot(c);if(!d.equals(s)){s=d,l=!1;continue}l=!0}catch(d){u++,u%3===0&&r.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(c)}catch(d){u++,u%3===0&&r.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<LC)){i=!0;break}}i||r.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:l}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,r){let{x:n,y:o}=e;this.logger.debug({x:n,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(n,o,{button:r.rightClick?"right":"left",clickCount:r.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,r,n){await yx(this.page,e,r,n)}async mouseDragUsingVisualCoordinates(e){let{fromTarget:r,...n}=e;await oS({...n,page:this.page,visualTarget:r,isAndroid:this.properties.isAndroid??!1})}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y,{steps:3})}async getElementLocation(e){let r=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:ce}),n=await $(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:Ne});process.platform==="darwin"&&n===1&&(n=IC);let o=r.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],c=a.backendNodeId||[],l=i.nodeIndex,u=i.bounds,d=-1;for(let y=0;y<s.length;y++)if(c[y]===e){d=l.indexOf(y);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,m=0,g=0,h=0]=u[d];p/=n,m/=n,g/=n,h/=n;let f=p+g/2,S=m+h/2;return{centerX:f,centerY:S}}async scrollVertical(e){return rS({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return rS({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,r){if(await this.stopScreencast(),this.recordUrlVisited(e.url()),this.onVideoPageChange){let n=await e.video()?.path();if(n){let o=Qx(n);this.onVideoPageChange({videoName:o})}}this.page=e,await this.reinitializeCDPClient(r??this.pageLoadTimeout)}async createNewTab(e,r){let n=await this.context.newPage();await this.changeActivePage(n,r?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...r}),this.handleAvailableTabsChange()}async switchToPage(e,r){let n=!0,o,i=Date.now();for(;n||r?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,r);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await le(Lt)}}throw o}async switchToPageHelper(e,r){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new M("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
4356
- Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Bi(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,r?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let r;return typeof e=="string"?r=Ju(e):r=[e],await this.context.addCookies(r),r}async setLocalStorage(e,r){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,r],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){try{await $(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},r)=>{this.transformer&&Yx({event:r,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,r)=>{this.transformer&&this.transformer.recordKeystroke(r)})}async startRecordingCrons(e){if(e.aborted)return;let r,n=(await this.getOpenPages()).map(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(r);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];Bi(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:n,currentUrl:l,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};r=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},Lt);let s=async()=>{clearInterval(r)};e.addEventListener("abort",s,{once:!0})}async startRecording(e,r,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=r,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:de})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:r,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await ql({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:r,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new M("UserInfrastructureError",`The page with URL ${tt(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await ql({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:r,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:r=!1}=e??{};return r||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return mj.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:r,error:n}=await Mt({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:Ne,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!r)throw new M("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return r}registerDialogHandler(e){let r=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",r)}async evaluateFunctionInAllFrames(e,r){return this.stateManager.executeFunctionInAllFrames(e,r)}async evaluateFunctionInPage(e,r,n,o=Ne){let i=await this.getActivePageOrFrame();return Mt({root:i,fn:e,arg:r,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:r,context:n,timeoutMs:o=ko}){let i=XC(),a={code:e,fragment:r,context:n},{result:s}=await $(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new M("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,r){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:Ne});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:r},timeout:de})}catch(o){throw this.logger.error({err:o,x:e,y:r},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:r,percentY:n}){if(r<0||r>1||n<0||n>1)throw new M("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),c=Math.round(a),l=Math.round(s),u=Math.ceil(o*r),d=Math.ceil(i*n),p=u+l,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let r=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(r,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:de,params:{highlightConfig:Tx,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:de,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:de})}catch{}}async getTargetFromPositionPercentages(e){let r=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(r,e);return this.getTargetFromBackendNodeId({root:r,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:r,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[r];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[mo],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(hn(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let l=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:s}}async performTargetRedirection(e,r,n){try{return await this.scrollIntoViewIfNeeded(e),await $(this.performTargetRedirectionHelper(e,r,n),{milliseconds:ce})??{locator:e}}catch(o){return r.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,r,n){let o=Date.now();if(n===void 0&&(n=await e.boundingBox({timeout:ce})??void 0),!n){let E=await gn(e,r,500);r.error(`Attempted to click on element with no bounding box: ${E}`);return}let{x:i,y:a,width:s,height:c}=n,l=this.getViewport();if(i<0||a<0||!l||i+s>l.width||a+c>l.height){r.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:d,mPathSelector:p,error:m,serializedElement:g,foundElementRelativePoint:h,force:f,logs:S}=await e.evaluate(E=>{let T=window;if(!T.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return T.performTargetRedirection(E)},void 0,{timeout:de}),y=Date.now()-o;if(m){r.warn({error:m,serializedElement:g,duration:y,force:f,logs:S},"Got error from target redirection with bounding box");return}else{if(d)return r.info({newDataMomenticId:d,serializedElement:g,duration:y,force:f,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(hn(d)),hints:{relativeXYToLocator:h,force:f}};if(p)return r.info({newMPathSelector:p,serializedElement:g,duration:y,force:f,logs:S},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(p),hints:{relativeXYToLocator:h,force:f}};if(h)return r.info({foundElementRelativePoint:h,serializedElement:g,duration:y,force:f,logs:S},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:h,force:f}};if(f)return r.info({serializedElement:g,duration:y,force:f,logs:S},"Forcing click on original element"),{locator:e,hints:{force:f}}}}async fetchHtmlAttributes({locator:e,logger:r=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,s=await e.evaluate((c,l)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,l):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:Ne});if("error"in s&&s.error)throw s.error.startsWith(_C)?new Eu(s.error):s.error.startsWith(MC)?new bu(s.error):new Error(s.error);return s.warnings.length&&r.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,r){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*r);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,r,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*r),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:de})}async scrollFromPositionPercentages(e,r,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),s=Math.ceil(i.height*r);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:s,x:n,y:o}}),{deltaX:a,deltaY:s}}canSolveCaptchas(){return!!kC}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(r){this.logger.debug({err:r,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,r,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,jf(e,this.debugData,i,{type:r,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:r}){if(!cp(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=r?.trim()||Qx(e),o=uj(e),i=fj(e),a=vg[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!cp(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:hj.getType(e)||"application/octet-stream"},{timeout:Qd})}catch(l){this.logger.error({err:l},"Error handling file chooser"),this.logToUserConsole(this.page,"error",l.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:l,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=l;let p=atob(l),m=new Array(p.length);for(let h=0;h<p.length;h++)m[h]=p.charCodeAt(h);let g=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:s,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let r={...this.debugData};return this.debugData={logsPerPage:[]},r}async copy(e){try{await this.evaluateFunctionInPage(r=>navigator.clipboard.writeText(r),e,"copying text to clipboard")}catch(r){if(r instanceof Error&&r.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw r}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(r=>{let n=r.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,r){this.requestRecorders[e]=r}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,r,n){this.customHeaders.push({key:e.toLowerCase(),value:r,matcher:n})}registerMock(e,r,n,o){let i=e??hS();return this.mocks[i]={matcher:r,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??OC}get userBrowserSettings(){return ic(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??hs}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=rp();for(let r of e)if(!(!cp(r)||!Xx(r).isDirectory()||!["new","pending","completed"].some(o=>{let i=Sj(r,o);return cp(i)&&Xx(i).isDirectory()&&dj(i).length>0})))return r}};import Eq from"fetch-cookie";import{cloneDeep as PI}from"lodash-es";import TPe,{multistream as RPe}from"pino";import wPe from"pino-pretty";var _Pe=5*1024,Ej="...[truncated]",MPe=Buffer.byteLength(Ej,"utf8");import{PostHog as bj}from"posthog-node";async function Zx(t,e){let r,n=0,o=3,i,a;for(;n<o;)try{let s=await $(t.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=s.featureFlags||{},a=s.featureFlagPayloads||{};break}catch(s){r=s,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw r}var up=class t extends Nl{constructor(r,n,o,i){super(o,i);this.client=r;this.orgId=n}static async init(r){let n=new bj("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await Zx(n,r);return new t(n,r,o,i)}async refresh(){let{flags:r,payloads:n}=await Zx(this.client,this.orgId);this.flags=r,this.payloads=n}};import{randomUUID as Tj}from"node:crypto";import{PostHog as vj}from"posthog-node";var dp=class t{bindings;client;options;constructor(e,r={}){this.bindings=e,this.options=r,this.client=new vj("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...r})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new t({...this.bindings,...e},this.options)}track(e,r){if(!xv(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:n,...o}=e;return this.client.capture({distinctId:Tj(),event:n,timestamp:r?.timestamp,properties:{...this.bindings,...o}}),this}};import{execSync as Rj}from"child_process";import Ss from"os";import Aj from"v8";var e_,Un,t_=Ss.platform(),wj=Ss.cpus().map(t=>({model:t.model,speed:t.speed})).reduce((t,e)=>(t[e.model]={speed:e.speed},t.totalCores=(t.totalCores??0)+1,t),{}),pp=t=>{try{let e={},r=!1,n=Cj(),o=xj(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),r=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(r=!0);let s=Aj.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(r=!0),r?(t.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),Ni&&b.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):t.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}},r_=t=>{pp(t),setTimeout(()=>pp(t),5e3)};function n_(t){if(!wr)return pp(t),{interval:setInterval(()=>pp(t),2e4),cpuMetadata:wj,platform:t_}}function Cj(){let t=Ss.totalmem(),e=t_==="darwin"?_j():(()=>{let n=Ss.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),r=e.availableMemory/t;return{totalMemory:t,freeMemory:e.availableMemory,freePercentage:r}}function xj(){let t=Ss.cpus(),e=Date.now(),r={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)r.user+=o.times.user,r.nice+=o.times.nice,r.sys+=o.times.sys,r.idle+=o.times.idle,r.irq+=o.times.irq;if(r.total=r.user+r.nice+r.sys+r.idle+r.irq,!Un)return Un=r,null;let n={user:r.user-Un.user,nice:r.nice-Un.nice,sys:r.sys-Un.sys,idle:r.idle-Un.idle,irq:r.irq-Un.irq,total:r.total-Un.total};return e_={measurementTime:e,intervalMs:e-Un.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100},Un=r,e_}function _j(){try{let t=Rj("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),r=t.match(/page size of (\d+) bytes/)?.[1],n=r?Number.parseInt(r,10):4096,o=u=>{let p=t.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Ss.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var mp=class{increment(e,r,n){}gauge(e,r){}distribution(e,r,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function Mj(t){if(!t||t.length===0)return{};let e={};for(let r of t){let n=r.indexOf(":");if(n>-1){let o=r.slice(0,n).trim(),i=r.slice(n+1).trim();o&&(e[o]=i);continue}e[r]=!0}return e}function hp(t,e){let r=Mj(t);return!e||Object.keys(e).length===0?r:{...e,...r}}var P_="=",yp=";",xS=",";var I_=8192;var Ts={};zN(Ts,{getKeyPairs:()=>lV,parseKeyPairsIntoRecord:()=>cV,parsePairKeyValue:()=>O_,serializeKeyPairs:()=>sV});Xe();var aV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function sV(t){return t.reduce(function(e,r){var n=""+e+(e!==""?xS:"")+r;return n.length>I_?e:n},"")}function lV(t){return t.getAllEntries().map(function(e){var r=aV(e,2),n=r[0],o=r[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=yp+o.metadata.toString()),i})}function O_(t){var e=t.split(yp);if(!(e.length<=0)){var r=e.shift();if(r){var n=r.indexOf(P_);if(!(n<=0)){var o=decodeURIComponent(r.substring(0,n).trim()),i=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=SS(e.join(yp))),{key:o,value:i,metadata:a}}}}}function cV(t){return typeof t!="string"||t.length===0?{}:t.split(xS).map(function(e){return O_(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,r){return e[r.key]=r.value,e},{})}Xe();var Ep;(function(t){t.AlwaysOff="always_off",t.AlwaysOn="always_on",t.ParentBasedAlwaysOff="parentbased_always_off",t.ParentBasedAlwaysOn="parentbased_always_on",t.ParentBasedTraceIdRatio="parentbased_traceidratio",t.TraceIdRatio="traceidratio"})(Ep||(Ep={}));var uV=",",dV=["OTEL_SDK_DISABLED"];function pV(t){return dV.indexOf(t)>-1}var mV=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function hV(t){return mV.indexOf(t)>-1}var gV=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function fV(t){return gV.indexOf(t)>-1}var _S=1/0,MS=128,SV=128,yV=128,PS={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:at.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:_S,OTEL_ATTRIBUTE_COUNT_LIMIT:MS,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:_S,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:MS,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:_S,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:MS,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:SV,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:yV,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Ep.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function EV(t,e,r){if(!(typeof r[t]>"u")){var n=String(r[t]);e[t]=n.toLowerCase()==="true"}}function bV(t,e,r,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof r[t]<"u"){var i=Number(r[t]);isNaN(i)||(i<n?e[t]=n:i>o?e[t]=o:e[t]=i)}}function TV(t,e,r,n){n===void 0&&(n=uV);var o=r[t];typeof o=="string"&&(e[t]=o.split(n).map(function(i){return i.trim()}))}var vV={ALL:at.ALL,VERBOSE:at.VERBOSE,DEBUG:at.DEBUG,INFO:at.INFO,WARN:at.WARN,ERROR:at.ERROR,NONE:at.NONE};function RV(t,e,r){var n=r[t];if(typeof n=="string"){var o=vV[n.toUpperCase()];o!=null&&(e[t]=o)}}function L_(t){var e={};for(var r in PS){var n=r;switch(n){case"OTEL_LOG_LEVEL":RV(n,e,t);break;default:if(pV(n))EV(n,e,t);else if(hV(n))bV(n,e,t);else if(fV(n))TV(n,e,t);else{var o=t[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function jt(){var t=L_(process.env);return Object.assign({},PS,t)}function N_(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-87:t-55}function bp(t){for(var e=new Uint8Array(t.length/2),r=0,n=0;n<t.length;n+=2){var o=N_(t.charCodeAt(n)),i=N_(t.charCodeAt(n+1));e[r++]=o<<4|i}return e}var D_="1.25.1";var AV="deployment.environment";var wV="process.runtime.name";var CV="service.name";var xV="service.instance.id";var _V="telemetry.sdk.name",MV="telemetry.sdk.language",PV="telemetry.sdk.version";var k_=AV;var F_=wV;var Tp=CV;var U_=xV;var pc=_V,mc=MV,hc=PV;var IV="nodejs";var B_=IV;var vs,vp=(vs={},vs[pc]="opentelemetry",vs[F_]="node",vs[mc]=B_,vs[hc]=D_,vs);var OV=9,LV=6,NV=Math.pow(10,LV),DV=Math.pow(10,OV);function z_(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*NV);return[r,n]}function H_(t){return t[0]*DV+t[1]}function gc(t){return t[0]*1e6+t[1]/1e3}var Yi;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Yi||(Yi={}));var G_=function(){function t(){var e=this;this._promise=new Promise(function(r,n){e._resolve=r,e._reject=n})}return Object.defineProperty(t.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),t.prototype.resolve=function(e){this._resolve(e)},t.prototype.reject=function(e){this._reject(e)},t}();var kV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},FV=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},j_=function(){function t(e,r){this._callback=e,this._that=r,this._isCalled=!1,this._deferred=new G_}return Object.defineProperty(t.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),t.prototype.call=function(){for(var e,r=this,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((e=this._callback).call.apply(e,FV([this._that],kV(n),!1))).then(function(i){return r._deferred.resolve(i)},function(i){return r._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},t}();var Kr;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(Kr||(Kr={}));var Zt;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Zt||(Zt={}));var UV=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();var cLe=function(t){UV(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function V_(t,e){for(var r=0,n=t.length-1;n-r>1;){var o=Math.trunc((n+r)/2);t[o]<=e?r=o:n=o-1}return t[n]<=e?n:t[r]<=e?r:-1}Xe();var Yr;(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Yr||(Yr={}));var $_=function(){function t(){this.kind=Yr.DROP}return t.prototype.createAccumulation=function(){},t.prototype.merge=function(e,r){},t.prototype.diff=function(e,r){},t.prototype.toMetricData=function(e,r,n,o){},t}();var ye;(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ye||(ye={}));var BV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function zV(t){var e=t.map(function(){return 0});return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var IS=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=zV(r)),this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=o}return t.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var r=V_(this._boundaries,e);this._current.buckets.counts[r+1]+=1}},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var OS=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=Yr.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new IS(e,this._boundaries,this._recordMinMax)},t.prototype.merge=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new IS(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},t.prototype.diff=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new IS(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Zt.HISTOGRAM,dataPoints:n.map(function(i){var a=BV(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ye.GAUGE||e.type===ye.UP_DOWN_COUNTER||e.type===ye.OBSERVABLE_GAUGE||e.type===ye.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},t}();Xe();var LS=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},NS=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},DS=function(){function t(e,r,n,o){e===void 0&&(e=new HV),r===void 0&&(r=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(t.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),t.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(r,n){return e.at(n)})},t.prototype.at=function(e){var r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)},t.prototype.incrementBucket=function(e,r){this.backing.increment(e,r)},t.prototype.decrementBucket=function(e,r){this.backing.decrement(e,r)},t.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},t.prototype.downscale=function(e){this._rotate();for(var r=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<r;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},t.prototype.clone=function(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},t.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},t.prototype._relocateBucket=function(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))},t}();var HV=function(){function t(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(t.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),t.prototype.countAt=function(e){return this._counts[e]},t.prototype.growTo=function(e,r,n){var o=new Array(e).fill(0);o.splice.apply(o,NS([n,this._counts.length-r],LS(this._counts.slice(r)),!1)),o.splice.apply(o,NS([0,r],LS(this._counts.slice(0,r)),!1)),this._counts=o},t.prototype.reverse=function(e,r){for(var n=Math.floor((e+r)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[r-o-1],this._counts[r-o-1]=i}},t.prototype.emptyBucket=function(e){var r=this._counts[e];return this._counts[e]=0,r},t.prototype.increment=function(e,r){this._counts[e]+=r},t.prototype.decrement=function(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0},t.prototype.clone=function(){return new t(NS([],LS(this._counts),!1))},t}();var W_=52,GV=2146435072,jV=1048575,kS=1023,Rp=-kS+1,Ap=kS,fc=Math.pow(2,-1022);function wp(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&GV)>>20;return n-kS}function Cp(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&jV)*Math.pow(2,32);return o+n}function Sc(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function K_(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var VV=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Qo=function(t){VV(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var X_=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<fc)return this._minNormalLowerBoundaryIndex();var r=wp(e),n=this._rightShift(Cp(e)-1,W_);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new Qo("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Qo("overflow: "+e+" is > maximum lower boundary: "+n);return Sc(1,e<<this._shift)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){var e=Rp>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Ap>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var J_=function(){function t(e){this._scale=e,this._scaleFactor=Sc(Math.LOG2E,e),this._inverseFactor=Sc(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=fc)return this._minNormalLowerBoundaryIndex()-1;if(Cp(e)===0){var r=wp(e);return(r<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},t.prototype.lowerBoundary=function(e){var r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Qo("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return fc;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Qo("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){return Rp<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Ap+1<<this._scale)-1},t}();var Q_=-10,Z_=20,$V=Array.from({length:31},function(t,e){return e>10?new J_(e-10):new X_(e-10)});function FS(t){if(t>Z_||t<Q_)throw new Qo("expected scale >= "+Q_+" && <= "+Z_+", got: "+t);return $V[t+10]}var WV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},xp=function(){function t(e,r){this.low=e,this.high=r}return t.combine=function(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))},t}(),qV=20,KV=160,US=2,YV=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=KV),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new DS),u===void 0&&(u=new DS),d===void 0&&(d=FS(qV)),this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<US&&(K.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+US),this._maxSize=US)}return t.prototype.record=function(e){this.updateByIncrement(e,1)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(t.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),t.prototype.updateByIncrement=function(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}},t.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)},t.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)},t.prototype.clone=function(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},t.prototype._updateBuckets=function(e,r,n){var o=this._mapping.mapToIndex(r),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,o,n)},t.prototype._incrementIndexBy=function(e,r,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){var o=e.indexEnd-r;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=r}else if(r>e.indexEnd){var o=r-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=r}var i=r-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},t.prototype._grow=function(e,r){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=K_(r);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},t.prototype._changeScale=function(e,r){for(var n=0;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n},t.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=FS(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=xp.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=xp.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(o.high,o.low))},t.prototype._highLowAtScale=function(e,r,n){if(e.length===0)return new xp(0,-1);var o=r-n;return new xp(e.indexStart>>o,e.indexEnd>>o)},t.prototype._mergeBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},t.prototype._diffBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},t}();var eM=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=Yr.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new YV(e,this._maxSize,this._recordMinMax)},t.prototype.merge=function(e,r){var n=r.clone();return n.merge(e),n},t.prototype.diff=function(e,r){var n=r.clone();return n.diff(e),n},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Zt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=WV(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ye.GAUGE||e.type===ye.UP_DOWN_COUNTER||e.type===ye.OBSERVABLE_GAUGE||e.type===ye.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},t}();var XV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},BS=function(){function t(e,r,n){r===void 0&&(r=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=r,this.sampleTime=n}return t.prototype.record=function(e){this._current=e,this.sampleTime=z_(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var tM=function(){function t(){this.kind=Yr.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new BS(e)},t.prototype.merge=function(e,r){var n=gc(r.sampleTime)>=gc(e.sampleTime)?r:e;return new BS(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=gc(r.sampleTime)>=gc(e.sampleTime)?r:e;return new BS(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Zt.GAUGE,dataPoints:n.map(function(i){var a=XV(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var JV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},yc=function(){function t(e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=r,this._current=n,this.reset=o}return t.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var zS=function(){function t(e){this.monotonic=e,this.kind=Yr.SUM}return t.prototype.createAccumulation=function(e){return new yc(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new yc(r.startTime,this.monotonic,o,r.reset):new yc(e.startTime,this.monotonic,n+o)},t.prototype.diff=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return this.monotonic&&n>o?new yc(r.startTime,this.monotonic,o,!0):new yc(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Zt.SUM,dataPoints:n.map(function(i){var a=JV(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var Xi=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),zn=function(){function t(){}return t.Drop=function(){return cM},t.Sum=function(){return uM},t.LastValue=function(){return dM},t.Histogram=function(){return pM},t.ExponentialHistogram=function(){return QV},t.Default=function(){return ZV},t}();var rM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new $_,e}(zn);var nM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case ye.COUNTER:case ye.OBSERVABLE_COUNTER:case ye.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new zS(!0),e.NON_MONOTONIC_INSTANCE=new zS(!1),e}(zn);var oM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new tM,e}(zn);var iM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new OS([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(zn);var aM=function(t){Xi(e,t);function e(r,n){n===void 0&&(n=!0);var o=t.call(this)||this;if(o._recordMinMax=n,r==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");r=r.concat(),r=r.sort(function(s,c){return s-c});var i=r.lastIndexOf(-1/0),a=r.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=r.slice(i+1,a),o}return e.prototype.createAggregator=function(r){return new OS(this._boundaries,this._recordMinMax)},e}(zn);var sM=function(t){Xi(e,t);function e(r,n){r===void 0&&(r=160),n===void 0&&(n=!0);var o=t.call(this)||this;return o._maxSize=r,o._recordMinMax=n,o}return e.prototype.createAggregator=function(r){return new eM(this._maxSize,this._recordMinMax)},e}(zn);var lM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case ye.COUNTER:case ye.UP_DOWN_COUNTER:case ye.OBSERVABLE_COUNTER:case ye.OBSERVABLE_UP_DOWN_COUNTER:return uM;case ye.GAUGE:case ye.OBSERVABLE_GAUGE:return dM;case ye.HISTOGRAM:return r.advice.explicitBucketBoundaries?new aM(r.advice.explicitBucketBoundaries):pM}return K.warn("Unable to recognize instrument type: "+r.type),cM},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(zn);var cM=new rM,uM=new nM,dM=new oM,pM=new iM,QV=new sM,ZV=new lM;Xe();function _p(){return"unknown_service:"+process.argv0}var Zo=function(){return Zo=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},Zo.apply(this,arguments)},e$=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},t$=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},r$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},HS=function(){function t(e,r){var n=this,o;this._attributes=e,this.asyncAttributesPending=r!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=r?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return K.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return t.empty=function(){return t.EMPTY},t.default=function(){var e;return new t((e={},e[Tp]=_p(),e[mc]=vp[mc],e[pc]=vp[pc],e[hc]=vp[hc],e))},Object.defineProperty(t.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&K.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),t.prototype.waitForAsyncAttributes=function(){return e$(this,void 0,void 0,function(){return t$(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},t.prototype.merge=function(e){var r=this,n;if(!e)return this;var o=Zo(Zo({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=r$(a,2),l=c[0],u=c[1];return Zo(Zo(Zo(Zo({},r._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new t(o,i)},t.EMPTY=new t({}),t}();var Ji;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE",t[t.LOWMEMORY=2]="LOWMEMORY"})(Ji||(Ji={}));Xe();var n$=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},o$=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},GS=function(){return Kr.CUMULATIVE},mM=function(t){switch(t){case ye.COUNTER:case ye.OBSERVABLE_COUNTER:case ye.GAUGE:case ye.HISTOGRAM:case ye.OBSERVABLE_GAUGE:return Kr.DELTA;case ye.UP_DOWN_COUNTER:case ye.OBSERVABLE_UP_DOWN_COUNTER:return Kr.CUMULATIVE}},hM=function(t){switch(t){case ye.COUNTER:case ye.HISTOGRAM:return Kr.DELTA;case ye.GAUGE:case ye.UP_DOWN_COUNTER:case ye.OBSERVABLE_UP_DOWN_COUNTER:case ye.OBSERVABLE_COUNTER:case ye.OBSERVABLE_GAUGE:return Kr.CUMULATIVE}};function i$(){var t=jt(),e=t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?GS:e==="delta"?mM:e==="lowmemory"?hM:(K.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),GS)}function a$(t){return t!=null?t===Ji.DELTA?mM:t===Ji.LOWMEMORY?hM:GS:i$()}function s$(t){return t?.aggregationPreference?t.aggregationPreference:function(e){return zn.Default()}}var gM=function(){function t(e,r){this._otlpExporter=e,this._aggregationSelector=s$(r),this._aggregationTemporalitySelector=a$(r?.temporalityPreference)}return t.prototype.export=function(e,r){this._otlpExporter.export([e],r)},t.prototype.shutdown=function(){return n$(this,void 0,void 0,function(){return o$(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},t.prototype.forceFlush=function(){return Promise.resolve()},t.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},t.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},t}();Xe();Xe();var l$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},fM=1e4,SM=5,yM=1e3,EM=5e3,bM=1.5;function Ec(t){t===void 0&&(t={});var e={};return Object.entries(t).forEach(function(r){var n=l$(r,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):K.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function jS(t,e){return t.endsWith("/")||(t=t+"/"),t+e}function VS(t){try{var e=new URL(t);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return K.warn("Could not parse export URL: '"+t+"'"),t}}function $S(t){return typeof t=="number"?t<=0?WS(t,fM):t:c$()}function c$(){var t,e=Number((t=jt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&t!==void 0?t:jt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?WS(e,fM):e}function WS(t,e){return K.warn("Timeout must be greater than 0",t),e}function TM(t){var e=[429,502,503,504];return e.includes(t)}function vM(t){if(t==null)return-1;var e=Number.parseInt(t,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var r=new Date(t).getTime()-Date.now();return r>=0?r:0}var RM=function(){function t(e){e===void 0&&(e={}),this._sendingPromises=[],this.url=this.getDefaultUrl(e),typeof e.hostname=="string"&&(this.hostname=e.hostname),this.shutdown=this.shutdown.bind(this),this._shutdownOnce=new j_(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=$S(e.timeoutMillis),this.onInit(e)}return t.prototype.export=function(e,r){if(this._shutdownOnce.isCalled){r({code:Yi.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){r({code:Yi.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){r({code:Yi.SUCCESS})}).catch(function(n){r({code:Yi.FAILED,error:n})})},t.prototype._export=function(e){var r=this;return new Promise(function(n,o){try{K.debug("items to be sent",e),r.send(e,n,o)}catch(i){o(i)}})},t.prototype.shutdown=function(){return this._shutdownOnce.call()},t.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},t.prototype._shutdown=function(){return K.debug("shutdown started"),this.onShutdown(),this.forceFlush()},t}();Xe();import*as qS from"url";import*as Pp from"http";import*as Ip from"https";import*as AM from"zlib";import{Readable as d$}from"stream";var ei;(function(t){t.NONE="none",t.GZIP="gzip"})(ei||(ei={}));var u$=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Rs=function(t){u$(e,t);function e(r,n,o){var i=t.call(this,r)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var Mp=function(){return Mp=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},Mp.apply(this,arguments)};function KS(t,e,r,n,o){var i=t.timeoutMillis,a=new qS.URL(t.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new Rs("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Mp({"Content-Type":r},t.headers),agent:t.agent},m=a.protocol==="http:"?Pp.request:Ip.request,g=function(h,f){switch(h===void 0&&(h=SM),f===void 0&&(f=yM),l=m(p,function(y){var E="";y.on("data",function(T){return E+=T}),y.on("aborted",function(){if(u){var T=new Rs("Request Timeout");o(T)}}),y.on("end",function(){if(u===!1)if(y.statusCode&&y.statusCode<299)K.debug("statusCode: "+y.statusCode,E),n(),clearTimeout(d),clearTimeout(c);else if(y.statusCode&&TM(y.statusCode)&&h>0){var T=void 0;f=bM*f,y.headers["retry-after"]?T=vM(y.headers["retry-after"]):T=Math.round(Math.random()*(EM-f)+f),c=setTimeout(function(){g(h-1,f)},T)}else{var v=new Rs(y.statusMessage,y.statusCode,E);o(v),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(y){if(u){var E=new Rs("Request Timeout",y.code);o(E)}else o(y);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var y=new Rs("Request Timeout");o(y)}clearTimeout(d),clearTimeout(c)}),t.compression){case ei.GZIP:{l.setHeader("Content-Encoding","gzip");var S=p$(e);S.on("error",o).pipe(AM.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function p$(t){var e=new d$;return e.push(t),e.push(null),e}function YS(t){if(t.httpAgentOptions&&t.keepAlive===!1){K.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(t.keepAlive===!1||!t.url))try{var e=new qS.URL(t.url),r=e.protocol==="http:"?Pp.Agent:Ip.Agent;return new r(Mp({keepAlive:!0},t.httpAgentOptions))}catch(n){K.error("collector exporter failed to create http agent. err: "+n.message);return}}function XS(t){if(t)return t;var e=jt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||jt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===ei.GZIP?ei.GZIP:ei.NONE}Xe();var m$=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Op=function(t){m$(e,t);function e(r,n,o){r===void 0&&(r={});var i=t.call(this,r)||this;return i.DEFAULT_HEADERS={},i._contentType=o,r.metadata&&K.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Ec(r.headers),Ts.parseKeyPairsIntoRecord(jt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=YS(r),i.compression=XS(r.compression),i._serializer=n,i}return e.prototype.onInit=function(r){},e.prototype.send=function(r,n,o){var i=this;if(this._shutdownOnce.isCalled){K.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;KS(i,(u=i._serializer.serializeRequest(r))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(RM);function CM(t){var e=BigInt(1e9);return BigInt(t[0])*e+BigInt(t[1])}function h$(t){var e=Number(BigInt.asUintN(32,t)),r=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:r}}function xM(t){var e=CM(t);return h$(e)}function g$(t){var e=CM(t);return e.toString()}var f$=typeof BigInt<"u"?g$:H_;function wM(t){return t}function _M(t){if(t!==void 0)return bp(t)}var S$={encodeHrTime:xM,encodeSpanContext:bp,encodeOptionalSpanContext:_M};function MM(t){var e,r;if(t===void 0)return S$;var n=(e=t.useLongBits)!==null&&e!==void 0?e:!0,o=(r=t.useHex)!==null&&r!==void 0?r:!1;return{encodeHrTime:n?xM:f$,encodeSpanContext:o?wM:bp,encodeOptionalSpanContext:o?wM:_M}}var y$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function PM(t){return{name:t.name,version:t.version}}function As(t){return Object.keys(t).map(function(e){return IM(e,t[e])})}function IM(t,e){return{key:t,value:OM(e)}}function OM(t){var e=typeof t;return e==="string"?{stringValue:t}:e==="number"?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:e==="boolean"?{boolValue:t}:t instanceof Uint8Array?{bytesValue:t}:Array.isArray(t)?{arrayValue:{values:t.map(OM)}}:e==="object"&&t!=null?{kvlistValue:{values:Object.entries(t).map(function(r){var n=y$(r,2),o=n[0],i=n[1];return IM(o,i)})}}:{}}function LM(t){return{attributes:As(t.attributes),droppedAttributesCount:0}}Xe();function DM(t,e){var r=MM(e);return{resource:LM(t.resource),schemaUrl:void 0,scopeMetrics:E$(t.scopeMetrics,r)}}function E$(t,e){return Array.from(t.map(function(r){return{scope:PM(r.scope),metrics:r.metrics.map(function(n){return b$(n,e)}),schemaUrl:r.scope.schemaUrl}}))}function b$(t,e){var r={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit},n=A$(t.aggregationTemporality);switch(t.dataPointType){case Zt.SUM:r.sum={aggregationTemporality:n,isMonotonic:t.isMonotonic,dataPoints:NM(t,e)};break;case Zt.GAUGE:r.gauge={dataPoints:NM(t,e)};break;case Zt.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:v$(t,e)};break;case Zt.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:R$(t,e)};break}return r}function T$(t,e,r){var n={attributes:As(t.attributes),startTimeUnixNano:r.encodeHrTime(t.startTime),timeUnixNano:r.encodeHrTime(t.endTime)};switch(e){case Pr.INT:n.asInt=t.value;break;case Pr.DOUBLE:n.asDouble=t.value;break}return n}function NM(t,e){return t.dataPoints.map(function(r){return T$(r,t.descriptor.valueType,e)})}function v$(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:As(r.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(r.startTime),timeUnixNano:e.encodeHrTime(r.endTime)}})}function R$(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:As(r.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(r.startTime),timeUnixNano:e.encodeHrTime(r.endTime)}})}function A$(t){switch(t){case Kr.DELTA:return 1;case Kr.CUMULATIVE:return 2}}function kM(t,e){return{resourceMetrics:t.map(function(r){return DM(r,e)})}}var JS={serializeRequest:function(t){var e=kM(t,{useLongBits:!1}),r=new TextEncoder;return r.encode(JSON.stringify(e))},deserializeResponse:function(t){var e=new TextDecoder;return JSON.parse(e.decode(t))}};var FM="0.52.1";var UM=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),ws=function(){return ws=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},ws.apply(this,arguments)},BM="v1/metrics",w$="http://localhost:4318/"+BM,C$={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+FM},x$=function(t){UM(e,t);function e(r){var n=t.call(this,r,JS,"application/json")||this;return n.headers=ws(ws(ws(ws({},n.headers),C$),Ts.parseKeyPairsIntoRecord(jt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ec(r?.headers)),n}return e.prototype.getDefaultUrl=function(r){return typeof r.url=="string"?r.url:jt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?VS(jt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):jt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?jS(jt().OTEL_EXPORTER_OTLP_ENDPOINT,BM):w$},e}(Op),zM=function(t){UM(e,t);function e(r){return t.call(this,new x$(r),r)||this}return e}(gM);var Cs;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(Cs||(Cs={}));var Hn;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Hn||(Hn={}));Xe();var _$=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),HM=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},GM=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},M$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},P$=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},I$=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function jM(t){return t!=null}function Lp(t){var e=Object.keys(t);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(r){return[r,t[r]]})))}function VM(t){var e,r;return t.name+":"+((e=t.version)!==null&&e!==void 0?e:"")+":"+((r=t.schemaUrl)!==null&&r!==void 0?r:"")}var QS=function(t){_$(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function ti(t,e){var r,n=new Promise(function(i,a){r=setTimeout(function(){a(new QS("Operation timed out."))},e)});return Promise.race([t,n]).then(function(o){return clearTimeout(r),o},function(o){throw clearTimeout(r),o})}function $M(t){return HM(this,void 0,void 0,function(){var e=this;return GM(this,function(r){return[2,Promise.all(t.map(function(n){return HM(e,void 0,void 0,function(){var o,i;return GM(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,n];case 1:return o=a.sent(),[2,{status:"fulfilled",value:o}];case 2:return i=a.sent(),[2,{status:"rejected",reason:i}];case 3:return[2]}})})}))]})})}function WM(t){return t.status==="rejected"}function ZS(t,e){var r=[];return t.forEach(function(n){r.push.apply(r,P$([],M$(e(n)),!1))}),r}function qM(t,e){var r,n;if(t.size!==e.size)return!1;try{for(var o=I$(t),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){r={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return!0}function KM(t,e){for(var r=0,n=t.length-1,o=t.length;n>=r;){var i=r+Math.trunc((n-r)/2);t[i]<e?r=i+1:(o=i,n=i-1)}return o}function YM(t,e){return t.toLowerCase()===e.toLowerCase()}Xe();var Xr;(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Xr||(Xr={}));var ey=function(){function t(){this.kind=Xr.DROP}return t.prototype.createAccumulation=function(){},t.prototype.merge=function(e,r){},t.prototype.diff=function(e,r){},t.prototype.toMetricData=function(e,r,n,o){},t}();Xe();var Ie;(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(Ie||(Ie={}));function Gn(t,e,r){var n,o,i,a;return L$(t)||K.warn('Invalid metric name: "'+t+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:t,type:e,description:(n=r?.description)!==null&&n!==void 0?n:"",unit:(o=r?.unit)!==null&&o!==void 0?o:"",valueType:(i=r?.valueType)!==null&&i!==void 0?i:Pr.DOUBLE,advice:(a=r?.advice)!==null&&a!==void 0?a:{}}}function XM(t,e){var r,n;return{name:(r=t.name)!==null&&r!==void 0?r:e.name,description:(n=t.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function JM(t,e){return YM(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}var O$=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function L$(t){return t.match(O$)!=null}var N$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function D$(t){var e=t.map(function(){return 0});return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Np=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=D$(r)),this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=o}return t.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var r=KM(this._boundaries,e);this._current.buckets.counts[r]+=1}},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var Dp=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=Xr.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new Np(e,this._boundaries,this._recordMinMax)},t.prototype.merge=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new Np(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},t.prototype.diff=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new Np(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Hn.HISTOGRAM,dataPoints:n.map(function(i){var a=N$(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Ie.GAUGE||e.type===Ie.UP_DOWN_COUNTER||e.type===Ie.OBSERVABLE_GAUGE||e.type===Ie.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},t}();Xe();var ty=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},ry=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},ny=function(){function t(e,r,n,o){e===void 0&&(e=new k$),r===void 0&&(r=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(t.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),t.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(r,n){return e.at(n)})},t.prototype.at=function(e){var r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)},t.prototype.incrementBucket=function(e,r){this.backing.increment(e,r)},t.prototype.decrementBucket=function(e,r){this.backing.decrement(e,r)},t.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},t.prototype.downscale=function(e){this._rotate();for(var r=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<r;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},t.prototype.clone=function(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},t.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},t.prototype._relocateBucket=function(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))},t}();var k$=function(){function t(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(t.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),t.prototype.countAt=function(e){return this._counts[e]},t.prototype.growTo=function(e,r,n){var o=new Array(e).fill(0);o.splice.apply(o,ry([n,this._counts.length-r],ty(this._counts.slice(r)),!1)),o.splice.apply(o,ry([0,r],ty(this._counts.slice(0,r)),!1)),this._counts=o},t.prototype.reverse=function(e,r){for(var n=Math.floor((e+r)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[r-o-1],this._counts[r-o-1]=i}},t.prototype.emptyBucket=function(e){var r=this._counts[e];return this._counts[e]=0,r},t.prototype.increment=function(e,r){this._counts[e]+=r},t.prototype.decrement=function(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0},t.prototype.clone=function(){return new t(ry([],ty(this._counts),!1))},t}();var QM=52,F$=2146435072,U$=1048575,oy=1023,kp=-oy+1,Fp=oy,bc=Math.pow(2,-1022);function Up(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&F$)>>20;return n-oy}function Bp(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&U$)*Math.pow(2,32);return o+n}function Tc(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function eP(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var B$=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),ri=function(t){B$(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var rP=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<bc)return this._minNormalLowerBoundaryIndex();var r=Up(e),n=this._rightShift(Bp(e)-1,QM);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new ri("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new ri("overflow: "+e+" is > maximum lower boundary: "+n);return Tc(1,e<<this._shift)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){var e=kp>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Fp>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var nP=function(){function t(e){this._scale=e,this._scaleFactor=Tc(Math.LOG2E,e),this._inverseFactor=Tc(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=bc)return this._minNormalLowerBoundaryIndex()-1;if(Bp(e)===0){var r=Up(e);return(r<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},t.prototype.lowerBoundary=function(e){var r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new ri("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return bc;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new ri("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){return kp<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Fp+1<<this._scale)-1},t}();var oP=-10,iP=20,z$=Array.from({length:31},function(t,e){return e>10?new nP(e-10):new rP(e-10)});function iy(t){if(t>iP||t<oP)throw new ri("expected scale >= "+oP+" && <= "+iP+", got: "+t);return z$[t+10]}var H$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},zp=function(){function t(e,r){this.low=e,this.high=r}return t.combine=function(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))},t}(),G$=20,j$=160,ay=2,aP=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=j$),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new ny),u===void 0&&(u=new ny),d===void 0&&(d=iy(G$)),this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<ay&&(K.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+ay),this._maxSize=ay)}return t.prototype.record=function(e){this.updateByIncrement(e,1)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(t.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),t.prototype.updateByIncrement=function(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}},t.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)},t.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)},t.prototype.clone=function(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},t.prototype._updateBuckets=function(e,r,n){var o=this._mapping.mapToIndex(r),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,o,n)},t.prototype._incrementIndexBy=function(e,r,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){var o=e.indexEnd-r;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=r}else if(r>e.indexEnd){var o=r-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=r}var i=r-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},t.prototype._grow=function(e,r){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=eP(r);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},t.prototype._changeScale=function(e,r){for(var n=0;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n},t.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=iy(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=zp.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=zp.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(o.high,o.low))},t.prototype._highLowAtScale=function(e,r,n){if(e.length===0)return new zp(0,-1);var o=r-n;return new zp(e.indexStart>>o,e.indexEnd>>o)},t.prototype._mergeBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},t.prototype._diffBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},t}();var sy=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=Xr.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new aP(e,this._maxSize,this._recordMinMax)},t.prototype.merge=function(e,r){var n=r.clone();return n.merge(e),n},t.prototype.diff=function(e,r){var n=r.clone();return n.diff(e),n},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Hn.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=H$(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Ie.GAUGE||e.type===Ie.UP_DOWN_COUNTER||e.type===Ie.OBSERVABLE_GAUGE||e.type===Ie.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},t}();Xe();var V$=yS("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function sP(t){return t.setValue(V$,!0)}Xe();function lP(){return function(t){K.error($$(t))}}function $$(t){return typeof t=="string"?t:JSON.stringify(W$(t))}function W$(t){for(var e={},r=t;r!==null;)Object.getOwnPropertyNames(r).forEach(function(n){if(!e[n]){var o=r[n];o&&(e[n]=String(o))}}),r=Object.getPrototypeOf(r);return e}var q$=lP();function Hp(t){try{q$(t)}catch{}}var cP="1.30.1";var K$="process.runtime.name";var Y$="service.name";var X$="telemetry.sdk.name",J$="telemetry.sdk.language",Q$="telemetry.sdk.version";var uP=K$;var dP=Y$;var vc=X$,Rc=J$,Ac=Q$;var Z$="nodejs";var pP=Z$;var xs,Qi=(xs={},xs[vc]="opentelemetry",xs[uP]="node",xs[Rc]=pP,xs[Ac]=cP,xs);function wc(t){t.unref()}var aW=9,sW=6,lW=Math.pow(10,sW),mke=Math.pow(10,aW);function Zi(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*lW);return[r,n]}function _s(t){return t[0]*1e6+t[1]/1e3}var Cc;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Cc||(Cc={}));Xe();function mP(t,e){return new Promise(function(r){bs.with(sP(bs.active()),function(){t.export(e,function(n){r(n)})})})}var hP={_export:mP};var cW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Gp=function(){function t(e,r,n){r===void 0&&(r=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=r,this.sampleTime=n}return t.prototype.record=function(e){this._current=e,this.sampleTime=Zi(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var ly=function(){function t(){this.kind=Xr.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new Gp(e)},t.prototype.merge=function(e,r){var n=_s(r.sampleTime)>=_s(e.sampleTime)?r:e;return new Gp(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=_s(r.sampleTime)>=_s(e.sampleTime)?r:e;return new Gp(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Hn.GAUGE,dataPoints:n.map(function(i){var a=cW(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var uW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Ms=function(){function t(e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=r,this._current=n,this.reset=o}return t.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var jp=function(){function t(e){this.monotonic=e,this.kind=Xr.SUM}return t.prototype.createAccumulation=function(e){return new Ms(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new Ms(r.startTime,this.monotonic,o,r.reset):new Ms(e.startTime,this.monotonic,n+o)},t.prototype.diff=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return this.monotonic&&n>o?new Ms(r.startTime,this.monotonic,o,!0):new Ms(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Hn.SUM,dataPoints:n.map(function(i){var a=uW(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var ea=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Jr=function(){function t(){}return t.Drop=function(){return TP},t.Sum=function(){return vP},t.LastValue=function(){return RP},t.Histogram=function(){return AP},t.ExponentialHistogram=function(){return dW},t.Default=function(){return pW},t}();var gP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new ey,e}(Jr);var fP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case Ie.COUNTER:case Ie.OBSERVABLE_COUNTER:case Ie.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new jp(!0),e.NON_MONOTONIC_INSTANCE=new jp(!1),e}(Jr);var SP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new ly,e}(Jr);var yP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Dp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Jr);var xc=function(t){ea(e,t);function e(r,n){n===void 0&&(n=!0);var o=t.call(this)||this;if(o._recordMinMax=n,r==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");r=r.concat(),r=r.sort(function(s,c){return s-c});var i=r.lastIndexOf(-1/0),a=r.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=r.slice(i+1,a),o}return e.prototype.createAggregator=function(r){return new Dp(this._boundaries,this._recordMinMax)},e}(Jr);var EP=function(t){ea(e,t);function e(r,n){r===void 0&&(r=160),n===void 0&&(n=!0);var o=t.call(this)||this;return o._maxSize=r,o._recordMinMax=n,o}return e.prototype.createAggregator=function(r){return new sy(this._maxSize,this._recordMinMax)},e}(Jr);var bP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case Ie.COUNTER:case Ie.UP_DOWN_COUNTER:case Ie.OBSERVABLE_COUNTER:case Ie.OBSERVABLE_UP_DOWN_COUNTER:return vP;case Ie.GAUGE:case Ie.OBSERVABLE_GAUGE:return RP;case Ie.HISTOGRAM:return r.advice.explicitBucketBoundaries?new xc(r.advice.explicitBucketBoundaries):AP}return K.warn("Unable to recognize instrument type: "+r.type),TP},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(Jr);var TP=new gP,vP=new fP,RP=new SP,AP=new yP,dW=new EP,pW=new bP;var wP=function(t){return Jr.Default()},CP=function(t){return Cs.CUMULATIVE};var cy=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},uy=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},xP=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},mW=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},_P=function(){function t(e){var r,n,o;this._shutdown=!1,this._aggregationSelector=(r=e?.aggregationSelector)!==null&&r!==void 0?r:wP,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:CP,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return t.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},t.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},t.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},t.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},t.prototype.onInitialized=function(){},t.prototype.collect=function(e){return cy(this,void 0,void 0,function(){var r,n,o,i,a,s;return uy(this,function(c){switch(c.label){case 0:if(this._sdkMetricProducer===void 0)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");return[4,Promise.all(mW([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],xP(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return r=xP.apply(void 0,[c.sent()]),n=r[0],o=r.slice(1),i=n.errors.concat(ZS(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(ZS(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},t.prototype.shutdown=function(e){return cy(this,void 0,void 0,function(){return uy(this,function(r){switch(r.label){case 0:return this._shutdown?(K.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return r.sent(),[3,4];case 2:return[4,ti(this.onShutdown(),e.timeoutMillis)];case 3:r.sent(),r.label=4;case 4:return this._shutdown=!0,[2]}})})},t.prototype.forceFlush=function(e){return cy(this,void 0,void 0,function(){return uy(this,function(r){switch(r.label){case 0:return this._shutdown?(K.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return r.sent(),[2];case 2:return[4,ti(this.onForceFlush(),e.timeoutMillis)];case 3:return r.sent(),[2]}})})},t}();Xe();var hW=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Vp=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},$p=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},gW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},fW=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},dy=function(t){hW(e,t);function e(r){var n,o,i,a,s=t.call(this,{aggregationSelector:(n=r.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(r.exporter),aggregationTemporalitySelector:(o=r.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(r.exporter),metricProducers:r.metricProducers})||this;if(r.exportIntervalMillis!==void 0&&r.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(r.exportTimeoutMillis!==void 0&&r.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(r.exportTimeoutMillis!==void 0&&r.exportIntervalMillis!==void 0&&r.exportIntervalMillis<r.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=r.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=r.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=r.exporter,s}return e.prototype._runOnce=function(){return Vp(this,void 0,void 0,function(){var r;return $p(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,ti(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return r=n.sent(),r instanceof QS?(K.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Hp(r),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var r,n;return Vp(this,void 0,void 0,function(){var o,i,a,s,c,l;return $p(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(l=K).error.apply(l,fW(["PeriodicExportingMetricReader: metrics collection errors"],gW(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(r=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(r)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),K.debug("Error while resolving async portion of resource: ",s),Hp(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,hP._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Cc.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var r=this;this._interval=setInterval(function(){r._runOnce()},this._exportInterval),wc(this._interval)},e.prototype.onForceFlush=function(){return Vp(this,void 0,void 0,function(){return $p(this,function(r){switch(r.label){case 0:return[4,this._runOnce()];case 1:return r.sent(),[4,this._exporter.forceFlush()];case 2:return r.sent(),[2]}})})},e.prototype.onShutdown=function(){return Vp(this,void 0,void 0,function(){return $p(this,function(r){switch(r.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return r.sent(),[4,this._exporter.shutdown()];case 2:return r.sent(),[2]}})})},e}(_P);Xe();Xe();function Wp(){return"unknown_service:"+process.argv0}var ni=function(){return ni=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},ni.apply(this,arguments)},SW=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},yW=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},EW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},qp=function(){function t(e,r){var n=this,o;this._attributes=e,this.asyncAttributesPending=r!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=r?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return K.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return t.empty=function(){return t.EMPTY},t.default=function(){var e;return new t((e={},e[dP]=Wp(),e[Rc]=Qi[Rc],e[vc]=Qi[vc],e[Ac]=Qi[Ac],e))},Object.defineProperty(t.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&K.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),t.prototype.waitForAsyncAttributes=function(){return SW(this,void 0,void 0,function(){return yW(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},t.prototype.merge=function(e){var r=this,n;if(!e)return this;var o=ni(ni({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=EW(a,2),l=c[0],u=c[1];return ni(ni(ni(ni({},r._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new t(o,i)},t.EMPTY=new t({}),t}();var MP=function(){function t(){this._registeredViews=[]}return t.prototype.addView=function(e){this._registeredViews.push(e)},t.prototype.findViews=function(e,r){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,r)});return o},t.prototype._matchInstrument=function(e,r){return(e.getType()===void 0||r.type===e.getType())&&e.getNameFilter().match(r.name)&&e.getUnitFilter().match(r.unit)},t.prototype._matchMeter=function(e,r){return e.getNameFilter().match(r.name)&&(r.version===void 0||e.getVersionFilter().match(r.version))&&(r.schemaUrl===void 0||e.getSchemaUrlFilter().match(r.schemaUrl))},t}();Xe();var ta=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Kp=function(){function t(e,r){this._writableMetricStorage=e,this._descriptor=r}return t.prototype._record=function(e,r,n){if(r===void 0&&(r={}),n===void 0&&(n=bs.active()),typeof e!="number"){K.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Pr.INT&&!Number.isInteger(e)&&(K.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,r,n,Zi(Date.now()))},t}();var PP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n,o){this._record(r,n,o)},e}(Kp);var IP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n,o){if(r<0){K.warn("negative value provided to counter "+this._descriptor.name+": "+r);return}this._record(r,n,o)},e}(Kp);var OP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n,o){this._record(r,n,o)},e}(Kp);var LP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n,o){if(r<0){K.warn("negative value provided to histogram "+this._descriptor.name+": "+r);return}this._record(r,n,o)},e}(Kp);var Yp=function(){function t(e,r,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=r}return t.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},t.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},t}();var NP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Yp);var DP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Yp);var kP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Yp);function _c(t){return t instanceof Yp}var FP=function(){function t(e){this._meterSharedState=e}return t.prototype.createGauge=function(e,r){var n=Gn(e,Ie.GAUGE,r),o=this._meterSharedState.registerMetricStorage(n);return new OP(o,n)},t.prototype.createHistogram=function(e,r){var n=Gn(e,Ie.HISTOGRAM,r),o=this._meterSharedState.registerMetricStorage(n);return new LP(o,n)},t.prototype.createCounter=function(e,r){var n=Gn(e,Ie.COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new IP(o,n)},t.prototype.createUpDownCounter=function(e,r){var n=Gn(e,Ie.UP_DOWN_COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new PP(o,n)},t.prototype.createObservableGauge=function(e,r){var n=Gn(e,Ie.OBSERVABLE_GAUGE,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new DP(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableCounter=function(e,r){var n=Gn(e,Ie.OBSERVABLE_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new NP(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableUpDownCounter=function(e,r){var n=Gn(e,Ie.OBSERVABLE_UP_DOWN_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new kP(n,o,this._meterSharedState.observableRegistry)},t.prototype.addBatchObservableCallback=function(e,r){this._meterSharedState.observableRegistry.addBatchCallback(e,r)},t.prototype.removeBatchObservableCallback=function(e,r){this._meterSharedState.observableRegistry.removeBatchCallback(e,r)},t}();var Xp=function(){function t(e){this._instrumentDescriptor=e}return t.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},t.prototype.updateDescription=function(e){this._instrumentDescriptor=Gn(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},t}();var bW=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),UP=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},TW=function(){function t(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return t.prototype.get=function(e,r){return r??(r=this._hash(e)),this._valueMap.get(r)},t.prototype.getOrDefault=function(e,r){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=r();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},t.prototype.set=function(e,r,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r)},t.prototype.has=function(e,r){return r??(r=this._hash(e)),this._valueMap.has(r)},t.prototype.keys=function(){var e,r;return UP(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),r=e.next(),n.label=1;case 1:return r.done===!0?[3,3]:[4,[r.value[1],r.value[0]]];case 2:return n.sent(),r=e.next(),[3,1];case 3:return[2]}})},t.prototype.entries=function(){var e,r;return UP(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),r=e.next(),n.label=1;case 1:return r.done===!0?[3,3]:[4,[this._keyMap.get(r.value[0]),r.value[1],r.value[0]]];case 2:return n.sent(),r=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(t.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),t}();var fn=function(t){bW(e,t);function e(){return t.call(this,Lp)||this}return e}(TW);var vW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Jp=function(){function t(e,r){this._aggregator=e,this._activeCollectionStorage=new fn,this._cumulativeMemoStorage=new fn,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(r??2e3)-1,this._overflowHashCode=Lp(this._overflowAttributes)}return t.prototype.record=function(e,r,n,o){var i=this,a=this._activeCollectionStorage.get(r);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(r,a)}a?.record(e)},t.prototype.batchCumulate=function(e,r){var n=this;Array.from(e.entries()).forEach(function(o){var i=vW(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(r);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},t.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new fn,e},t}();var py=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},BP=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Qp=function(){function t(e,r){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,r.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return t.prototype.buildMetrics=function(e,r,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===Cs.CUMULATIVE?a=t.merge(c.accumulations,i,this._aggregator):a=t.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(r.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=RW(a);if(u.length!==0)return this._aggregator.toMetricData(r,s,u,o)},t.prototype._stashAccumulations=function(e){var r,n,o=this._unreportedAccumulations.keys();try{for(var i=py(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype._getMergedUnreportedAccumulations=function(e){var r,n,o=new fn,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=py(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=t.merge(o,c,this._aggregator)}}catch(l){r={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return o},t.merge=function(e,r,n){for(var o=e,i=r.entries(),a=i.next();a.done!==!0;){var s=BP(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},t.calibrateStartTime=function(e,r,n){var o,i;try{for(var a=py(e.keys()),s=a.next();!s.done;s=a.next()){var c=BP(s.value,2),l=c[0],u=c[1],d=r.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return r},t}();function RW(t){return Array.from(t.entries())}var AW=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),wW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},zP=function(t){AW(e,t);function e(r,n,o,i,a){var s=t.call(this,r)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Jp(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Qp(n,i),s}return e.prototype.record=function(r,n){var o=this,i=new fn;Array.from(r.entries()).forEach(function(a){var s=wW(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(r,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(r,this._instrumentDescriptor,o,n)},e}(Xp);Xe();function my(t,e){var r="";return t.unit!==e.unit&&(r+=" - Unit '"+t.unit+"' does not match '"+e.unit+`'
4356
+ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Bi(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,r?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let r;return typeof e=="string"?r=Ju(e):r=[e],await this.context.addCookies(r),r}async setLocalStorage(e,r){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,r],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){try{await $(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},r)=>{this.transformer&&Yx({event:r,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,r)=>{this.transformer&&this.transformer.recordKeystroke(r)})}async startRecordingCrons(e){if(e.aborted)return;let r,n=(await this.getOpenPages()).map(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(r);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];Bi(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:n,currentUrl:l,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};r=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},Lt);let s=async()=>{clearInterval(r)};e.addEventListener("abort",s,{once:!0})}async startRecording(e,r,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=r,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:de})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:r,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await ql({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:r,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new M("UserInfrastructureError",`The page with URL ${tt(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await ql({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:r,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:r=!1}=e??{};return r||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return mj.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:r,error:n}=await Mt({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:Ne,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!r)throw new M("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return r}registerDialogHandler(e){let r=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",r)}async evaluateFunctionInAllFrames(e,r){return this.stateManager.executeFunctionInAllFrames(e,r)}async evaluateFunctionInPage(e,r,n,o=Ne){let i=await this.getActivePageOrFrame();return Mt({root:i,fn:e,arg:r,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:r,context:n,timeoutMs:o=ko}){let i=XC(),a={code:e,fragment:r,context:n},{result:s}=await $(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new M("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,r){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:Ne});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:r},timeout:de})}catch(o){throw this.logger.error({err:o,x:e,y:r},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:r,percentY:n}){if(r<0||r>1||n<0||n>1)throw new M("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),c=Math.round(a),l=Math.round(s),u=Math.ceil(o*r),d=Math.ceil(i*n),p=u+l,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let r=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(r,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:de,params:{highlightConfig:Tx,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:de,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:de})}catch{}}async getTargetFromPositionPercentages(e){let r=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(r,e);return this.getTargetFromBackendNodeId({root:r,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:r,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[r];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[mo],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(hn(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let l=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:s}}async performTargetRedirection(e,r,n){try{return await this.scrollIntoViewIfNeeded(e),await $(this.performTargetRedirectionHelper(e,r,n),{milliseconds:ce})??{locator:e}}catch(o){return r.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,r,n){let o=Date.now();if(n===void 0&&(n=await e.boundingBox({timeout:ce})??void 0),!n){let E=await gn(e,r,500);r.error(`Attempted to click on element with no bounding box: ${E}`);return}let{x:i,y:a,width:s,height:c}=n,l=this.getViewport();if(i<0||a<0||!l||i+s>l.width||a+c>l.height){r.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:d,mPathSelector:p,error:m,serializedElement:g,foundElementRelativePoint:h,force:f,logs:S}=await e.evaluate(E=>{let T=window;if(!T.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return T.performTargetRedirection(E)},void 0,{timeout:de}),y=Date.now()-o;if(m){r.warn({error:m,serializedElement:g,duration:y,force:f,logs:S},"Got error from target redirection with bounding box");return}else{if(d)return r.info({newDataMomenticId:d,serializedElement:g,duration:y,force:f,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(hn(d)),hints:{relativeXYToLocator:h,force:f}};if(p)return r.info({newMPathSelector:p,serializedElement:g,duration:y,force:f,logs:S},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(p),hints:{relativeXYToLocator:h,force:f}};if(h)return r.info({foundElementRelativePoint:h,serializedElement:g,duration:y,force:f,logs:S},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:h,force:f}};if(f)return r.info({serializedElement:g,duration:y,force:f,logs:S},"Forcing click on original element"),{locator:e,hints:{force:f}}}}async fetchHtmlAttributes({locator:e,logger:r=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,s=await e.evaluate((c,l)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,l):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:Ne});if("error"in s&&s.error)throw s.error.startsWith(_C)?new Eu(s.error):s.error.startsWith(MC)?new bu(s.error):new Error(s.error);return s.warnings.length&&r.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,r){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*r);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,r,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*r),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:de})}async scrollFromPositionPercentages(e,r,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),s=Math.ceil(i.height*r);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:s,x:n,y:o}}),{deltaX:a,deltaY:s}}canSolveCaptchas(){return!!kC}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(r){this.logger.debug({err:r,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,r,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,jf(e,this.debugData,i,{type:r,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:r}){if(!cp(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=r?.trim()||Qx(e),o=uj(e),i=fj(e),a=vg[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!cp(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:hj.getType(e)||"application/octet-stream"},{timeout:Qd})}catch(l){this.logger.error({err:l},"Error handling file chooser"),this.logToUserConsole(this.page,"error",l.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:l,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=l;let p=atob(l),m=new Array(p.length);for(let h=0;h<p.length;h++)m[h]=p.charCodeAt(h);let g=new Uint8Array(m);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:s,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let r={...this.debugData};return this.debugData={logsPerPage:[]},r}async copy(e){try{await this.evaluateFunctionInPage(r=>navigator.clipboard.writeText(r),e,"copying text to clipboard")}catch(r){if(r instanceof Error&&r.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw r}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(r=>{let n=r.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,r){this.requestRecorders[e]=r}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,r,n){this.customHeaders.push({key:e.toLowerCase(),value:r,matcher:n})}registerMock(e,r,n,o){let i=e??hS();return this.mocks[i]={matcher:r,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??OC}get userBrowserSettings(){return ic(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??hs}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=rp();for(let r of e)if(!(!cp(r)||!Xx(r).isDirectory()||!["new","pending","completed"].some(o=>{let i=Sj(r,o);return cp(i)&&Xx(i).isDirectory()&&dj(i).length>0})))return r}};import Eq from"fetch-cookie";import{cloneDeep as PI}from"lodash-es";import TPe,{multistream as RPe}from"pino";import wPe from"pino-pretty";var _Pe=5*1024,Ej="...[truncated]",MPe=Buffer.byteLength(Ej,"utf8");import{PostHog as bj}from"posthog-node";async function Zx(t,e){let r,n=0,o=3,i,a;for(;n<o;)try{let s=await $(t.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=s.featureFlags||{},a=s.featureFlagPayloads||{};break}catch(s){r=s,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw r}var up=class t extends Nl{constructor(r,n,o,i){super(o,i);this.client=r;this.orgId=n}static async init(r){let n=new bj("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await Zx(n,r);return new t(n,r,o,i)}async refresh(){let{flags:r,payloads:n}=await Zx(this.client,this.orgId);this.flags=r,this.payloads=n}};import{randomUUID as Tj}from"node:crypto";import{PostHog as vj}from"posthog-node";var dp=class t{bindings;client;options;constructor(e,r={}){this.bindings=e,this.options=r,this.client=new vj("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...r})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new t({...this.bindings,...e},this.options)}track(e,r){if(!xv(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:n,...o}=e;return this.client.capture({distinctId:Tj(),event:n,timestamp:r?.timestamp,properties:{...this.bindings,...o}}),this}};import{execSync as Rj}from"child_process";import Ss from"os";import Aj from"v8";var e_,Un,t_=Ss.platform(),wj=Ss.cpus().map(t=>({model:t.model,speed:t.speed})).reduce((t,e)=>(t[e.model]={speed:e.speed},t.totalCores=(t.totalCores??0)+1,t),{}),pp=t=>{try{let e={},r=!1,n=Cj(),o=xj(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),r=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(r=!0);let s=Aj.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(r=!0),r?(t.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),Ni&&b.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):t.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}},r_=t=>{pp(t),setTimeout(()=>pp(t),5e3)};function n_(t){if(!wr)return pp(t),{interval:setInterval(()=>pp(t),2e4),cpuMetadata:wj,platform:t_}}function Cj(){let t=Ss.totalmem(),e=t_==="darwin"?_j():(()=>{let n=Ss.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),r=e.availableMemory/t;return{totalMemory:t,freeMemory:e.availableMemory,freePercentage:r}}function xj(){let t=Ss.cpus(),e=Date.now(),r={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)r.user+=o.times.user,r.nice+=o.times.nice,r.sys+=o.times.sys,r.idle+=o.times.idle,r.irq+=o.times.irq;if(r.total=r.user+r.nice+r.sys+r.idle+r.irq,!Un)return Un=r,null;let n={user:r.user-Un.user,nice:r.nice-Un.nice,sys:r.sys-Un.sys,idle:r.idle-Un.idle,irq:r.irq-Un.irq,total:r.total-Un.total};return e_={measurementTime:e,intervalMs:e-Un.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100},Un=r,e_}function _j(){try{let t=Rj("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),r=t.match(/page size of (\d+) bytes/)?.[1],n=r?Number.parseInt(r,10):4096,o=u=>{let p=t.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Ss.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var mp=class{increment(e,r,n){}gauge(e,r){}distribution(e,r,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function Mj(t){if(!t||t.length===0)return{};let e={};for(let r of t){let n=r.indexOf(":");if(n>-1){let o=r.slice(0,n).trim(),i=r.slice(n+1).trim();o&&(e[o]=i);continue}e[r]=!0}return e}function hp(t,e){let r=Mj(t);return!e||Object.keys(e).length===0?r:{...e,...r}}var P_="=",yp=";",xS=",";var I_=8192;var Ts={};zN(Ts,{getKeyPairs:()=>lV,parseKeyPairsIntoRecord:()=>cV,parsePairKeyValue:()=>O_,serializeKeyPairs:()=>sV});Je();var aV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function sV(t){return t.reduce(function(e,r){var n=""+e+(e!==""?xS:"")+r;return n.length>I_?e:n},"")}function lV(t){return t.getAllEntries().map(function(e){var r=aV(e,2),n=r[0],o=r[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=yp+o.metadata.toString()),i})}function O_(t){var e=t.split(yp);if(!(e.length<=0)){var r=e.shift();if(r){var n=r.indexOf(P_);if(!(n<=0)){var o=decodeURIComponent(r.substring(0,n).trim()),i=decodeURIComponent(r.substring(n+1).trim()),a;return e.length>0&&(a=SS(e.join(yp))),{key:o,value:i,metadata:a}}}}}function cV(t){return typeof t!="string"||t.length===0?{}:t.split(xS).map(function(e){return O_(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,r){return e[r.key]=r.value,e},{})}Je();var Ep;(function(t){t.AlwaysOff="always_off",t.AlwaysOn="always_on",t.ParentBasedAlwaysOff="parentbased_always_off",t.ParentBasedAlwaysOn="parentbased_always_on",t.ParentBasedTraceIdRatio="parentbased_traceidratio",t.TraceIdRatio="traceidratio"})(Ep||(Ep={}));var uV=",",dV=["OTEL_SDK_DISABLED"];function pV(t){return dV.indexOf(t)>-1}var mV=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_BLRP_EXPORT_TIMEOUT","OTEL_BLRP_MAX_EXPORT_BATCH_SIZE","OTEL_BLRP_MAX_QUEUE_SIZE","OTEL_BLRP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_OTLP_LOGS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function hV(t){return mV.indexOf(t)>-1}var gV=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function fV(t){return gV.indexOf(t)>-1}var _S=1/0,MS=128,SV=128,yV=128,PS={OTEL_SDK_DISABLED:!1,CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_BLRP_EXPORT_TIMEOUT:3e4,OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BLRP_MAX_QUEUE_SIZE:2048,OTEL_BLRP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_LOGS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_LOGS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:at.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:_S,OTEL_ATTRIBUTE_COUNT_LIMIT:MS,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:_S,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:MS,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:_S,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:MS,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:SV,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:yV,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Ep.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_LOGS_EXPORTER:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_LOGS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_LOGS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_LOGS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function EV(t,e,r){if(!(typeof r[t]>"u")){var n=String(r[t]);e[t]=n.toLowerCase()==="true"}}function bV(t,e,r,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof r[t]<"u"){var i=Number(r[t]);isNaN(i)||(i<n?e[t]=n:i>o?e[t]=o:e[t]=i)}}function TV(t,e,r,n){n===void 0&&(n=uV);var o=r[t];typeof o=="string"&&(e[t]=o.split(n).map(function(i){return i.trim()}))}var vV={ALL:at.ALL,VERBOSE:at.VERBOSE,DEBUG:at.DEBUG,INFO:at.INFO,WARN:at.WARN,ERROR:at.ERROR,NONE:at.NONE};function RV(t,e,r){var n=r[t];if(typeof n=="string"){var o=vV[n.toUpperCase()];o!=null&&(e[t]=o)}}function L_(t){var e={};for(var r in PS){var n=r;switch(n){case"OTEL_LOG_LEVEL":RV(n,e,t);break;default:if(pV(n))EV(n,e,t);else if(hV(n))bV(n,e,t);else if(fV(n))TV(n,e,t);else{var o=t[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function jt(){var t=L_(process.env);return Object.assign({},PS,t)}function N_(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-87:t-55}function bp(t){for(var e=new Uint8Array(t.length/2),r=0,n=0;n<t.length;n+=2){var o=N_(t.charCodeAt(n)),i=N_(t.charCodeAt(n+1));e[r++]=o<<4|i}return e}var D_="1.25.1";var AV="deployment.environment";var wV="process.runtime.name";var CV="service.name";var xV="service.instance.id";var _V="telemetry.sdk.name",MV="telemetry.sdk.language",PV="telemetry.sdk.version";var k_=AV;var F_=wV;var Tp=CV;var U_=xV;var pc=_V,mc=MV,hc=PV;var IV="nodejs";var B_=IV;var vs,vp=(vs={},vs[pc]="opentelemetry",vs[F_]="node",vs[mc]=B_,vs[hc]=D_,vs);var OV=9,LV=6,NV=Math.pow(10,LV),DV=Math.pow(10,OV);function z_(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*NV);return[r,n]}function H_(t){return t[0]*DV+t[1]}function gc(t){return t[0]*1e6+t[1]/1e3}var Yi;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Yi||(Yi={}));var G_=function(){function t(){var e=this;this._promise=new Promise(function(r,n){e._resolve=r,e._reject=n})}return Object.defineProperty(t.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),t.prototype.resolve=function(e){this._resolve(e)},t.prototype.reject=function(e){this._reject(e)},t}();var kV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},FV=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},j_=function(){function t(e,r){this._callback=e,this._that=r,this._isCalled=!1,this._deferred=new G_}return Object.defineProperty(t.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),t.prototype.call=function(){for(var e,r=this,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];if(!this._isCalled){this._isCalled=!0;try{Promise.resolve((e=this._callback).call.apply(e,FV([this._that],kV(n),!1))).then(function(i){return r._deferred.resolve(i)},function(i){return r._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},t}();var Kr;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(Kr||(Kr={}));var Zt;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Zt||(Zt={}));var UV=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}();var cLe=function(t){UV(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function V_(t,e){for(var r=0,n=t.length-1;n-r>1;){var o=Math.trunc((n+r)/2);t[o]<=e?r=o:n=o-1}return t[n]<=e?n:t[r]<=e?r:-1}Je();var Yr;(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Yr||(Yr={}));var $_=function(){function t(){this.kind=Yr.DROP}return t.prototype.createAccumulation=function(){},t.prototype.merge=function(e,r){},t.prototype.diff=function(e,r){},t.prototype.toMetricData=function(e,r,n,o){},t}();var ye;(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ye||(ye={}));var BV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function zV(t){var e=t.map(function(){return 0});return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var IS=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=zV(r)),this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=o}return t.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var r=V_(this._boundaries,e);this._current.buckets.counts[r+1]+=1}},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var OS=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=Yr.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new IS(e,this._boundaries,this._recordMinMax)},t.prototype.merge=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new IS(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},t.prototype.diff=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new IS(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Zt.HISTOGRAM,dataPoints:n.map(function(i){var a=BV(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ye.GAUGE||e.type===ye.UP_DOWN_COUNTER||e.type===ye.OBSERVABLE_GAUGE||e.type===ye.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},t}();Je();var LS=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},NS=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},DS=function(){function t(e,r,n,o){e===void 0&&(e=new HV),r===void 0&&(r=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(t.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),t.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(r,n){return e.at(n)})},t.prototype.at=function(e){var r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)},t.prototype.incrementBucket=function(e,r){this.backing.increment(e,r)},t.prototype.decrementBucket=function(e,r){this.backing.decrement(e,r)},t.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},t.prototype.downscale=function(e){this._rotate();for(var r=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<r;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},t.prototype.clone=function(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},t.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},t.prototype._relocateBucket=function(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))},t}();var HV=function(){function t(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(t.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),t.prototype.countAt=function(e){return this._counts[e]},t.prototype.growTo=function(e,r,n){var o=new Array(e).fill(0);o.splice.apply(o,NS([n,this._counts.length-r],LS(this._counts.slice(r)),!1)),o.splice.apply(o,NS([0,r],LS(this._counts.slice(0,r)),!1)),this._counts=o},t.prototype.reverse=function(e,r){for(var n=Math.floor((e+r)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[r-o-1],this._counts[r-o-1]=i}},t.prototype.emptyBucket=function(e){var r=this._counts[e];return this._counts[e]=0,r},t.prototype.increment=function(e,r){this._counts[e]+=r},t.prototype.decrement=function(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0},t.prototype.clone=function(){return new t(NS([],LS(this._counts),!1))},t}();var W_=52,GV=2146435072,jV=1048575,kS=1023,Rp=-kS+1,Ap=kS,fc=Math.pow(2,-1022);function wp(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&GV)>>20;return n-kS}function Cp(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&jV)*Math.pow(2,32);return o+n}function Sc(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function K_(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var VV=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Qo=function(t){VV(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var X_=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<fc)return this._minNormalLowerBoundaryIndex();var r=wp(e),n=this._rightShift(Cp(e)-1,W_);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new Qo("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Qo("overflow: "+e+" is > maximum lower boundary: "+n);return Sc(1,e<<this._shift)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){var e=Rp>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Ap>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var J_=function(){function t(e){this._scale=e,this._scaleFactor=Sc(Math.LOG2E,e),this._inverseFactor=Sc(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=fc)return this._minNormalLowerBoundaryIndex()-1;if(Cp(e)===0){var r=wp(e);return(r<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},t.prototype.lowerBoundary=function(e){var r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Qo("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return fc;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Qo("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){return Rp<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Ap+1<<this._scale)-1},t}();var Q_=-10,Z_=20,$V=Array.from({length:31},function(t,e){return e>10?new J_(e-10):new X_(e-10)});function FS(t){if(t>Z_||t<Q_)throw new Qo("expected scale >= "+Q_+" && <= "+Z_+", got: "+t);return $V[t+10]}var WV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},xp=function(){function t(e,r){this.low=e,this.high=r}return t.combine=function(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))},t}(),qV=20,KV=160,US=2,YV=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=KV),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new DS),u===void 0&&(u=new DS),d===void 0&&(d=FS(qV)),this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<US&&(K.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+US),this._maxSize=US)}return t.prototype.record=function(e){this.updateByIncrement(e,1)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(t.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),t.prototype.updateByIncrement=function(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}},t.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)},t.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)},t.prototype.clone=function(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},t.prototype._updateBuckets=function(e,r,n){var o=this._mapping.mapToIndex(r),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,o,n)},t.prototype._incrementIndexBy=function(e,r,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){var o=e.indexEnd-r;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=r}else if(r>e.indexEnd){var o=r-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=r}var i=r-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},t.prototype._grow=function(e,r){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=K_(r);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},t.prototype._changeScale=function(e,r){for(var n=0;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n},t.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=FS(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=xp.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=xp.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(o.high,o.low))},t.prototype._highLowAtScale=function(e,r,n){if(e.length===0)return new xp(0,-1);var o=r-n;return new xp(e.indexStart>>o,e.indexEnd>>o)},t.prototype._mergeBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},t.prototype._diffBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},t}();var eM=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=Yr.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new YV(e,this._maxSize,this._recordMinMax)},t.prototype.merge=function(e,r){var n=r.clone();return n.merge(e),n},t.prototype.diff=function(e,r){var n=r.clone();return n.diff(e),n},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Zt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=WV(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ye.GAUGE||e.type===ye.UP_DOWN_COUNTER||e.type===ye.OBSERVABLE_GAUGE||e.type===ye.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},t}();var XV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},BS=function(){function t(e,r,n){r===void 0&&(r=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=r,this.sampleTime=n}return t.prototype.record=function(e){this._current=e,this.sampleTime=z_(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var tM=function(){function t(){this.kind=Yr.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new BS(e)},t.prototype.merge=function(e,r){var n=gc(r.sampleTime)>=gc(e.sampleTime)?r:e;return new BS(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=gc(r.sampleTime)>=gc(e.sampleTime)?r:e;return new BS(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Zt.GAUGE,dataPoints:n.map(function(i){var a=XV(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var JV=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},yc=function(){function t(e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=r,this._current=n,this.reset=o}return t.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var zS=function(){function t(e){this.monotonic=e,this.kind=Yr.SUM}return t.prototype.createAccumulation=function(e){return new yc(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new yc(r.startTime,this.monotonic,o,r.reset):new yc(e.startTime,this.monotonic,n+o)},t.prototype.diff=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return this.monotonic&&n>o?new yc(r.startTime,this.monotonic,o,!0):new yc(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Zt.SUM,dataPoints:n.map(function(i){var a=JV(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var Xi=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),zn=function(){function t(){}return t.Drop=function(){return cM},t.Sum=function(){return uM},t.LastValue=function(){return dM},t.Histogram=function(){return pM},t.ExponentialHistogram=function(){return QV},t.Default=function(){return ZV},t}();var rM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new $_,e}(zn);var nM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case ye.COUNTER:case ye.OBSERVABLE_COUNTER:case ye.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new zS(!0),e.NON_MONOTONIC_INSTANCE=new zS(!1),e}(zn);var oM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new tM,e}(zn);var iM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new OS([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(zn);var aM=function(t){Xi(e,t);function e(r,n){n===void 0&&(n=!0);var o=t.call(this)||this;if(o._recordMinMax=n,r==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");r=r.concat(),r=r.sort(function(s,c){return s-c});var i=r.lastIndexOf(-1/0),a=r.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=r.slice(i+1,a),o}return e.prototype.createAggregator=function(r){return new OS(this._boundaries,this._recordMinMax)},e}(zn);var sM=function(t){Xi(e,t);function e(r,n){r===void 0&&(r=160),n===void 0&&(n=!0);var o=t.call(this)||this;return o._maxSize=r,o._recordMinMax=n,o}return e.prototype.createAggregator=function(r){return new eM(this._maxSize,this._recordMinMax)},e}(zn);var lM=function(t){Xi(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case ye.COUNTER:case ye.UP_DOWN_COUNTER:case ye.OBSERVABLE_COUNTER:case ye.OBSERVABLE_UP_DOWN_COUNTER:return uM;case ye.GAUGE:case ye.OBSERVABLE_GAUGE:return dM;case ye.HISTOGRAM:return r.advice.explicitBucketBoundaries?new aM(r.advice.explicitBucketBoundaries):pM}return K.warn("Unable to recognize instrument type: "+r.type),cM},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(zn);var cM=new rM,uM=new nM,dM=new oM,pM=new iM,QV=new sM,ZV=new lM;Je();function _p(){return"unknown_service:"+process.argv0}var Zo=function(){return Zo=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},Zo.apply(this,arguments)},e$=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},t$=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},r$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},HS=function(){function t(e,r){var n=this,o;this._attributes=e,this.asyncAttributesPending=r!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=r?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return K.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return t.empty=function(){return t.EMPTY},t.default=function(){var e;return new t((e={},e[Tp]=_p(),e[mc]=vp[mc],e[pc]=vp[pc],e[hc]=vp[hc],e))},Object.defineProperty(t.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&K.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),t.prototype.waitForAsyncAttributes=function(){return e$(this,void 0,void 0,function(){return t$(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},t.prototype.merge=function(e){var r=this,n;if(!e)return this;var o=Zo(Zo({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=r$(a,2),l=c[0],u=c[1];return Zo(Zo(Zo(Zo({},r._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new t(o,i)},t.EMPTY=new t({}),t}();var Ji;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE",t[t.LOWMEMORY=2]="LOWMEMORY"})(Ji||(Ji={}));Je();var n$=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},o$=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},GS=function(){return Kr.CUMULATIVE},mM=function(t){switch(t){case ye.COUNTER:case ye.OBSERVABLE_COUNTER:case ye.GAUGE:case ye.HISTOGRAM:case ye.OBSERVABLE_GAUGE:return Kr.DELTA;case ye.UP_DOWN_COUNTER:case ye.OBSERVABLE_UP_DOWN_COUNTER:return Kr.CUMULATIVE}},hM=function(t){switch(t){case ye.COUNTER:case ye.HISTOGRAM:return Kr.DELTA;case ye.GAUGE:case ye.UP_DOWN_COUNTER:case ye.OBSERVABLE_UP_DOWN_COUNTER:case ye.OBSERVABLE_COUNTER:case ye.OBSERVABLE_GAUGE:return Kr.CUMULATIVE}};function i$(){var t=jt(),e=t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?GS:e==="delta"?mM:e==="lowmemory"?hM:(K.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+t.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),GS)}function a$(t){return t!=null?t===Ji.DELTA?mM:t===Ji.LOWMEMORY?hM:GS:i$()}function s$(t){return t?.aggregationPreference?t.aggregationPreference:function(e){return zn.Default()}}var gM=function(){function t(e,r){this._otlpExporter=e,this._aggregationSelector=s$(r),this._aggregationTemporalitySelector=a$(r?.temporalityPreference)}return t.prototype.export=function(e,r){this._otlpExporter.export([e],r)},t.prototype.shutdown=function(){return n$(this,void 0,void 0,function(){return o$(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},t.prototype.forceFlush=function(){return Promise.resolve()},t.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},t.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},t}();Je();Je();var l$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},fM=1e4,SM=5,yM=1e3,EM=5e3,bM=1.5;function Ec(t){t===void 0&&(t={});var e={};return Object.entries(t).forEach(function(r){var n=l$(r,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):K.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function jS(t,e){return t.endsWith("/")||(t=t+"/"),t+e}function VS(t){try{var e=new URL(t);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return K.warn("Could not parse export URL: '"+t+"'"),t}}function $S(t){return typeof t=="number"?t<=0?WS(t,fM):t:c$()}function c$(){var t,e=Number((t=jt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&t!==void 0?t:jt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?WS(e,fM):e}function WS(t,e){return K.warn("Timeout must be greater than 0",t),e}function TM(t){var e=[429,502,503,504];return e.includes(t)}function vM(t){if(t==null)return-1;var e=Number.parseInt(t,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var r=new Date(t).getTime()-Date.now();return r>=0?r:0}var RM=function(){function t(e){e===void 0&&(e={}),this._sendingPromises=[],this.url=this.getDefaultUrl(e),typeof e.hostname=="string"&&(this.hostname=e.hostname),this.shutdown=this.shutdown.bind(this),this._shutdownOnce=new j_(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=$S(e.timeoutMillis),this.onInit(e)}return t.prototype.export=function(e,r){if(this._shutdownOnce.isCalled){r({code:Yi.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){r({code:Yi.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){r({code:Yi.SUCCESS})}).catch(function(n){r({code:Yi.FAILED,error:n})})},t.prototype._export=function(e){var r=this;return new Promise(function(n,o){try{K.debug("items to be sent",e),r.send(e,n,o)}catch(i){o(i)}})},t.prototype.shutdown=function(){return this._shutdownOnce.call()},t.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},t.prototype._shutdown=function(){return K.debug("shutdown started"),this.onShutdown(),this.forceFlush()},t}();Je();import*as qS from"url";import*as Pp from"http";import*as Ip from"https";import*as AM from"zlib";import{Readable as d$}from"stream";var ei;(function(t){t.NONE="none",t.GZIP="gzip"})(ei||(ei={}));var u$=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Rs=function(t){u$(e,t);function e(r,n,o){var i=t.call(this,r)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var Mp=function(){return Mp=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},Mp.apply(this,arguments)};function KS(t,e,r,n,o){var i=t.timeoutMillis,a=new qS.URL(t.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new Rs("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Mp({"Content-Type":r},t.headers),agent:t.agent},m=a.protocol==="http:"?Pp.request:Ip.request,g=function(h,f){switch(h===void 0&&(h=SM),f===void 0&&(f=yM),l=m(p,function(y){var E="";y.on("data",function(T){return E+=T}),y.on("aborted",function(){if(u){var T=new Rs("Request Timeout");o(T)}}),y.on("end",function(){if(u===!1)if(y.statusCode&&y.statusCode<299)K.debug("statusCode: "+y.statusCode,E),n(),clearTimeout(d),clearTimeout(c);else if(y.statusCode&&TM(y.statusCode)&&h>0){var T=void 0;f=bM*f,y.headers["retry-after"]?T=vM(y.headers["retry-after"]):T=Math.round(Math.random()*(EM-f)+f),c=setTimeout(function(){g(h-1,f)},T)}else{var v=new Rs(y.statusMessage,y.statusCode,E);o(v),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(y){if(u){var E=new Rs("Request Timeout",y.code);o(E)}else o(y);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var y=new Rs("Request Timeout");o(y)}clearTimeout(d),clearTimeout(c)}),t.compression){case ei.GZIP:{l.setHeader("Content-Encoding","gzip");var S=p$(e);S.on("error",o).pipe(AM.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function p$(t){var e=new d$;return e.push(t),e.push(null),e}function YS(t){if(t.httpAgentOptions&&t.keepAlive===!1){K.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(t.keepAlive===!1||!t.url))try{var e=new qS.URL(t.url),r=e.protocol==="http:"?Pp.Agent:Ip.Agent;return new r(Mp({keepAlive:!0},t.httpAgentOptions))}catch(n){K.error("collector exporter failed to create http agent. err: "+n.message);return}}function XS(t){if(t)return t;var e=jt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||jt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===ei.GZIP?ei.GZIP:ei.NONE}Je();var m$=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Op=function(t){m$(e,t);function e(r,n,o){r===void 0&&(r={});var i=t.call(this,r)||this;return i.DEFAULT_HEADERS={},i._contentType=o,r.metadata&&K.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Ec(r.headers),Ts.parseKeyPairsIntoRecord(jt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=YS(r),i.compression=XS(r.compression),i._serializer=n,i}return e.prototype.onInit=function(r){},e.prototype.send=function(r,n,o){var i=this;if(this._shutdownOnce.isCalled){K.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;KS(i,(u=i._serializer.serializeRequest(r))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(RM);function CM(t){var e=BigInt(1e9);return BigInt(t[0])*e+BigInt(t[1])}function h$(t){var e=Number(BigInt.asUintN(32,t)),r=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:r}}function xM(t){var e=CM(t);return h$(e)}function g$(t){var e=CM(t);return e.toString()}var f$=typeof BigInt<"u"?g$:H_;function wM(t){return t}function _M(t){if(t!==void 0)return bp(t)}var S$={encodeHrTime:xM,encodeSpanContext:bp,encodeOptionalSpanContext:_M};function MM(t){var e,r;if(t===void 0)return S$;var n=(e=t.useLongBits)!==null&&e!==void 0?e:!0,o=(r=t.useHex)!==null&&r!==void 0?r:!1;return{encodeHrTime:n?xM:f$,encodeSpanContext:o?wM:bp,encodeOptionalSpanContext:o?wM:_M}}var y$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function PM(t){return{name:t.name,version:t.version}}function As(t){return Object.keys(t).map(function(e){return IM(e,t[e])})}function IM(t,e){return{key:t,value:OM(e)}}function OM(t){var e=typeof t;return e==="string"?{stringValue:t}:e==="number"?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:e==="boolean"?{boolValue:t}:t instanceof Uint8Array?{bytesValue:t}:Array.isArray(t)?{arrayValue:{values:t.map(OM)}}:e==="object"&&t!=null?{kvlistValue:{values:Object.entries(t).map(function(r){var n=y$(r,2),o=n[0],i=n[1];return IM(o,i)})}}:{}}function LM(t){return{attributes:As(t.attributes),droppedAttributesCount:0}}Je();function DM(t,e){var r=MM(e);return{resource:LM(t.resource),schemaUrl:void 0,scopeMetrics:E$(t.scopeMetrics,r)}}function E$(t,e){return Array.from(t.map(function(r){return{scope:PM(r.scope),metrics:r.metrics.map(function(n){return b$(n,e)}),schemaUrl:r.scope.schemaUrl}}))}function b$(t,e){var r={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit},n=A$(t.aggregationTemporality);switch(t.dataPointType){case Zt.SUM:r.sum={aggregationTemporality:n,isMonotonic:t.isMonotonic,dataPoints:NM(t,e)};break;case Zt.GAUGE:r.gauge={dataPoints:NM(t,e)};break;case Zt.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:v$(t,e)};break;case Zt.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:R$(t,e)};break}return r}function T$(t,e,r){var n={attributes:As(t.attributes),startTimeUnixNano:r.encodeHrTime(t.startTime),timeUnixNano:r.encodeHrTime(t.endTime)};switch(e){case Pr.INT:n.asInt=t.value;break;case Pr.DOUBLE:n.asDouble=t.value;break}return n}function NM(t,e){return t.dataPoints.map(function(r){return T$(r,t.descriptor.valueType,e)})}function v$(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:As(r.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(r.startTime),timeUnixNano:e.encodeHrTime(r.endTime)}})}function R$(t,e){return t.dataPoints.map(function(r){var n=r.value;return{attributes:As(r.attributes),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:e.encodeHrTime(r.startTime),timeUnixNano:e.encodeHrTime(r.endTime)}})}function A$(t){switch(t){case Kr.DELTA:return 1;case Kr.CUMULATIVE:return 2}}function kM(t,e){return{resourceMetrics:t.map(function(r){return DM(r,e)})}}var JS={serializeRequest:function(t){var e=kM(t,{useLongBits:!1}),r=new TextEncoder;return r.encode(JSON.stringify(e))},deserializeResponse:function(t){var e=new TextDecoder;return JSON.parse(e.decode(t))}};var FM="0.52.1";var UM=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),ws=function(){return ws=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},ws.apply(this,arguments)},BM="v1/metrics",w$="http://localhost:4318/"+BM,C$={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+FM},x$=function(t){UM(e,t);function e(r){var n=t.call(this,r,JS,"application/json")||this;return n.headers=ws(ws(ws(ws({},n.headers),C$),Ts.parseKeyPairsIntoRecord(jt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ec(r?.headers)),n}return e.prototype.getDefaultUrl=function(r){return typeof r.url=="string"?r.url:jt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?VS(jt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):jt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?jS(jt().OTEL_EXPORTER_OTLP_ENDPOINT,BM):w$},e}(Op),zM=function(t){UM(e,t);function e(r){return t.call(this,new x$(r),r)||this}return e}(gM);var Cs;(function(t){t[t.DELTA=0]="DELTA",t[t.CUMULATIVE=1]="CUMULATIVE"})(Cs||(Cs={}));var Hn;(function(t){t[t.HISTOGRAM=0]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",t[t.GAUGE=2]="GAUGE",t[t.SUM=3]="SUM"})(Hn||(Hn={}));Je();var _$=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),HM=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},GM=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},M$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},P$=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},I$=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function jM(t){return t!=null}function Lp(t){var e=Object.keys(t);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(r){return[r,t[r]]})))}function VM(t){var e,r;return t.name+":"+((e=t.version)!==null&&e!==void 0?e:"")+":"+((r=t.schemaUrl)!==null&&r!==void 0?r:"")}var QS=function(t){_$(e,t);function e(r){var n=t.call(this,r)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function ti(t,e){var r,n=new Promise(function(i,a){r=setTimeout(function(){a(new QS("Operation timed out."))},e)});return Promise.race([t,n]).then(function(o){return clearTimeout(r),o},function(o){throw clearTimeout(r),o})}function $M(t){return HM(this,void 0,void 0,function(){var e=this;return GM(this,function(r){return[2,Promise.all(t.map(function(n){return HM(e,void 0,void 0,function(){var o,i;return GM(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,n];case 1:return o=a.sent(),[2,{status:"fulfilled",value:o}];case 2:return i=a.sent(),[2,{status:"rejected",reason:i}];case 3:return[2]}})})}))]})})}function WM(t){return t.status==="rejected"}function ZS(t,e){var r=[];return t.forEach(function(n){r.push.apply(r,P$([],M$(e(n)),!1))}),r}function qM(t,e){var r,n;if(t.size!==e.size)return!1;try{for(var o=I$(t),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){r={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return!0}function KM(t,e){for(var r=0,n=t.length-1,o=t.length;n>=r;){var i=r+Math.trunc((n-r)/2);t[i]<e?r=i+1:(o=i,n=i-1)}return o}function YM(t,e){return t.toLowerCase()===e.toLowerCase()}Je();var Xr;(function(t){t[t.DROP=0]="DROP",t[t.SUM=1]="SUM",t[t.LAST_VALUE=2]="LAST_VALUE",t[t.HISTOGRAM=3]="HISTOGRAM",t[t.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Xr||(Xr={}));var ey=function(){function t(){this.kind=Xr.DROP}return t.prototype.createAccumulation=function(){},t.prototype.merge=function(e,r){},t.prototype.diff=function(e,r){},t.prototype.toMetricData=function(e,r,n,o){},t}();Je();var Ie;(function(t){t.COUNTER="COUNTER",t.GAUGE="GAUGE",t.HISTOGRAM="HISTOGRAM",t.UP_DOWN_COUNTER="UP_DOWN_COUNTER",t.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",t.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",t.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(Ie||(Ie={}));function Gn(t,e,r){var n,o,i,a;return L$(t)||K.warn('Invalid metric name: "'+t+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:t,type:e,description:(n=r?.description)!==null&&n!==void 0?n:"",unit:(o=r?.unit)!==null&&o!==void 0?o:"",valueType:(i=r?.valueType)!==null&&i!==void 0?i:Pr.DOUBLE,advice:(a=r?.advice)!==null&&a!==void 0?a:{}}}function XM(t,e){var r,n;return{name:(r=t.name)!==null&&r!==void 0?r:e.name,description:(n=t.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function JM(t,e){return YM(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}var O$=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function L$(t){return t.match(O$)!=null}var N$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i};function D$(t){var e=t.map(function(){return 0});return e.push(0),{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Np=function(){function t(e,r,n,o){n===void 0&&(n=!0),o===void 0&&(o=D$(r)),this.startTime=e,this._boundaries=r,this._recordMinMax=n,this._current=o}return t.prototype.record=function(e){if(!Number.isNaN(e)){this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);var r=KM(this._boundaries,e);this._current.buckets.counts[r]+=1}},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var Dp=function(){function t(e,r){this._boundaries=e,this._recordMinMax=r,this.kind=Xr.HISTOGRAM}return t.prototype.createAccumulation=function(e){return new Np(e,this._boundaries,this._recordMinMax)},t.prototype.merge=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new Np(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},t.prototype.diff=function(e,r){for(var n=e.toPointValue(),o=r.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new Np(r.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Hn.HISTOGRAM,dataPoints:n.map(function(i){var a=N$(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Ie.GAUGE||e.type===Ie.UP_DOWN_COUNTER||e.type===Ie.OBSERVABLE_GAUGE||e.type===Ie.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},t}();Je();var ty=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},ry=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},ny=function(){function t(e,r,n,o){e===void 0&&(e=new k$),r===void 0&&(r=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=r,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(t.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"length",{get:function(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1},enumerable:!1,configurable:!0}),t.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(r,n){return e.at(n)})},t.prototype.at=function(e){var r=this.indexBase-this.indexStart;return e<r&&(e+=this.backing.length),e-=r,this.backing.countAt(e)},t.prototype.incrementBucket=function(e,r){this.backing.increment(e,r)},t.prototype.decrementBucket=function(e,r){this.backing.decrement(e,r)},t.prototype.trim=function(){for(var e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(var e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()},t.prototype.downscale=function(e){this._rotate();for(var r=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var s=a%n;s<0&&(s+=n);for(var c=s;c<n&&o<r;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},t.prototype.clone=function(){return new t(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},t.prototype._rotate=function(){var e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)},t.prototype._relocateBucket=function(e,r){e!==r&&this.incrementBucket(e,this.backing.emptyBucket(r))},t}();var k$=function(){function t(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(t.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),t.prototype.countAt=function(e){return this._counts[e]},t.prototype.growTo=function(e,r,n){var o=new Array(e).fill(0);o.splice.apply(o,ry([n,this._counts.length-r],ty(this._counts.slice(r)),!1)),o.splice.apply(o,ry([0,r],ty(this._counts.slice(0,r)),!1)),this._counts=o},t.prototype.reverse=function(e,r){for(var n=Math.floor((e+r)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[r-o-1],this._counts[r-o-1]=i}},t.prototype.emptyBucket=function(e){var r=this._counts[e];return this._counts[e]=0,r},t.prototype.increment=function(e,r){this._counts[e]+=r},t.prototype.decrement=function(e,r){this._counts[e]>=r?this._counts[e]-=r:this._counts[e]=0},t.prototype.clone=function(){return new t(ry([],ty(this._counts),!1))},t}();var QM=52,F$=2146435072,U$=1048575,oy=1023,kp=-oy+1,Fp=oy,bc=Math.pow(2,-1022);function Up(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=(r&F$)>>20;return n-oy}function Bp(t){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);var r=e.getUint32(0),n=e.getUint32(4),o=(r&U$)*Math.pow(2,32);return o+n}function Tc(t,e){return t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)?t:t*Math.pow(2,e)}function eP(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t++,t}var B$=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),ri=function(t){B$(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Error);var rP=function(){function t(e){this._shift=-e}return t.prototype.mapToIndex=function(e){if(e<bc)return this._minNormalLowerBoundaryIndex();var r=Up(e),n=this._rightShift(Bp(e)-1,QM);return r+n>>this._shift},t.prototype.lowerBoundary=function(e){var r=this._minNormalLowerBoundaryIndex();if(e<r)throw new ri("underflow: "+e+" is < minimum lower boundary: "+r);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new ri("overflow: "+e+" is > maximum lower boundary: "+n);return Tc(1,e<<this._shift)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){var e=kp>>this._shift;return this._shift<2&&e--,e},t.prototype._maxNormalLowerBoundaryIndex=function(){return Fp>>this._shift},t.prototype._rightShift=function(e,r){return Math.floor(e*Math.pow(2,-r))},t}();var nP=function(){function t(e){this._scale=e,this._scaleFactor=Tc(Math.LOG2E,e),this._inverseFactor=Tc(Math.LN2,-e)}return t.prototype.mapToIndex=function(e){if(e<=bc)return this._minNormalLowerBoundaryIndex()-1;if(Bp(e)===0){var r=Up(e);return(r<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},t.prototype.lowerBoundary=function(e){var r=this._maxNormalLowerBoundaryIndex();if(e>=r){if(e===r)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new ri("overflow: "+e+" is > maximum lower boundary: "+r)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return bc;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new ri("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(t.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),t.prototype._minNormalLowerBoundaryIndex=function(){return kp<<this._scale},t.prototype._maxNormalLowerBoundaryIndex=function(){return(Fp+1<<this._scale)-1},t}();var oP=-10,iP=20,z$=Array.from({length:31},function(t,e){return e>10?new nP(e-10):new rP(e-10)});function iy(t){if(t>iP||t<oP)throw new ri("expected scale >= "+oP+" && <= "+iP+", got: "+t);return z$[t+10]}var H$=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},zp=function(){function t(e,r){this.low=e,this.high=r}return t.combine=function(e,r){return new t(Math.min(e.low,r.low),Math.max(e.high,r.high))},t}(),G$=20,j$=160,ay=2,aP=function(){function t(e,r,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),r===void 0&&(r=j$),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new ny),u===void 0&&(u=new ny),d===void 0&&(d=iy(G$)),this.startTime=e,this._maxSize=r,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<ay&&(K.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+ay),this._maxSize=ay)}return t.prototype.record=function(e){this.updateByIncrement(e,1)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}},Object.defineProperty(t.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),t.prototype.updateByIncrement=function(e,r){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=r,e===0){this._zeroCount+=r;return}this._sum+=e*r,e>0?this._updateBuckets(this._positive,e,r):this._updateBuckets(this._negative,-e,r)}},t.prototype.merge=function(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;var r=this._minScale(e);this._downscale(this.scale-r),this._mergeBuckets(this.positive,e,e.positive,r),this._mergeBuckets(this.negative,e,e.negative,r)},t.prototype.diff=function(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;var r=this._minScale(e);this._downscale(this.scale-r),this._diffBuckets(this.positive,e,e.positive,r),this._diffBuckets(this.negative,e,e.negative,r)},t.prototype.clone=function(){return new t(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},t.prototype._updateBuckets=function(e,r,n){var o=this._mapping.mapToIndex(r),i=!1,a=0,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(r)}this._incrementIndexBy(e,o,n)},t.prototype._incrementIndexBy=function(e,r,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=r),r<e.indexStart){var o=e.indexEnd-r;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=r}else if(r>e.indexEnd){var o=r-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=r}var i=r-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},t.prototype._grow=function(e,r){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=eP(r);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},t.prototype._changeScale=function(e,r){for(var n=0;e-r>=this._maxSize;)e>>=1,r>>=1,n++;return n},t.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var r=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=iy(r)}},t.prototype._minScale=function(e){var r=Math.min(this.scale,e.scale),n=zp.combine(this._highLowAtScale(this.positive,this.scale,r),this._highLowAtScale(e.positive,e.scale,r)),o=zp.combine(this._highLowAtScale(this.negative,this.scale,r),this._highLowAtScale(e.negative,e.scale,r));return Math.min(r-this._changeScale(n.high,n.low),r-this._changeScale(o.high,o.low))},t.prototype._highLowAtScale=function(e,r,n){if(e.length===0)return new zp(0,-1);var o=r-n;return new zp(e.indexStart>>o,e.indexEnd>>o)},t.prototype._mergeBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},t.prototype._diffBuckets=function(e,r,n,o){for(var i=n.offset,a=r.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},t}();var sy=function(){function t(e,r){this._maxSize=e,this._recordMinMax=r,this.kind=Xr.EXPONENTIAL_HISTOGRAM}return t.prototype.createAccumulation=function(e){return new aP(e,this._maxSize,this._recordMinMax)},t.prototype.merge=function(e,r){var n=r.clone();return n.merge(e),n},t.prototype.diff=function(e,r){var n=r.clone();return n.diff(e),n},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Hn.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=H$(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===Ie.GAUGE||e.type===Ie.UP_DOWN_COUNTER||e.type===Ie.OBSERVABLE_GAUGE||e.type===Ie.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},t}();Je();var V$=yS("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function sP(t){return t.setValue(V$,!0)}Je();function lP(){return function(t){K.error($$(t))}}function $$(t){return typeof t=="string"?t:JSON.stringify(W$(t))}function W$(t){for(var e={},r=t;r!==null;)Object.getOwnPropertyNames(r).forEach(function(n){if(!e[n]){var o=r[n];o&&(e[n]=String(o))}}),r=Object.getPrototypeOf(r);return e}var q$=lP();function Hp(t){try{q$(t)}catch{}}var cP="1.30.1";var K$="process.runtime.name";var Y$="service.name";var X$="telemetry.sdk.name",J$="telemetry.sdk.language",Q$="telemetry.sdk.version";var uP=K$;var dP=Y$;var vc=X$,Rc=J$,Ac=Q$;var Z$="nodejs";var pP=Z$;var xs,Qi=(xs={},xs[vc]="opentelemetry",xs[uP]="node",xs[Rc]=pP,xs[Ac]=cP,xs);function wc(t){t.unref()}var aW=9,sW=6,lW=Math.pow(10,sW),mke=Math.pow(10,aW);function Zi(t){var e=t/1e3,r=Math.trunc(e),n=Math.round(t%1e3*lW);return[r,n]}function _s(t){return t[0]*1e6+t[1]/1e3}var Cc;(function(t){t[t.SUCCESS=0]="SUCCESS",t[t.FAILED=1]="FAILED"})(Cc||(Cc={}));Je();function mP(t,e){return new Promise(function(r){bs.with(sP(bs.active()),function(){t.export(e,function(n){r(n)})})})}var hP={_export:mP};var cW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Gp=function(){function t(e,r,n){r===void 0&&(r=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=r,this.sampleTime=n}return t.prototype.record=function(e){this._current=e,this.sampleTime=Zi(Date.now())},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var ly=function(){function t(){this.kind=Xr.LAST_VALUE}return t.prototype.createAccumulation=function(e){return new Gp(e)},t.prototype.merge=function(e,r){var n=_s(r.sampleTime)>=_s(e.sampleTime)?r:e;return new Gp(e.startTime,n.toPointValue(),n.sampleTime)},t.prototype.diff=function(e,r){var n=_s(r.sampleTime)>=_s(e.sampleTime)?r:e;return new Gp(r.startTime,n.toPointValue(),n.sampleTime)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Hn.GAUGE,dataPoints:n.map(function(i){var a=cW(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},t}();var uW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Ms=function(){function t(e,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=r,this._current=n,this.reset=o}return t.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},t.prototype.setStartTime=function(e){this.startTime=e},t.prototype.toPointValue=function(){return this._current},t}();var jp=function(){function t(e){this.monotonic=e,this.kind=Xr.SUM}return t.prototype.createAccumulation=function(e){return new Ms(e,this.monotonic)},t.prototype.merge=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return r.reset?new Ms(r.startTime,this.monotonic,o,r.reset):new Ms(e.startTime,this.monotonic,n+o)},t.prototype.diff=function(e,r){var n=e.toPointValue(),o=r.toPointValue();return this.monotonic&&n>o?new Ms(r.startTime,this.monotonic,o,!0):new Ms(r.startTime,this.monotonic,o-n)},t.prototype.toMetricData=function(e,r,n,o){return{descriptor:e,aggregationTemporality:r,dataPointType:Hn.SUM,dataPoints:n.map(function(i){var a=uW(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},t}();var ea=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Jr=function(){function t(){}return t.Drop=function(){return TP},t.Sum=function(){return vP},t.LastValue=function(){return RP},t.Histogram=function(){return AP},t.ExponentialHistogram=function(){return dW},t.Default=function(){return pW},t}();var gP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new ey,e}(Jr);var fP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){switch(r.type){case Ie.COUNTER:case Ie.OBSERVABLE_COUNTER:case Ie.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new jp(!0),e.NON_MONOTONIC_INSTANCE=new jp(!1),e}(Jr);var SP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new ly,e}(Jr);var yP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.createAggregator=function(r){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Dp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Jr);var xc=function(t){ea(e,t);function e(r,n){n===void 0&&(n=!0);var o=t.call(this)||this;if(o._recordMinMax=n,r==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");r=r.concat(),r=r.sort(function(s,c){return s-c});var i=r.lastIndexOf(-1/0),a=r.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=r.slice(i+1,a),o}return e.prototype.createAggregator=function(r){return new Dp(this._boundaries,this._recordMinMax)},e}(Jr);var EP=function(t){ea(e,t);function e(r,n){r===void 0&&(r=160),n===void 0&&(n=!0);var o=t.call(this)||this;return o._maxSize=r,o._recordMinMax=n,o}return e.prototype.createAggregator=function(r){return new sy(this._maxSize,this._recordMinMax)},e}(Jr);var bP=function(t){ea(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._resolve=function(r){switch(r.type){case Ie.COUNTER:case Ie.UP_DOWN_COUNTER:case Ie.OBSERVABLE_COUNTER:case Ie.OBSERVABLE_UP_DOWN_COUNTER:return vP;case Ie.GAUGE:case Ie.OBSERVABLE_GAUGE:return RP;case Ie.HISTOGRAM:return r.advice.explicitBucketBoundaries?new xc(r.advice.explicitBucketBoundaries):AP}return K.warn("Unable to recognize instrument type: "+r.type),TP},e.prototype.createAggregator=function(r){return this._resolve(r).createAggregator(r)},e}(Jr);var TP=new gP,vP=new fP,RP=new SP,AP=new yP,dW=new EP,pW=new bP;var wP=function(t){return Jr.Default()},CP=function(t){return Cs.CUMULATIVE};var cy=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},uy=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},xP=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},mW=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},_P=function(){function t(e){var r,n,o;this._shutdown=!1,this._aggregationSelector=(r=e?.aggregationSelector)!==null&&r!==void 0?r:wP,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:CP,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return t.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},t.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},t.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},t.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},t.prototype.onInitialized=function(){},t.prototype.collect=function(e){return cy(this,void 0,void 0,function(){var r,n,o,i,a,s;return uy(this,function(c){switch(c.label){case 0:if(this._sdkMetricProducer===void 0)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");return[4,Promise.all(mW([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],xP(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return r=xP.apply(void 0,[c.sent()]),n=r[0],o=r.slice(1),i=n.errors.concat(ZS(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(ZS(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},t.prototype.shutdown=function(e){return cy(this,void 0,void 0,function(){return uy(this,function(r){switch(r.label){case 0:return this._shutdown?(K.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return r.sent(),[3,4];case 2:return[4,ti(this.onShutdown(),e.timeoutMillis)];case 3:r.sent(),r.label=4;case 4:return this._shutdown=!0,[2]}})})},t.prototype.forceFlush=function(e){return cy(this,void 0,void 0,function(){return uy(this,function(r){switch(r.label){case 0:return this._shutdown?(K.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return r.sent(),[2];case 2:return[4,ti(this.onForceFlush(),e.timeoutMillis)];case 3:return r.sent(),[2]}})})},t}();Je();var hW=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Vp=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},$p=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},gW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},fW=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},dy=function(t){hW(e,t);function e(r){var n,o,i,a,s=t.call(this,{aggregationSelector:(n=r.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(r.exporter),aggregationTemporalitySelector:(o=r.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(r.exporter),metricProducers:r.metricProducers})||this;if(r.exportIntervalMillis!==void 0&&r.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(r.exportTimeoutMillis!==void 0&&r.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(r.exportTimeoutMillis!==void 0&&r.exportIntervalMillis!==void 0&&r.exportIntervalMillis<r.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return s._exportInterval=(i=r.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=r.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=r.exporter,s}return e.prototype._runOnce=function(){return Vp(this,void 0,void 0,function(){var r;return $p(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,ti(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return r=n.sent(),r instanceof QS?(K.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Hp(r),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var r,n;return Vp(this,void 0,void 0,function(){var o,i,a,s,c,l;return $p(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(l=K).error.apply(l,fW(["PeriodicExportingMetricReader: metrics collection errors"],gW(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(r=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(r)];case 3:return u.sent(),[3,5];case 4:return s=u.sent(),K.debug("Error while resolving async portion of resource: ",s),Hp(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,hP._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Cc.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var r=this;this._interval=setInterval(function(){r._runOnce()},this._exportInterval),wc(this._interval)},e.prototype.onForceFlush=function(){return Vp(this,void 0,void 0,function(){return $p(this,function(r){switch(r.label){case 0:return[4,this._runOnce()];case 1:return r.sent(),[4,this._exporter.forceFlush()];case 2:return r.sent(),[2]}})})},e.prototype.onShutdown=function(){return Vp(this,void 0,void 0,function(){return $p(this,function(r){switch(r.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return r.sent(),[4,this._exporter.shutdown()];case 2:return r.sent(),[2]}})})},e}(_P);Je();Je();function Wp(){return"unknown_service:"+process.argv0}var ni=function(){return ni=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},ni.apply(this,arguments)},SW=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},yW=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},EW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},qp=function(){function t(e,r){var n=this,o;this._attributes=e,this.asyncAttributesPending=r!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=r?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return K.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return t.empty=function(){return t.EMPTY},t.default=function(){var e;return new t((e={},e[dP]=Wp(),e[Rc]=Qi[Rc],e[vc]=Qi[vc],e[Ac]=Qi[Ac],e))},Object.defineProperty(t.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&K.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),t.prototype.waitForAsyncAttributes=function(){return SW(this,void 0,void 0,function(){return yW(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},t.prototype.merge=function(e){var r=this,n;if(!e)return this;var o=ni(ni({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new t(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var s,c=EW(a,2),l=c[0],u=c[1];return ni(ni(ni(ni({},r._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new t(o,i)},t.EMPTY=new t({}),t}();var MP=function(){function t(){this._registeredViews=[]}return t.prototype.addView=function(e){this._registeredViews.push(e)},t.prototype.findViews=function(e,r){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,r)});return o},t.prototype._matchInstrument=function(e,r){return(e.getType()===void 0||r.type===e.getType())&&e.getNameFilter().match(r.name)&&e.getUnitFilter().match(r.unit)},t.prototype._matchMeter=function(e,r){return e.getNameFilter().match(r.name)&&(r.version===void 0||e.getVersionFilter().match(r.version))&&(r.schemaUrl===void 0||e.getSchemaUrlFilter().match(r.schemaUrl))},t}();Je();var ta=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Kp=function(){function t(e,r){this._writableMetricStorage=e,this._descriptor=r}return t.prototype._record=function(e,r,n){if(r===void 0&&(r={}),n===void 0&&(n=bs.active()),typeof e!="number"){K.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Pr.INT&&!Number.isInteger(e)&&(K.warn("INT value type cannot accept a floating-point value for "+this._descriptor.name+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,r,n,Zi(Date.now()))},t}();var PP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n,o){this._record(r,n,o)},e}(Kp);var IP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n,o){if(r<0){K.warn("negative value provided to counter "+this._descriptor.name+": "+r);return}this._record(r,n,o)},e}(Kp);var OP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n,o){this._record(r,n,o)},e}(Kp);var LP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n,o){if(r<0){K.warn("negative value provided to histogram "+this._descriptor.name+": "+r);return}this._record(r,n,o)},e}(Kp);var Yp=function(){function t(e,r,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=r}return t.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},t.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},t}();var NP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Yp);var DP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Yp);var kP=function(t){ta(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Yp);function _c(t){return t instanceof Yp}var FP=function(){function t(e){this._meterSharedState=e}return t.prototype.createGauge=function(e,r){var n=Gn(e,Ie.GAUGE,r),o=this._meterSharedState.registerMetricStorage(n);return new OP(o,n)},t.prototype.createHistogram=function(e,r){var n=Gn(e,Ie.HISTOGRAM,r),o=this._meterSharedState.registerMetricStorage(n);return new LP(o,n)},t.prototype.createCounter=function(e,r){var n=Gn(e,Ie.COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new IP(o,n)},t.prototype.createUpDownCounter=function(e,r){var n=Gn(e,Ie.UP_DOWN_COUNTER,r),o=this._meterSharedState.registerMetricStorage(n);return new PP(o,n)},t.prototype.createObservableGauge=function(e,r){var n=Gn(e,Ie.OBSERVABLE_GAUGE,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new DP(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableCounter=function(e,r){var n=Gn(e,Ie.OBSERVABLE_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new NP(n,o,this._meterSharedState.observableRegistry)},t.prototype.createObservableUpDownCounter=function(e,r){var n=Gn(e,Ie.OBSERVABLE_UP_DOWN_COUNTER,r),o=this._meterSharedState.registerAsyncMetricStorage(n);return new kP(n,o,this._meterSharedState.observableRegistry)},t.prototype.addBatchObservableCallback=function(e,r){this._meterSharedState.observableRegistry.addBatchCallback(e,r)},t.prototype.removeBatchObservableCallback=function(e,r){this._meterSharedState.observableRegistry.removeBatchCallback(e,r)},t}();var Xp=function(){function t(e){this._instrumentDescriptor=e}return t.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},t.prototype.updateDescription=function(e){this._instrumentDescriptor=Gn(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},t}();var bW=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),UP=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},TW=function(){function t(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return t.prototype.get=function(e,r){return r??(r=this._hash(e)),this._valueMap.get(r)},t.prototype.getOrDefault=function(e,r){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=r();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},t.prototype.set=function(e,r,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r)},t.prototype.has=function(e,r){return r??(r=this._hash(e)),this._valueMap.has(r)},t.prototype.keys=function(){var e,r;return UP(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),r=e.next(),n.label=1;case 1:return r.done===!0?[3,3]:[4,[r.value[1],r.value[0]]];case 2:return n.sent(),r=e.next(),[3,1];case 3:return[2]}})},t.prototype.entries=function(){var e,r;return UP(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),r=e.next(),n.label=1;case 1:return r.done===!0?[3,3]:[4,[this._keyMap.get(r.value[0]),r.value[1],r.value[0]]];case 2:return n.sent(),r=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(t.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),t}();var fn=function(t){bW(e,t);function e(){return t.call(this,Lp)||this}return e}(TW);var vW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Jp=function(){function t(e,r){this._aggregator=e,this._activeCollectionStorage=new fn,this._cumulativeMemoStorage=new fn,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(r??2e3)-1,this._overflowHashCode=Lp(this._overflowAttributes)}return t.prototype.record=function(e,r,n,o){var i=this,a=this._activeCollectionStorage.get(r);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(r,a)}a?.record(e)},t.prototype.batchCumulate=function(e,r){var n=this;Array.from(e.entries()).forEach(function(o){var i=vW(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(r);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},t.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new fn,e},t}();var py=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},BP=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},Qp=function(){function t(e,r){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,r.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return t.prototype.buildMetrics=function(e,r,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===Cs.CUMULATIVE?a=t.merge(c.accumulations,i,this._aggregator):a=t.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(r.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=RW(a);if(u.length!==0)return this._aggregator.toMetricData(r,s,u,o)},t.prototype._stashAccumulations=function(e){var r,n,o=this._unreportedAccumulations.keys();try{for(var i=py(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype._getMergedUnreportedAccumulations=function(e){var r,n,o=new fn,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=py(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=t.merge(o,c,this._aggregator)}}catch(l){r={error:l}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return o},t.merge=function(e,r,n){for(var o=e,i=r.entries(),a=i.next();a.done!==!0;){var s=BP(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},t.calibrateStartTime=function(e,r,n){var o,i;try{for(var a=py(e.keys()),s=a.next();!s.done;s=a.next()){var c=BP(s.value,2),l=c[0],u=c[1],d=r.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return r},t}();function RW(t){return Array.from(t.entries())}var AW=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),wW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},zP=function(t){AW(e,t);function e(r,n,o,i,a){var s=t.call(this,r)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Jp(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Qp(n,i),s}return e.prototype.record=function(r,n){var o=this,i=new fn;Array.from(r.entries()).forEach(function(a){var s=wW(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(r,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(r,this._instrumentDescriptor,o,n)},e}(Xp);Je();function my(t,e){var r="";return t.unit!==e.unit&&(r+=" - Unit '"+t.unit+"' does not match '"+e.unit+`'
4357
4357
  `),t.type!==e.type&&(r+=" - Type '"+t.type+"' does not match '"+e.type+`'
4358
4358
  `),t.valueType!==e.valueType&&(r+=" - Value Type '"+t.valueType+"' does not match '"+e.valueType+`'
4359
4359
  `),t.description!==e.description&&(r+=" - Description '"+t.description+"' does not match '"+e.description+`'
@@ -4365,22 +4365,22 @@ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Bi(o.url,this.logger)){
4365
4365
  To resolve the conflict:`,hy(l,e))),i=c):K.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
4366
4366
  `,`Details:
4367
4367
  `,my(l,e),`To resolve the conflict:
4368
- `,hy(l,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},t}();var GP=function(){function t(e){this._backingStorages=e}return t.prototype.record=function(e,r,n,o){this._backingStorages.forEach(function(i){i.record(e,r,n,o)})},t}();Xe();Xe();var jP=function(){function t(e,r){this._instrumentName=e,this._valueType=r,this._buffer=new fn}return t.prototype.observe=function(e,r){if(r===void 0&&(r={}),typeof e!="number"){K.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Pr.INT&&!Number.isInteger(e)&&(K.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(r,e)},t}();var VP=function(){function t(){this._buffer=new Map}return t.prototype.observe=function(e,r,n){if(n===void 0&&(n={}),!!_c(e)){var o=this._buffer.get(e);if(o==null&&(o=new fn,this._buffer.set(e,o)),typeof r!="number"){K.warn("non-number value provided to metric "+e._descriptor.name+": "+r);return}e._descriptor.valueType===Pr.INT&&!Number.isInteger(r)&&(K.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),r=Math.trunc(r),!Number.isInteger(r))||o.set(n,r)}},t}();var fy=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},Sy=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},$P=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},WP=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},qP=function(){function t(){this._callbacks=[],this._batchCallbacks=[]}return t.prototype.addCallback=function(e,r){var n=this._findCallback(e,r);n>=0||this._callbacks.push({callback:e,instrument:r})},t.prototype.removeCallback=function(e,r){var n=this._findCallback(e,r);n<0||this._callbacks.splice(n,1)},t.prototype.addBatchCallback=function(e,r){var n=new Set(r.filter(_c));if(n.size===0){K.error("BatchObservableCallback is not associated with valid instruments",r);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},t.prototype.removeBatchCallback=function(e,r){var n=new Set(r.filter(_c)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},t.prototype.observe=function(e,r){return fy(this,void 0,void 0,function(){var n,o,i,a;return Sy(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,r),o=this._observeBatchCallbacks(e,r),[4,$M(WP(WP([],$P(n),!1),$P(o),!1))];case 1:return i=s.sent(),a=i.filter(WM).map(function(c){return c.reason}),[2,a]}})})},t.prototype._observeCallbacks=function(e,r){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return fy(n,void 0,void 0,function(){var s,c;return Sy(this,function(l){switch(l.label){case 0:return s=new jP(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),r!=null&&(c=ti(c,r)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._buffer,e)}),[2]}})})})},t.prototype._observeBatchCallbacks=function(e,r){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return fy(n,void 0,void 0,function(){var s,c;return Sy(this,function(l){switch(l.label){case 0:return s=new VP,c=Promise.resolve(i(s)),r!=null&&(c=ti(c,r)),[4,c];case 1:return l.sent(),a.forEach(function(u){var d=s._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},t.prototype._findCallback=function(e,r){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===r})},t.prototype._findBatchCallback=function(e,r){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&qM(n.instruments,r)})},t}();var PW=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),KP=function(t){PW(e,t);function e(r,n,o,i,a){var s=t.call(this,r)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Jp(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Qp(n,i),s}return e.prototype.record=function(r,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(r,n,o,i)},e.prototype.collect=function(r,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(r,this._instrumentDescriptor,o,n)},e}(Xp);var YP=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Ps=function(){function t(){}return t.Noop=function(){return OW},t}();var IW=function(t){YP(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.process=function(r,n){return r},e}(Ps);var XP=function(t){YP(e,t);function e(r){var n=t.call(this)||this;return n._allowedAttributeNames=r,n}return e.prototype.process=function(r,n){var o=this,i={};return Object.keys(r).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=r[a]}),i},e}(Ps);var OW=new IW;var LW=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},NW=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},DW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},JP=function(){function t(e,r){this._meterProviderSharedState=e,this._instrumentationScope=r,this.metricStorageRegistry=new HP,this.observableRegistry=new qP,this.meter=new FP(this)}return t.prototype.registerMetricStorage=function(e){var r=this._registerMetricStorage(e,KP);return r.length===1?r[0]:new GP(r)},t.prototype.registerAsyncMetricStorage=function(e){var r=this._registerMetricStorage(e,zP);return r},t.prototype.collect=function(e,r,n){return LW(this,void 0,void 0,function(){var o,i,a;return NW(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(r,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,r)}).filter(jM),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},t.prototype._registerMetricStorage=function(e,r){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var l=XM(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),p=new r(l,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),s=a.map(function(c){var l=DW(c,2),u=l[0],d=l[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new r(e,m,Ps.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},t}();var kW=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},QP=function(){function t(e){this.resource=e,this.viewRegistry=new MP,this.metricCollectors=[],this.meterSharedStates=new Map}return t.prototype.getMeterSharedState=function(e){var r=VM(e),n=this.meterSharedStates.get(r);return n==null&&(n=new JP(this,e),this.meterSharedStates.set(r,n)),n},t.prototype.selectAggregations=function(e){var r,n,o=[];try{for(var i=kW(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.selectAggregation(e)])}}catch(c){r={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return o},t}();var Zp=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},em=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},FW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},UW=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},ZP=function(){function t(e,r){this._sharedState=e,this._metricReader=r}return t.prototype.collect=function(e){return Zp(this,void 0,void 0,function(){var r,n,o,i,a=this;return em(this,function(s){switch(s.label){case 0:return r=Zi(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Zp(a,void 0,void 0,function(){var l;return em(this,function(u){switch(u.label){case 0:return[4,c.collect(this,r,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,UW([],FW(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},t.prototype.forceFlush=function(e){return Zp(this,void 0,void 0,function(){return em(this,function(r){switch(r.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return r.sent(),[2]}})})},t.prototype.shutdown=function(e){return Zp(this,void 0,void 0,function(){return em(this,function(r){switch(r.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return r.sent(),[2]}})})},t.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},t.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},t.prototype.selectCardinalityLimit=function(e){var r,n,o;return(o=(n=(r=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(r,e))!==null&&o!==void 0?o:2e3},t}();var eI=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},tI=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},rI=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function BW(t,e){var r=e??qp.empty();return t?qp.default().merge(r):r}var yy=function(){function t(e){var r,n,o,i,a;if(this._shutdown=!1,this._sharedState=new QP(BW((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=rI(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(m){r={error:m}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=rI(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(m){o={error:m}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return t.prototype.getMeter=function(e,r,n){return r===void 0&&(r=""),n===void 0&&(n={}),this._shutdown?(K.warn("A shutdown MeterProvider cannot provide a Meter"),RS()):this._sharedState.getMeterSharedState({name:e,version:r,schemaUrl:n.schemaUrl}).meter},t.prototype.addMetricReader=function(e){var r=new ZP(this._sharedState,e);e.setMetricProducer(r),this._sharedState.metricCollectors.push(r)},t.prototype.shutdown=function(e){return eI(this,void 0,void 0,function(){return tI(this,function(r){switch(r.label){case 0:return this._shutdown?(K.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return r.sent(),[2]}})})},t.prototype.forceFlush=function(e){return eI(this,void 0,void 0,function(){return tI(this,function(r){switch(r.label){case 0:return this._shutdown?(K.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return r.sent(),[2]}})})},t}();var zW=/[\^$\\.+?()[\]{}|]/g,tm=function(){function t(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(t.escapePattern(e)))}return t.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},t.escapePattern=function(e){return"^"+e.replace(zW,"\\$&").replace("*",".*")+"$"},t.hasWildcard=function(e){return e.includes("*")},t}();var Is=function(){function t(e){this._matchAll=e===void 0,this._pattern=e}return t.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},t}();var nI=function(){function t(e){var r;this._nameFilter=new tm((r=e?.name)!==null&&r!==void 0?r:"*"),this._type=e?.type,this._unitFilter=new Is(e?.unit)}return t.prototype.getType=function(){return this._type},t.prototype.getNameFilter=function(){return this._nameFilter},t.prototype.getUnitFilter=function(){return this._unitFilter},t}();var oI=function(){function t(e){this._nameFilter=new Is(e?.name),this._versionFilter=new Is(e?.version),this._schemaUrlFilter=new Is(e?.schemaUrl)}return t.prototype.getNameFilter=function(){return this._nameFilter},t.prototype.getVersionFilter=function(){return this._versionFilter},t.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},t}();function HW(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}var rm=function(){function t(e){var r;if(HW(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||tm.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");e.attributeKeys!=null?this.attributesProcessor=new XP(e.attributeKeys):this.attributesProcessor=Ps.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(r=e.aggregation)!==null&&r!==void 0?r:Jr.Default(),this.instrumentSelector=new nI({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new oI({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return t}();var KFe=process.env.APP||"unknown";Xe();import{v4 as GW}from"uuid";function jW(){return new zM({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:Ji.DELTA})}var VW=[new rm({instrumentName:"test_event_duration",instrumentType:Ie.HISTOGRAM,aggregation:new xc([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new rm({instrumentName:"test_step_duration",instrumentType:Ie.HISTOGRAM,aggregation:new xc([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],nm=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let r=this.counterCache.get(e);if(r)return r;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let r=this.histogramCache.get(e);if(r)return r;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let r=this.observableGaugeCache.get(e);if(r)return r;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let r=typeof process<"u"?"production":"unknown",n=new HS({[Tp]:e.serviceName,[k_]:r,[U_]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:GW()}),o=jW(),i=new dy({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new yy({resource:n,readers:[i],views:VW}),Sp.setGlobalMeterProvider(this.provider),this.meter=Sp.getMeter("momentic-serverless")}increment(e,r,n){try{let o=hp(n,this.globalAttributes);this.getCounter(e).add(typeof r=="number"?r:1,o)}catch{}}gauge(e,r){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,r)}catch{}}distribution(e,r,n){try{let o=hp(n,this.globalAttributes);this.getHistogram(e).record(r,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:r,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(r,Date.now()-o,n)}}};var kt=new mp;function iI(t){t.disabled||(kt=new nm(t))}import{CookieJar as bq}from"tough-cookie";async function aI({codePath:t,screenshotBuff:e,storage:r,logger:n}){if(e)try{let o=await r.uploadScreenshot(e);return n.info({screenshotUrl:o,codePath:t},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:t},"Failed to save screenshot for debugging")}}async function Qr({frameConfig:t,action:e,browser:r}){let n=r.getActiveFrameConfig();t?r.setActiveFrameConfig(t):n?.type==="auto"&&r.setActiveFrameConfig(void 0);try{return await e()}finally{r.setActiveFrameConfig(n)}}var $W=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function sI({beforeUrl:t,beforePages:e,browser:r,command:n,logger:o}){if($W.includes(n.type))return;let s=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),l=0;for(;l===0||Date.now()-c<s;){await le(250),l++;let u=(await r.getOpenPages()).map(p=>p.url),d=r.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Bi(m,o)&&m!==t&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:t},"Auto-following new tab after preset action"),await r.switchToPage({type:"INDEX",index:String(p)});break}}}}async function jn(t,e={}){let r=await t.getBrowserState(e);return{serializedTree:r.serialize(e.serializationOpts),tree:r}}import{randomUUID as JW}from"crypto";var cI={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},uI={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},lI=/<(\S+) id="(\d+)".*?>/g,WW=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,dI=["h1","h2","section","footer","nav","aside","form","label","dialog"],qW=[...dI,"span","div","h3"],KW=["table","select","form","ul","ol","menu","pre","code","dialog"],YW=["table","form","dialog","nav","section","ul","select"];function om(t){return XW(t)}function XW({logger:t,serializedTree:e,options:r}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=r,s=[],c=e.split(`
4368
+ `,hy(l,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},t}();var GP=function(){function t(e){this._backingStorages=e}return t.prototype.record=function(e,r,n,o){this._backingStorages.forEach(function(i){i.record(e,r,n,o)})},t}();Je();Je();var jP=function(){function t(e,r){this._instrumentName=e,this._valueType=r,this._buffer=new fn}return t.prototype.observe=function(e,r){if(r===void 0&&(r={}),typeof e!="number"){K.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Pr.INT&&!Number.isInteger(e)&&(K.warn("INT value type cannot accept a floating-point value for "+this._instrumentName+", ignoring the fractional digits."),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(r,e)},t}();var VP=function(){function t(){this._buffer=new Map}return t.prototype.observe=function(e,r,n){if(n===void 0&&(n={}),!!_c(e)){var o=this._buffer.get(e);if(o==null&&(o=new fn,this._buffer.set(e,o)),typeof r!="number"){K.warn("non-number value provided to metric "+e._descriptor.name+": "+r);return}e._descriptor.valueType===Pr.INT&&!Number.isInteger(r)&&(K.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),r=Math.trunc(r),!Number.isInteger(r))||o.set(n,r)}},t}();var fy=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},Sy=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},$P=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},WP=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},qP=function(){function t(){this._callbacks=[],this._batchCallbacks=[]}return t.prototype.addCallback=function(e,r){var n=this._findCallback(e,r);n>=0||this._callbacks.push({callback:e,instrument:r})},t.prototype.removeCallback=function(e,r){var n=this._findCallback(e,r);n<0||this._callbacks.splice(n,1)},t.prototype.addBatchCallback=function(e,r){var n=new Set(r.filter(_c));if(n.size===0){K.error("BatchObservableCallback is not associated with valid instruments",r);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},t.prototype.removeBatchCallback=function(e,r){var n=new Set(r.filter(_c)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},t.prototype.observe=function(e,r){return fy(this,void 0,void 0,function(){var n,o,i,a;return Sy(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,r),o=this._observeBatchCallbacks(e,r),[4,$M(WP(WP([],$P(n),!1),$P(o),!1))];case 1:return i=s.sent(),a=i.filter(WM).map(function(c){return c.reason}),[2,a]}})})},t.prototype._observeCallbacks=function(e,r){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return fy(n,void 0,void 0,function(){var s,c;return Sy(this,function(l){switch(l.label){case 0:return s=new jP(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),r!=null&&(c=ti(c,r)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._buffer,e)}),[2]}})})})},t.prototype._observeBatchCallbacks=function(e,r){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return fy(n,void 0,void 0,function(){var s,c;return Sy(this,function(l){switch(l.label){case 0:return s=new VP,c=Promise.resolve(i(s)),r!=null&&(c=ti(c,r)),[4,c];case 1:return l.sent(),a.forEach(function(u){var d=s._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},t.prototype._findCallback=function(e,r){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===r})},t.prototype._findBatchCallback=function(e,r){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&qM(n.instruments,r)})},t}();var PW=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),KP=function(t){PW(e,t);function e(r,n,o,i,a){var s=t.call(this,r)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Jp(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new Qp(n,i),s}return e.prototype.record=function(r,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(r,n,o,i)},e.prototype.collect=function(r,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(r,this._instrumentDescriptor,o,n)},e}(Xp);var YP=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(n[i]=o[i])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),Ps=function(){function t(){}return t.Noop=function(){return OW},t}();var IW=function(t){YP(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.process=function(r,n){return r},e}(Ps);var XP=function(t){YP(e,t);function e(r){var n=t.call(this)||this;return n._allowedAttributeNames=r,n}return e.prototype.process=function(r,n){var o=this,i={};return Object.keys(r).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=r[a]}),i},e}(Ps);var OW=new IW;var LW=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},NW=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},DW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},JP=function(){function t(e,r){this._meterProviderSharedState=e,this._instrumentationScope=r,this.metricStorageRegistry=new HP,this.observableRegistry=new qP,this.meter=new FP(this)}return t.prototype.registerMetricStorage=function(e){var r=this._registerMetricStorage(e,KP);return r.length===1?r[0]:new GP(r)},t.prototype.registerAsyncMetricStorage=function(e){var r=this._registerMetricStorage(e,zP);return r},t.prototype.collect=function(e,r,n){return LW(this,void 0,void 0,function(){var o,i,a;return NW(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(r,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,r)}).filter(jM),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},t.prototype._registerMetricStorage=function(e,r){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var l=XM(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),p=new r(l,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),s=a.map(function(c){var l=DW(c,2),u=l[0],d=l[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new r(e,m,Ps.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},t}();var kW=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},QP=function(){function t(e){this.resource=e,this.viewRegistry=new MP,this.metricCollectors=[],this.meterSharedStates=new Map}return t.prototype.getMeterSharedState=function(e){var r=VM(e),n=this.meterSharedStates.get(r);return n==null&&(n=new JP(this,e),this.meterSharedStates.set(r,n)),n},t.prototype.selectAggregations=function(e){var r,n,o=[];try{for(var i=kW(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.selectAggregation(e)])}}catch(c){r={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return o},t}();var Zp=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},em=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},FW=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return i},UW=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},ZP=function(){function t(e,r){this._sharedState=e,this._metricReader=r}return t.prototype.collect=function(e){return Zp(this,void 0,void 0,function(){var r,n,o,i,a=this;return em(this,function(s){switch(s.label){case 0:return r=Zi(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Zp(a,void 0,void 0,function(){var l;return em(this,function(u){switch(u.label){case 0:return[4,c.collect(this,r,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,UW([],FW(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},t.prototype.forceFlush=function(e){return Zp(this,void 0,void 0,function(){return em(this,function(r){switch(r.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return r.sent(),[2]}})})},t.prototype.shutdown=function(e){return Zp(this,void 0,void 0,function(){return em(this,function(r){switch(r.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return r.sent(),[2]}})})},t.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},t.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},t.prototype.selectCardinalityLimit=function(e){var r,n,o;return(o=(n=(r=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(r,e))!==null&&o!==void 0?o:2e3},t}();var eI=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},tI=function(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,o=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){r.label=l[1];break}if(l[0]===6&&r.label<i[1]){r.label=i[1],i=l;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(l);break}i[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},rI=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function BW(t,e){var r=e??qp.empty();return t?qp.default().merge(r):r}var yy=function(){function t(e){var r,n,o,i,a;if(this._shutdown=!1,this._sharedState=new QP(BW((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=rI(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(m){r={error:m}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=rI(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}catch(m){o={error:m}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}}return t.prototype.getMeter=function(e,r,n){return r===void 0&&(r=""),n===void 0&&(n={}),this._shutdown?(K.warn("A shutdown MeterProvider cannot provide a Meter"),RS()):this._sharedState.getMeterSharedState({name:e,version:r,schemaUrl:n.schemaUrl}).meter},t.prototype.addMetricReader=function(e){var r=new ZP(this._sharedState,e);e.setMetricProducer(r),this._sharedState.metricCollectors.push(r)},t.prototype.shutdown=function(e){return eI(this,void 0,void 0,function(){return tI(this,function(r){switch(r.label){case 0:return this._shutdown?(K.warn("shutdown may only be called once per MeterProvider"),[2]):(this._shutdown=!0,[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.shutdown(e)}))]);case 1:return r.sent(),[2]}})})},t.prototype.forceFlush=function(e){return eI(this,void 0,void 0,function(){return tI(this,function(r){switch(r.label){case 0:return this._shutdown?(K.warn("invalid attempt to force flush after MeterProvider shutdown"),[2]):[4,Promise.all(this._sharedState.metricCollectors.map(function(n){return n.forceFlush(e)}))];case 1:return r.sent(),[2]}})})},t}();var zW=/[\^$\\.+?()[\]{}|]/g,tm=function(){function t(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(t.escapePattern(e)))}return t.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},t.escapePattern=function(e){return"^"+e.replace(zW,"\\$&").replace("*",".*")+"$"},t.hasWildcard=function(e){return e.includes("*")},t}();var Is=function(){function t(e){this._matchAll=e===void 0,this._pattern=e}return t.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},t}();var nI=function(){function t(e){var r;this._nameFilter=new tm((r=e?.name)!==null&&r!==void 0?r:"*"),this._type=e?.type,this._unitFilter=new Is(e?.unit)}return t.prototype.getType=function(){return this._type},t.prototype.getNameFilter=function(){return this._nameFilter},t.prototype.getUnitFilter=function(){return this._unitFilter},t}();var oI=function(){function t(e){this._nameFilter=new Is(e?.name),this._versionFilter=new Is(e?.version),this._schemaUrlFilter=new Is(e?.schemaUrl)}return t.prototype.getNameFilter=function(){return this._nameFilter},t.prototype.getVersionFilter=function(){return this._versionFilter},t.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},t}();function HW(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}var rm=function(){function t(e){var r;if(HW(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||tm.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.");e.attributeKeys!=null?this.attributesProcessor=new XP(e.attributeKeys):this.attributesProcessor=Ps.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(r=e.aggregation)!==null&&r!==void 0?r:Jr.Default(),this.instrumentSelector=new nI({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new oI({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return t}();var KFe=process.env.APP||"unknown";Je();import{v4 as GW}from"uuid";function jW(){return new zM({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:Ji.DELTA})}var VW=[new rm({instrumentName:"test_event_duration",instrumentType:Ie.HISTOGRAM,aggregation:new xc([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new rm({instrumentName:"test_step_duration",instrumentType:Ie.HISTOGRAM,aggregation:new xc([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],nm=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let r=this.counterCache.get(e);if(r)return r;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let r=this.histogramCache.get(e);if(r)return r;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let r=this.observableGaugeCache.get(e);if(r)return r;let n=this.meter.createObservableGauge(e);return n.addCallback(o=>{let i=this.gaugeValues.get(e);i!==void 0&&o.observe(i,this.globalAttributes)}),this.observableGaugeCache.set(e,n),n}constructor(e){this.globalAttributes={...e.globalAttributes??{}};let r=typeof process<"u"?"production":"unknown",n=new HS({[Tp]:e.serviceName,[k_]:r,[U_]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:GW()}),o=jW(),i=new dy({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new yy({resource:n,readers:[i],views:VW}),Sp.setGlobalMeterProvider(this.provider),this.meter=Sp.getMeter("momentic-serverless")}increment(e,r,n){try{let o=hp(n,this.globalAttributes);this.getCounter(e).add(typeof r=="number"?r:1,o)}catch{}}gauge(e,r){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,r)}catch{}}distribution(e,r,n){try{let o=hp(n,this.globalAttributes);this.getHistogram(e).record(r,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:r,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(r,Date.now()-o,n)}}};var kt=new mp;function iI(t){t.disabled||(kt=new nm(t))}import{CookieJar as bq}from"tough-cookie";async function aI({codePath:t,screenshotBuff:e,storage:r,logger:n}){if(e)try{let o=await r.uploadScreenshot(e);return n.info({screenshotUrl:o,codePath:t},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:t},"Failed to save screenshot for debugging")}}async function Qr({frameConfig:t,action:e,browser:r}){let n=r.getActiveFrameConfig();t?r.setActiveFrameConfig(t):n?.type==="auto"&&r.setActiveFrameConfig(void 0);try{return await e()}finally{r.setActiveFrameConfig(n)}}var $W=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function sI({beforeUrl:t,beforePages:e,browser:r,command:n,logger:o}){if($W.includes(n.type))return;let s=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),l=0;for(;l===0||Date.now()-c<s;){await le(250),l++;let u=(await r.getOpenPages()).map(p=>p.url),d=r.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Bi(m,o)&&m!==t&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:t},"Auto-following new tab after preset action"),await r.switchToPage({type:"INDEX",index:String(p)});break}}}}async function jn(t,e={}){let r=await t.getBrowserState(e);return{serializedTree:r.serialize(e.serializationOpts),tree:r}}import{randomUUID as JW}from"crypto";var cI={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},uI={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},lI=/<(\S+) id="(\d+)".*?>/g,WW=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,dI=["h1","h2","section","footer","nav","aside","form","label","dialog"],qW=[...dI,"span","div","h3"],KW=["table","select","form","ul","ol","menu","pre","code","dialog"],YW=["table","form","dialog","nav","section","ul","select"];function om(t){return XW(t)}function XW({logger:t,serializedTree:e,options:r}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=r,s=[],c=e.split(`
4369
4369
  `),l=0,u=[],d=0,p=[],m=[],g=!1;for(;l<c.length;){g&&(s.push({ids:p,content:u.join(`
4370
4370
  `),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[l],f=Pe(h);d+=f,h.length>a&&(h=h.slice(0,a));let E=Array.from(h.matchAll(lI)).map(W=>W&&W.length>=3?{tagName:W[1],id:W[2]}:void 0).filter(W=>!!W),v=Array.from(h.matchAll(WW)).map(W=>W&&(W[2]||W[4])).filter(W=>!!W);v.reverse();let w=h.replace(/ id="[0-9]+"/g,"");u.push(w);for(let W of E)p.push(W.id),m.push(W);for(let W of v){let q=m[m.length-1];q&&q.tagName===W&&m.pop()}let C=m.some(W=>KW.includes(W.tagName)),_=c[l+1]??"",N=Pe(_),j=Array.from(_.matchAll(lI)).map(W=>W&&W.length>2?W[1]:void 0).filter(W=>!!W),O=j.some(W=>dI.includes(W)),B=j.some(W=>qW.includes(W));d+N>=i&&(g=!0),d>=n&&(O&&!C||v.some(W=>YW.includes(W)))&&(g=!0),d>=o&&B&&!C&&(g=!0),l++}return u.length&&s.push({ids:p,content:u.join(`
4371
4371
  `),tokenLength:d}),s.forEach((h,f)=>{let S=h.ids[0],y=h.ids[h.ids.length-1];t.debug({tokenLength:h.tokenLength,minId:S,maxId:y},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var QW=75e4,im=3e5;async function ra(t){let{options:e,fixtures:r,screenshot:n}=t,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:c}=r,l=t.tree,u=t.serializedTree,d=Pe(u);if(d>QW)try{let p=om({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await eq({...t,tokenLimit:im-1e4,chunks:p.chunks}),u=l.serialize();let m=Pe(u);i.info({oldTokens:d,newTokens:m},"Filtered page using keywords"),d=m}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(im*Bo),u=l.serialize();let m=Pe(u);i.info({oldTokens:d,newTokens:m},"Filtered page using naive truncation"),d=m}if(d>im)try{if(o){let p=om({serializedTree:u,options:uI,logger:i}),m=JW();l=await $(ZW({...t,chunks:p.chunks,callId:m}),{milliseconds:12e3,signal:c}),u=l.serialize();let g=Pe(u);i.info({oldTokens:d,newTokens:g,langfuseCallId:m},"Filtered page using AI chunk ranking"),d=g}else{let p=om({serializedTree:u,options:cI,logger:i});l=await $(tq({...t,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let m=Pe(u);i.info({oldTokens:d,newTokens:m},"Filtered page using RAG"),d=m}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(im*Bo),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function ZW({type:t,callId:e,chunks:r,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:c}=o,l=await a.rankChunksWithAi({chunks:r,description:n,type:t,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:c,loggerTags:je(c)}),u=[];return r.forEach((p,m)=>{l.indices.includes(m)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function eq(t){let{description:e,fixtures:r,tree:n}=t,{generator:o,logger:i,signal:a}=r;if(!e.trim())throw new Error("Empty description passed to page filtering");let s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:je(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=t.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((m,g)=>m+g.tokenLength,0)>t.tokenLimit&&l.length>1)continue;let d=l.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function tq(t){let{description:e,fixtures:r,chunkResult:n,tokenLimit:o,tree:i}=t,{generator:a,logger:s,signal:c}=r,l=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:s,loggerTags:je(s)});if(l.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`)))}async function by(t,e){if(!t.description)throw new M("UserConfigurationError","Cannot locate element with empty description");return Qr({action:async()=>rq(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function rq(t,e){let{disableCache:r,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:c,logger:l,allowNotActionableNodesOverride:u}=t,{ctx:d,orgId:p,browser:m,localCodeEvalTools:g,generator:h,abortSignal:f}=e,S=t.description,y=t.useMemory&&!r;n&&(S=await pr({orgId:p,s:S,context:n,localTools:g,signal:f,logger:l})),a&&(S=oq(S,a));let{serializedTree:E,tree:T}=await jn(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),v,w=Date.now(),C;for(;!v&&Date.now()-w<3e3;){f.throwIfAborted();try{v=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Y){C=Y}}if(!v)throw new M("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${C?.message}`);let _=E,N=!1,j=`data:image/jpeg;base64,${v.toString("base64")}`;_=await ra({type:"locator",description:S,screenshot:j,serializedTree:E,options:{aiPageFiltering:c},tree:T,fixtures:{generator:h,signal:f,logger:l,orgId:p}}),_!==E&&(N=!0);let O=await h.getElementLocation({browserState:_,goal:S,screenshot:j,source:a,memory:y?s:void 0},{disableCache:r,abortSignal:f,loggerTags:je(l),useMemory:y});if(l.debug({usedRag:N,result:O},"Got locator result"),!(O.id>0))throw new Ia(`Could not find any relevant element: ${O.thoughts}`,O.updatedMemory?{type:"GCS_TRACES",traces:O.updatedMemory}:void 0);let{resolution:W,target:q,frameConfig:ve}=await m.createTargetFromA11yId({id:O.id,requirements:O.requirements,additionalElements:O.additionalElements,description:S,targetSource:"AI",logger:l});if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new M("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${W.displayString}`);return y&&(O.updatedMemory?q.memory={type:"GCS_TRACES",traces:O.updatedMemory}:s&&(q.memory=s)),{thoughts:O.thoughts,target:q,resolution:W,frameConfig:ve,screenshot:j}}var nq=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],pI="<select> element:",mI="text input or contenteditable element:",hI="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",gI="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",Ey=[pI,mI,hI,gI,...nq];function fI(t,e){if(t===e)return!0;for(let r of Ey){if(!t.startsWith(r))continue;let n=t.slice(r.length).trim();if(Ey.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Ey.some(r=>e.startsWith(r)&&e.slice(r.length).trim()===t.trim())}function oq(t,e){if(!t||!e)return t;switch(e){case"SELECT_OPTION":return`${pI} ${t}`;case"TYPE":return`${mI} ${t}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${hI}
4372
4372
  ${t}`;case"ELEMENT_CHECK":return`${gI}
4373
- ${t}`;default:return t}}var iq=15;async function am({command:t,aiPageFiltering:e,logger:r,fixtures:n,source:o,useMemory:i,maxRetries:a=iq}){if(!t.assertion.trim())throw new M("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=t.timeout?t.timeout*1e3:s.smartWaitingTimeout,l=Dw(c),u=0,d=Date.now(),p,m,g;try{await Qr({action:()=>s.clearHighlights(),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:s,logger:r})}catch(f){r.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await le(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await Qr({action:async()=>{let y=await SI(s,r,n.abortSignal);return m&&m.serializedTree===y.serializedTree&&m.screenshotBuff.equals(y.screenshotBuff)?(f=!0,p):(m=y,yI({command:t,state:y,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:r,source:o}))},frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:r,browser:s}),p?.success){p?.updatedMemory&&Vl(t,p.updatedMemory,r);break}else throw p?.thoughts?new M("AssertionFailureError",p.thoughts):new M("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(S){n.abortSignal.throwIfAborted(),g=S instanceof Error?S:new Error(`${S}`),f?r.info(`AI check attempt ${u} failed (re-used previous result)`):r.info({err:S},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await Qr({action:async()=>yI({command:t,state:await SI(s,r,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:r}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:r,browser:s})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(p?.updatedMemory&&Vl(t,p.updatedMemory,r),!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new M("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function SI(t,e,r){let[n,o]=await Promise.all([jn(t,{abortSignal:r,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function yI({command:t,state:e,fixtures:r,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=r,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,S=f.toString("base64"),y=u.url(),E=t.contextChoice??"MULTIMODAL",T=g;E!=="VISION_ONLY"&&(T=await ra({type:"assertion",serializedTree:g,tree:h,description:t.assertion,screenshot:S,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:r.orgId}}),T!==g&&(m.ragUsed=!0),m.pageState=T);let v={goal:t.assertion,url:y,memory:o?t.cache?.memory:void 0,browserState:T,screenshot:S,contextChoice:E,source:c},C=await(E==="VISION_ONLY"?(_,N)=>d.getVisualAssertionResult(_,N):(_,N)=>d.getAssertionResult(_,N))(v,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!t.disableCache,abortSignal:p,logger:l,loggerTags:je(l)});return(C.result||i)&&C.relevantElements&&(m.relevantElementsSerialized=C.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_),await aq(C.relevantElements,u,l)),{success:C.result,thoughts:C.thoughts,afterScreenshotOverride:f,updatedMemory:o?C.updatedMemory:void 0}}async function aq(t,e,r){let n=Date.now();for(let o of t){if(Date.now()-n>2e3){r.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await $(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){r.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var sq=75e4,sm=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function EI(t,e){let{logger:r}=t,{abortSignal:n,browser:o}=e,i=Date.now();try{await lq(i,t,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof sm?r.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):r.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await le(s,n)}finally{r.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function lq(t,e,r){let{abortSignal:n,browser:o}=r;if(o.smartWaitingTimeout<3e3){await le(o.smartWaitingTimeout,n);return}if(!e.description)throw new M("UserConfigurationError","Cannot locate element with empty description");await $(cq(t,e,r),{milliseconds:o.smartWaitingTimeout})}async function cq(t,e,r){let{logger:n,iframeUrl:o}=e,{browser:i}=r;for(;Date.now()-t<i.smartWaitingTimeout;)if(await Qr({action:async()=>uq(e,r),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function uq(t,e){let{testContext:r,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=t,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=t.description;r&&(d=await pr({orgId:l,s:d,context:r,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await jn(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Pe(p)>sq)throw new sm;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(y){throw new M("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${y instanceof Error?y.message:y}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;s.throwIfAborted();let S=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:je(n)});return n.debug({result:S},"Got smart waiting result"),S.isPageReady}import{cloneDeep as TI}from"lodash-es";async function vI(t){let{command:e,timeoutMs:r,fixtures:n}=t,{abortSignal:o}=n,i=()=>LE(e.cache)?e.cache:void 0,a=i(),s=TI(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=rf(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,p=500,m=!1;for(;u<2||Date.now()-l<r;){u++,u>1&&await le(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await bI({cacheToUse:a,params:t});if(d=h,m=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new M("InternalPlatformError",`Failed to evaluate manual element assertion in ${r}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&ru(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await bI({cacheToUse:h,params:t});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!m&&(g.target=jl(g.target),g.updatedAt=new Date),d}async function bI({cacheToUse:t,params:e}){let{command:r,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(r.target&&!Ao(r.target))throw new Error("Element assertion with x/y is not supported yet");let c=LA(r.assertion),l,u=!1,d=TI(t);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:r,target:r.target,cache:d?.target,action:async h=>dq(h.locator,e),options:{...r,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Ri(r),targetName:"target"}});return l={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(s.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),l={...m,thoughts:g}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof M)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function dq(t,{command:e,fixtures:r}){return await r.browser.highlight(t),await pq(t,e.assertion)}async function pq(t,e){let r=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await t.textContent()??"";if(o={elementTextContent:tt(a,500,!0)},!Gl(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=es(e);r=!1,n=new M("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:tt(await t.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await t.getAttribute(e.attr,{timeout:3e3})??""}catch(s){n=new M("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),r=!1;break}if(!Gl(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=es(e);r=!1,e.operation==="EXISTS"?n=new M("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new M("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{r=await t.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Tn*1e3);break}case"EDITABLE":{r=await t.isEditable({timeout:Tn*1e3});break}case"EXISTS":{r=!0;break}case"ENABLED":{r=await t.isEnabled({timeout:Tn*1e3});break}case"FOCUSED":{r=await t.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.condition)}if(r=e.negated?!r:r,!r){let a=es(e);n=new M("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await t.evaluate(s=>s.tagName);if(!Gl(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=es(e);r=!1,n=new M("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await t.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!Gl(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=es(e);r=!1,e.operation==="EXISTS"?n=new M("AssertionFailureError",`The style property ${e.property} ${s}`):n=new M("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:r,data:o,err:n}}function RI(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as mq}from"jimp";async function Pc(t,e){let r=await t.screenshot(e),n=await mq.fromBuffer(r);return{buffer:r,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as AI}from"jimp";import Ty from"jpeg-js";import hq from"pixelmatch";async function wI({ctx:t,tracer:e,command:r,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(r.target&&!Ao(r.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},l;r.target?.elementDescriptor?l=(await i({ctx:t,tracer:e,command:r,target:r.target,cache:r.cache?.target,action:async j=>Pc(o,{locator:j.locator,...c}),options:{...r,disableCache:n,disableGlobalLocatorRedirect:!0,memory:r.cache?.target?.memory,targetName:"target"}})).result:l=await Pc(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,r,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let U=`${l.width}x${l.height}`,j=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${U}) does not match saved screenshot dimensions (${j}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await AI.fromBuffer(l.buffer),p={width:l.width,height:l.height},m=await AI.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,S=g.width*g.height,y=Math.abs(p.height-g.height),E=Math.abs(p.width-g.width);if(f>S){let U=d.cover({w:g.width,h:g.height});l.buffer=await U.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(S>f){let U=m.cover({w:p.width,h:p.height});u.buffer=await U.getBuffer("image/jpeg"),h="saved"}let T={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=r.threshold??.1,C=hq(Ty.decode(u.buffer).data,Ty.decode(l.buffer).data,T.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,_=C>v*100,N=`Visual diff of ${C.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${v*100}%.`;if(h&&(N+=` The ${h} screenshot was cropped since it was taller by ${y} pixels and wider by ${E} pixels.`),_)throw new M("ActionFailureError",N);return{fail:_,thoughts:N,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Ty.encode(T,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var gq=3e4;function fq(t){if(!t.body)return{};switch(t.body.type){case"json":return{content:t.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(t.body.content).forEach(([r,n])=>{e.append(r,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function CI({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??gq/1e3,i=Object.fromEntries(Object.entries(t.headers||{}).filter(([g,h])=>g&&h)),a=new URLSearchParams;Object.entries(t.params||{}).filter(([g,h])=>g&&h).forEach(([g,h])=>{a.append(g,h)});let s=a.toString(),c;if(as(t.url)&&(c=t.url),r&&ss(t.url,r)&&(c=new URL(t.url,r).toString()),!c)throw new M("ActionFailureError",`Invalid URL: ${t.url}`);let l=c;e.info({url:l,searchParams:s,headers:i,body:t.body,method:t.method},"Making HTTP request");let d=await $((async()=>{let g=s?`${l}?${s}`:l;try{let h=fq(t),f=new Headers(i);return h.contentType&&!f.has("Content-Type")&&f.set("Content-Type",h.contentType),await n(g,{headers:f,method:t.method,body:h.content})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new M("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let g;try{g=await d.text()}catch(h){g=`Failed to read response body: ${h}`}throw new M("ActionFailureError",`Fetch request failed with status ${d.status}: ${g}`)}let p={};d.headers.forEach((g,h)=>{p[h]=g});let m={status:d.status,headers:p,request:{url:d.url,method:t.method,headers:i}};if(t.body?.type==="json"&&t.body.content)try{m.request.json=JSON.parse(t.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{m.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(m.text=await d.text());return m}var Sq=5e3;async function lm({timeout:t=Tn,...e}){let r=Date.now(),n=t*1e3,o=n+1e4,i,a=0,s=500;for(;a-r<n;){if(Date.now()-r>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal?.throwIfAborted();let c=Date.now();i=await xI(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await le(s,e.signal),s=Math.min(Math.floor(s*1.5),Sq);else return i}return i=await xI(e),i}async function xI({assertion:t,browser:e,autoExpandIframes:r}){switch(t.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(r){let c=await e.evaluateFunctionInAllFrames(_I,{value:t.value,negated:!!t.negated,returnHtml:!1});i=t.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(_I,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!i){let c=t.negated?oo.CONTAINS:io.CONTAINS;a=new M("AssertionFailureError",`The page ${c} '${t.value}'.`),o=s}}catch(s){a=new M("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function _I({value:t,negated:e,returnHtml:r}){let n=document.documentElement.outerHTML,o=n.includes(t)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&r?n:void 0}}var yq=3e4;async function MI({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??yq/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(as(t.url)&&(s=t.url),r&&ss(t.url,r)&&(s=new URL(t.url,r).toString()),!s)throw new M("ActionFailureError",`Invalid URL: ${t.url}`);let l=await $((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:t.query,variables:t.variables?JSON.parse(t.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!l)throw new M("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new M("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new M("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new M("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var oi=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:r,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=r,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:r,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([jn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await ra({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:r,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...je(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:r,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([jn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await ra({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:r,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...je(a)},langfuseSessionId:s})}catch(g){throw new M("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return jn(this.browser,e)}async locateElement(e){return await by({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,r){return Qr({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:r?{type:"url",url:r}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:r,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await s(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:r,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new M("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let r=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await Qr({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:r})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Sh(i)){r.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(bh(i)||yh(i))){r.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Th(i)){r.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Rn&&i.retryableWithAI){r.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof M?n:new M("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:r,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(r.type!=="description")throw new M("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:r.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await le(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:r,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,S=!1,y=PI(e.cache);if((!y||l)&&!ih(o))throw new M("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),S=!0,y=void 0),y&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&y.targetSource==="HEURISTIC_HEALED"&&(S=!0,y=void 0),y?.inputDescription&&!fI(o.elementDescriptor,y.inputDescription)&&(g.warn({old:y.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),S=!0,y=void 0);let E=v=>!!v&&ru(v),T=!0;if(!E(y)){T=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:S,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(S||!i)&&await EI({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:m,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(r)),f--;let v;try{v=await by({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:m,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(r))}catch(_){if(_ instanceof Ia&&_.updatedLocatorMemory){let N={id:-1,...i,memory:_.updatedLocatorMemory};vd({cmd:c,key:d,newTarget:N,logger:g,updatedWithAI:!0})}throw new M("ActionFailureError",_.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let w=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),C=await a(w);return vd({cmd:c,key:d,newTarget:v.target,logger:g,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=je(g)),{result:C,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(r,y,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let w=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),C=await a(w);if(kt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!y.requirements}`,`hasAdditionalElements:${!!y.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.29.4"]),vd({cmd:c,key:d,newTarget:y,logger:g,updatedWithAI:!1}),T){let _=v.decisions.filter(N=>N.matched);if(_.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let N=_[0].type;n.recordTargetAutoHeal({healType:N})}}return{result:C,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let w="unknown";v instanceof kr&&v.cacheMissReason&&(w=v.cacheMissReason),kt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!y.requirements}`,`hasAdditionalElements:${!!y.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.29.4",`missReason:${w}`]);let C=!1;if((v instanceof Rn||Sh(v)||bh(v)||Th(v)||zb(v)||yh(v)||Hb(v))&&(C=!0),v instanceof M&&!C)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let _;return y.memory&&nu(y.memory)&&(_=y.memory),this.wrapElementTargetingCommand({ctx:r,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:_,retriesWithAI:f,targetHealingInProgress:!0}})}throw new M("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,r){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,r):{locator:e}}async screenshotWithDimensions(e){return Pc(this.browser,e)}async executePresetCommand(e,r,n,o,i){this.options?.slowMoMs&&await le(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new M("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,r,n,o,i);return this.browser.userBrowserSettings.visualActions&&rb(n)?await this.browser.waitForDOMStability({timeout:Ne}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:de}),this.options?.autoFollowNewTabs&&await sI({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{xC(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Hf(e)}}async resolveCommandTemplateStrings(e,r){return Xd({obj:e,context:r,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,r,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let s=n.condition;return s?.assertion.trim()?am({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new M("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new M("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return am({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new M("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let h=iA(n.schema);if(h)throw new M("UserConfigurationError",h)}let m=await this.browser.getCondensedHtml(),g=await this.browser.screenshot({retries:2});try{let h=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${g.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:je(a)});if(h.result==="NOT_FOUND")throw new M("ActionFailureError","No relevant data found for extraction goal on this page");if(h.thoughts?.includes("MaxGenerationLengthExceededError"))throw new M("UserConfigurationError",h.thoughts);return{thoughts:h.thoughts||void 0,data:h.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(h){let f=h.message;throw f.includes("MaxGenerationLengthExceededError")?new M("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):f.includes("AIProviderError")&&f.includes("time")?new M("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:h}}):h}}case"NAVIGATE":if(!as(n.url)&&!ss(n.url,this.browser.baseUrl))throw new M("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":throw new M("UserConfigurationError","Captcha solving is no longer available on Momentic");case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let m,g;if(n.target&&bn(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:S,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:n.target,cache:n.cache?.target,action:E=>this.browser.hover(E),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=S,g=y}let h=this.browser.getViewport()?.height??Kt.height,f=this.browser.getViewport()?.width??Kt.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??h));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??h);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??f));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??f);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:g}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new M("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new M("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let c=n.delay*1e3;await le(c,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(bn(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=this.browser.url(),{elementInteractedDisplayString:g,result:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,target:n.target,command:n,cache:n.cache?.target,action:y=>this.browser.click(y,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:f,data:h.downloadedFile?{downloadedFile:h.downloadedFile}:void 0};return Dd(m,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(bn(n.fromTarget)&&bn(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0});break}if(bn(n.fromTarget)||bn(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,thoughts:g}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:r,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(h,f)=>this.browser.dragAndDrop(h.locator,f.locator,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m[0],thoughts:g}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),g=parseInt(n.deltaY),h=n.steps??5;if(isNaN(m)||isNaN(g))throw new M("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&bn(n.target)){await this.browser.mouseDragUsingVisualCoordinates({deltaX:m,deltaY:g,steps:h,fromTarget:n.target.pixels});break}let f,S;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:y,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:n.target,cache:n.cache?.target,action:async T=>this.browser.mouseDrag(m,g,h,T.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});f=y,S=E}else await this.browser.mouseDrag(m,g,h,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:S}}case"SELECT_OPTION":{if(!Ao(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,g=n.choice,{elementInteractedDisplayString:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:S=>this.browser.selectOption(S,g,n.force),options:{...n,targetName:"target",disableCache:i,source:Ri(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,thoughts:f}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let l=await this.browser.setCookie(n.value);a.debug({results:l},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let m;try{n.environment==="BROWSER"?(m=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:m},"Executed JavaScript in browser")):m=await qo({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async g=>{if(!this.options?.scratchPadId){a.warn({updates:g},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:g,logger:a})}}})}catch(g){throw this.throwIfClosed(),new M("ActionFailureError",g instanceof Error?g.message:`${g}`,{errOptions:{cause:g}})}try{JSON.stringify(m)}catch(g){throw new M("ActionFailureError",`Return value is not serializable: ${g instanceof Error?g.message:`${g}`}`,{errOptions:{cause:g}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&bn(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let m=this.browser.url(),g,h,f=PI(n.target),S=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(f){let{elementInteractedDisplayString:E,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:f,cache:n.cache?.target,action:v=>this.browser.typeIntoTarget(n.value,v,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!S,source:Ri(n)}});g=E,h=T}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let y={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:h};return Dd(m,y.urlAfterCommand)&&(y.succeedImmediately=!0,y.succeedImmediatelyReason="URL changed"),y}case"HOVER":{if(bn(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:n.target,cache:n.cache?.target,action:h=>this.browser.hover(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:g}}case"FOCUS":{if(!Ao(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:n.target,cache:n.cache?.target,action:h=>this.browser.focus(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:g}}case"BLUR":{if(n.target&&!Ao(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:m,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,target:n.target,command:n,cache:n.cache?.target,action:h=>this.browser.blur(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:g}}case"PRESS":let u=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Dd(u,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let m=new bq,g=Eq(fetch,m),h;try{h=new URL(n.url).hostname}catch{}let f=await CI({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:g});return{data:al.parse({...f,cookies:Lv(m,h)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await MI({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return wI({ctx:e,tracer:r,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,g;if(n.fileSource.type==="URL"?(g=n.fileSource.url,m=await UC({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(g=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new M("UserConfigurationError",`Attempted to use non-existent file for upload step: ${g}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await qo({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new M("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let g;try{g=Qu.optional().parse(m)}catch(h){throw new M("ActionFailureError",`Credentials provided do not follow the required format: ${h}`)}await this.browser.loadAuthState(g);break}case"ELEMENT_CHECK":{let m=(n.timeout??Tn)*1e3,g=this.generator.getAgentConfig()?.assertion;if(RI(n.assertion)&&!n.useSelector&&n.target.type==="description"&&g&&g!=="v1"){let f={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let S=await am({command:f,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${S.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:S.afterScreenshotOverride}}finally{f.cache?.memory&&Vl(n,f.cache?.memory.traces,a)}}let h=await vI({command:n,tracer:r,timeoutMs:m,targetingWrapper:f=>this.wrapElementTargetingCommand(f),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!h.success,data:h.data,elementInteracted:h.elementInteractedDisplayString,thoughts:h.err?.message??h.thoughts??`Element assertion ${h.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let m=await Qr({action:async()=>lm({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new Yo(n.requestMatcher),g=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=g.then(async h=>await Wf(h)).catch(h=>{a.error({err:h},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new M("ActionFailureError",`No listener registered with key: ${n.key}`);let g=n.timeout??10;return{data:await $(m,{milliseconds:g*1e3,message:`Request listener timed out after ${g} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new Yo(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:g=>m.matches({url:g.request.url,method:g.request.method}),onRequestStart:(g,h)=>{this.recordedRequests[n.key][g]=tp(h)},onRequestComplete:(g,h)=>{this.recordedRequests[n.key]?.[g]&&(this.recordedRequests[n.key][g]=tp(h))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new M("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new Yo(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Yo(n.requestMatcher),async(g,h)=>{let f=await qo({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:g,response:h},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),S=Nv.parse(f);return new Response(S.body,{status:S.status,headers:S.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:r,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:r,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:je(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:r,isClickToRecord:n}){this.recordAbortController=r;let o=new sp({signal:r.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:je(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:je(this.logger)})}};var vy=async t=>{let{step:e,resolvedInputs:r}=t.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:s}=t.fixtures,c=s.browser,{orgId:l,runId:u}=t.inputs,d=s.executeAbortController.signal;Object.keys(r).length>0&&(o.setInputs(r),n.info(is({json:{inputs:r,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=!1,g,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await pr({orgId:l,s:f,context:o,logger:n,localTools:a,signal:d});h={orgId:l,cacheKeys:[S,...Object.entries(r).map(([E,T])=>`${E}:${T}`)]},n.info({original:f,keyParams:h},"Module cache key params");let y=Date.now();for(;Date.now()-y<aR;){d?.throwIfAborted();let E=await i.getCacheResult(h);if(E){n.info({cacheResult:tt(E,1e3,!0)},"Got result from module execution cache"),p=cm(e,r,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(E),m=!0;break}else n.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let T=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${Tq()};runId:${u}`},d);if(T.acquired){g=T.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await le(2500+Math.random()*1e4,d)}}try{if(!p)p=await vq(t);else if(e.autoAuth){let f=Qu.safeParse(p.data);if(!f.success)throw new M("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);n.debug("Automatically loading auth state after cached module result"),await c.loadAuthState(f.data);let S=!1,y=e.advanced?.cacheInvalidation;if(y&&y.type==="PAGE_CHECK"){let E={type:"CONTENT",value:y.substring},T=await lm({timeout:Tn,assertion:E,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});T.success?n.debug({invalResult:T},"Cached result still valid after page check, continuing..."):(n.info({invalResult:T},"Invalidating cached result due to page check failure"),S=!0)}if(h&&S)return await i.deleteCacheResult(h),vy(t)}}finally{try{g!==void 0&&!m&&p?.status==="SUCCESS"&&await Rq({step:e,result:p,browser:s.browser,cacheKeyPrefix:g,logger:n,storage:i})}finally{g!==void 0&&await i.releaseCacheLock(g)}}return p},vq=async t=>{let{step:e,tracer:r}=t.moduleParams,n=cm(e,t.moduleParams.resolvedInputs,"SUCCESS"),o=await r.startSubSteps(),{status:i,results:a}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return n.results=a,n.status=i,n.finishedAt=new Date,mn({asyncTasks:t.work.asyncTasks,nestedResults:a,result:n,logger:t.fixtures.logger}),n};function cm(t,e,r){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:t.id,moduleId:t.moduleId,moduleName:t.name,startedAt:new Date,cacheConfig:t.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:r}}async function II({orgId:t,step:e,context:r,logger:n,codeEvalTools:o,signal:i}){let a={};try{for(let s of e.parameters??[]){let c=e.inputs?.[s]??e.defaultParameters?.[s];if(!c){n.warn(`No value or default found for parameter '${s}' that is required by module '${e.name}'`);continue}a[s]=await qo({orgId:t,code:c,fragment:!0,context:r,logger:n,localTools:o,signal:i})}return a}catch(s){throw i?.throwIfAborted(),new M("UserConfigurationError",`Failed to evaluate module inputs: ${s}`)}}async function Rq({step:t,result:e,browser:r,cacheKeyPrefix:n,logger:o,storage:i}){let a=t.cacheConfig?.cacheExpiryMs;(!a||a===XR)&&(a=t.defaultCacheTtl??JR);let s;t.autoAuth?s=JSON.stringify(await r.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:is({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:n,ttlMs:a})}async function na(t,e,r){return Aq(t,e,r)}async function Aq(t,e,r){let n=new Date;try{return r.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(r.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof M?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,t.type==="RESOLVED_MODULE"){let c=cm(t,{},"FAILED");return c.message=s,c.startedAt=n,c.finishedAt=i,c}return{...Ld(t),startedAt:n,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function Os(t,e){let r=!1;try{return t&&!t.state.failureRecoveryDisabled&&(t.state.failureRecoveryDisabled=!0,r=!0),await e()}finally{t&&r&&(t.state.failureRecoveryDisabled=void 0)}}import{cloneDeep as kq}from"lodash-es";import{randomUUID as OI}from"crypto";import{diff as wq}from"deep-object-diff";import{cloneDeep as LI}from"lodash-es";var um=async t=>{let{step:e,tracer:r}=t.presetParams,{logger:n,controller:o,context:i}=t.fixtures,{collectDebugData:a}=t.options,{testMetadata:s}=t.inputs,c=e.command.type,l=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u="cache"in e.command&&e.command.cache?LI(e.command.cache):{},d=o.browser.url(),p=new Date,m,g=OI(),h=OI();if(a)try{if(m=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let T=await o.browser.getRawCondensedHtml();r.attachBeforeHtmlSnapshot({logger:l,snapshotId:g,html:T})}}catch(T){l.debug({err:T},"Failed to take before screenshot, continuing...")}let f,S,y,E=zu();try{let T=await o.executePresetCommand(E,r,e.command,i,s?.advanced.disableAICaching??!1);T.beforeScreenshotOverride&&(m=T.beforeScreenshotOverride),y=T.afterScreenshotOverride;let v=new Date,w=o.browser.url();S={beforeUrl:d,afterUrl:w,startedAt:p,finishedAt:v,viewport:o.browser.getViewport(),status:T.fail?"FAILED":"SUCCESS",elementInteracted:T.elementInteracted},f={...e,message:T.thoughts??"Successfully executed preset action.",beforeUrl:d,afterUrl:w,finishedAt:v,startedAt:p,status:T.fail?"FAILED":"SUCCESS",data:T.data,results:[S],details:E.details},"assertion"in e.command&&(f.message=T.thoughts||"Assertion passed.")}catch(T){l.error({message:T.message,stack:T.stack},`Failed executing preset step ${ao(e.command)}`);let v=o.browser.url(),w=new Date,C=T instanceof Error?T.message:`${T}`;S={beforeUrl:d,afterUrl:v,startedAt:p,finishedAt:w,viewport:o.browser.getViewport(),status:T instanceof DOMException&&T.name==="AbortError"?"CANCELLED":"FAILED",message:C},f={...e,startedAt:p,finishedAt:w,beforeUrl:d,afterUrl:v,status:T instanceof DOMException&&T.name==="AbortError"?"CANCELLED":"FAILED",message:C,failureReason:T instanceof M?T.reason:void 0,results:[S],details:E.details}}finally{let T="cache"in e.command&&e.command.cache?LI(e.command.cache):{},v=wq(u,T);v&&Object.keys(v).length>0&&l.info({diffs:qu(v)},"Updated cache")}if(a)try{if(y||(y=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let T=await o.browser.getRawCondensedHtml();r.attachAfterHtmlSnapshot({logger:l,snapshotId:h,html:T})}}catch(T){l.debug({err:T},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return S.beforeSnapshot=g,f.beforeSnapshot=g,S.afterSnapshot=h,f.afterSnapshot=h,m&&r.attachBeforeScreenshot({logger:l,snapshotId:g,screenshot:m}),y&&r.attachAfterScreenshot({logger:l,snapshotId:h,screenshot:y}),f};async function NI(t){let{step:e,tracer:r}=t.conditionalParams,{logger:n,controller:o}=t.fixtures,i=new Date,a=Ld(e),s=e.elseSteps,c=!0,l=[],u,d=zu();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let S=e.blocks[f];try{let y=await um({...t,presetParams:{tracer:r,step:S.assertion}});l.push(y),u=y,y.status==="SUCCESS"?(n.info(`Condition ${f} resolved to true, executing the corresponding ${S.steps.length} steps`),c=!1,s=S.steps):n.info(y.message,`Condition ${f} resolved to false`)}catch(y){n.info({err:y},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(s)c&&n.info("No conditions resolved to true, executing the else block steps");else{n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped");let f={...a,assertionResult:u,status:"SUCCESS",startedAt:i,data:l[l.length-1]?.data,message:l[l.length-1]?.message,results:[],finishedAt:new Date,details:d.details};return mn({asyncTasks:t.work.asyncTasks,nestedResults:[...l],result:f,logger:n}),f}n.info(`Executing ${s.length} steps in the selected conditional block`);let p=await t.conditionalParams.tracer.startSubSteps(),m=await t.executeStepList({...t,listParams:{steps:s,containerName:"conditional block",tracer:p}}),h={...a,assertionResult:u,...m,startedAt:i,finishedAt:new Date};return mn({asyncTasks:t.work.asyncTasks,nestedResults:[...l,...m.results],result:h,logger:n}),h}import{randomUUID as DI}from"crypto";var kI=async t=>{let{tracer:e}=t.aiStepParams,{controller:r,logger:n}=t.fixtures;await r.browser.waitForDOMStability();let o=await r.browser.screenshot({}),i=await Cq(t);i.finishedAt=new Date,mn({asyncTasks:t.work.asyncTasks,result:i,nestedResults:i.results,logger:t.fixtures.logger});let a=await r.browser.screenshot({}),s=DI();i.beforeSnapshot=s,e.attachBeforeScreenshot({logger:n,snapshotId:s,screenshot:o});let c=DI();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:a}),i},Cq=async t=>{let{step:e,tracer:r}=t.aiStepParams,{controller:n,context:o,logger:i}=t.fixtures,a={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new M("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await r.startSubSteps(),{status:l}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:c}});return a.finishedAt=new Date,a.status=l,a}catch(c){i.warn({err:c},"Failed executing saved deprecated AI action steps");let l=n.executeAbortController.signal.aborted;a.message=c instanceof Error?c.message:`${c}`,a.status=l?"CANCELLED":"FAILED"}return a};import{randomUUID as Ry}from"crypto";var FI=15,xq=7,UI=async t=>{let{tracer:e}=t.aiStepParams,{logger:r,controller:n}=t.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({quality:75}),i=await _q(t);i.finishedAt=new Date,mn({asyncTasks:t.work.asyncTasks,result:i,nestedResults:i.results,logger:t.fixtures.logger});let a=await n.browser.screenshot({quality:75}),s=Ry();i.beforeSnapshot=s,e.attachBeforeScreenshot({logger:r,snapshotId:s,screenshot:o});let c=Ry();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:r,snapshotId:c,screenshot:a}),i},_q=async t=>{let{step:e,tracer:r}=t.aiStepParams,{testMetadata:n,orgId:o}=t.inputs,{controller:i,context:a,logger:s,codeEvalTools:c}=t.fixtures,{step:l}=t.callbacks,u=`${e.id}-${Date.now()}`,d=s.child({stepId:e.id,langfuseSessionId:u}),p={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await pr({orgId:o,s:e.text,context:a,logger:d,localTools:c});await i.browser.waitForDOMStability({logger:d});let h=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],S=0,y=0,E,T;for(;;){if(S>FI)return p.message=`Exceeded the maximum number of commands allowed per AI step (${FI})`,p.status="FAILED",p;if(i.executeAbortController.signal.aborted)return p.message="Test execution was cancelled",p.status="CANCELLED",p;l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let v=await i.evaluateAiAction({goal:m,startingScreenshot:S===0?void 0:h,history:f,logger:d,langfuseSessionId:u,lastError:T}),{evaluation:w,reasoning:C,summary:_}=v;d.info(v,"Got AI evaluation");let N=p.results[S-1]?.id;switch(w.type){case"DONE":return p.message=`Our AI evaluator confirmed all tasks are complete: ${C}`,p.status="SUCCESS",N&&l.onDynamicAIActionEvaluatingEvent?.({stepId:N,status:"SUCCESS",message:`${_}
4373
+ ${t}`;default:return t}}var iq=15;async function am({command:t,aiPageFiltering:e,logger:r,fixtures:n,source:o,useMemory:i,maxRetries:a=iq}){if(!t.assertion.trim())throw new M("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=t.timeout?t.timeout*1e3:s.smartWaitingTimeout,l=Dw(c),u=0,d=Date.now(),p,m,g;try{await Qr({action:()=>s.clearHighlights(),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:s,logger:r})}catch(f){r.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;u<a&&(!h||h-d<c);){n.abortSignal.throwIfAborted(),u!==0&&await le(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await Qr({action:async()=>{let y=await SI(s,r,n.abortSignal);return m&&m.serializedTree===y.serializedTree&&m.screenshotBuff.equals(y.screenshotBuff)?(f=!0,p):(m=y,yI({command:t,state:y,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:r,source:o}))},frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:r,browser:s}),p?.success){p?.updatedMemory&&Vl(t,p.updatedMemory,r);break}else throw p?.thoughts?new M("AssertionFailureError",p.thoughts):new M("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(S){n.abortSignal.throwIfAborted(),g=S instanceof Error?S:new Error(`${S}`),f?r.info(`AI check attempt ${u} failed (re-used previous result)`):r.info({err:S},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await Qr({action:async()=>yI({command:t,state:await SI(s,r,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:r}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:r,browser:s})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(p?.updatedMemory&&Vl(t,p.updatedMemory,r),!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new M("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function SI(t,e,r){let[n,o]=await Promise.all([jn(t,{abortSignal:r,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function yI({command:t,state:e,fixtures:r,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:p}=r,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,S=f.toString("base64"),y=u.url(),E=t.contextChoice??"MULTIMODAL",T=g;E!=="VISION_ONLY"&&(T=await ra({type:"assertion",serializedTree:g,tree:h,description:t.assertion,screenshot:S,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:r.orgId}}),T!==g&&(m.ragUsed=!0),m.pageState=T);let v={goal:t.assertion,url:y,memory:o?t.cache?.memory:void 0,browserState:T,screenshot:S,contextChoice:E,source:c},C=await(E==="VISION_ONLY"?(_,N)=>d.getVisualAssertionResult(_,N):(_,N)=>d.getAssertionResult(_,N))(v,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!t.disableCache,abortSignal:p,logger:l,loggerTags:je(l)});return(C.result||i)&&C.relevantElements&&(m.relevantElementsSerialized=C.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_),await aq(C.relevantElements,u,l)),{success:C.result,thoughts:C.thoughts,afterScreenshotOverride:f,updatedMemory:o?C.updatedMemory:void 0}}async function aq(t,e,r){let n=Date.now();for(let o of t){if(Date.now()-n>2e3){r.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await $(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){r.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var sq=75e4,sm=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function EI(t,e){let{logger:r}=t,{abortSignal:n,browser:o}=e,i=Date.now();try{await lq(i,t,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof sm?r.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):r.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await le(s,n)}finally{r.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function lq(t,e,r){let{abortSignal:n,browser:o}=r;if(o.smartWaitingTimeout<3e3){await le(o.smartWaitingTimeout,n);return}if(!e.description)throw new M("UserConfigurationError","Cannot locate element with empty description");await $(cq(t,e,r),{milliseconds:o.smartWaitingTimeout})}async function cq(t,e,r){let{logger:n,iframeUrl:o}=e,{browser:i}=r;for(;Date.now()-t<i.smartWaitingTimeout;)if(await Qr({action:async()=>uq(e,r),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function uq(t,e){let{testContext:r,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=t,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=t.description;r&&(d=await pr({orgId:l,s:d,context:r,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await jn(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Pe(p)>sq)throw new sm;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(y){throw new M("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${y instanceof Error?y.message:y}`)}let f=`data:image/jpeg;base64,${g.toString("base64")}`;s.throwIfAborted();let S=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:je(n)});return n.debug({result:S},"Got smart waiting result"),S.isPageReady}import{cloneDeep as TI}from"lodash-es";async function vI(t){let{command:e,timeoutMs:r,fixtures:n}=t,{abortSignal:o}=n,i=()=>LE(e.cache)?e.cache:void 0,a=i(),s=TI(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=rf(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,p=500,m=!1;for(;u<2||Date.now()-l<r;){u++,u>1&&await le(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await bI({cacheToUse:a,params:t});if(d=h,m=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new M("InternalPlatformError",`Failed to evaluate manual element assertion in ${r}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&ru(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await bI({cacheToUse:h,params:t});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!m&&(g.target=jl(g.target),g.updatedAt=new Date),d}async function bI({cacheToUse:t,params:e}){let{command:r,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(r.target&&!Ao(r.target))throw new Error("Element assertion with x/y is not supported yet");let c=LA(r.assertion),l,u=!1,d=TI(t);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:r,target:r.target,cache:d?.target,action:async h=>dq(h.locator,e),options:{...r,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Ri(r),targetName:"target"}});return l={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(s.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),l={...m,thoughts:g}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof M)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function dq(t,{command:e,fixtures:r}){return await r.browser.highlight(t),await pq(t,e.assertion)}async function pq(t,e){let r=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await t.textContent()??"";if(o={elementTextContent:tt(a,500,!0)},!Gl(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=es(e);r=!1,n=new M("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:tt(await t.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await t.getAttribute(e.attr,{timeout:3e3})??""}catch(s){n=new M("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),r=!1;break}if(!Gl(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=es(e);r=!1,e.operation==="EXISTS"?n=new M("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new M("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{r=await t.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Tn*1e3);break}case"EDITABLE":{r=await t.isEditable({timeout:Tn*1e3});break}case"EXISTS":{r=!0;break}case"ENABLED":{r=await t.isEnabled({timeout:Tn*1e3});break}case"FOCUSED":{r=await t.evaluate(s=>s===document.activeElement);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e.condition)}if(r=e.negated?!r:r,!r){let a=es(e);n=new M("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await t.evaluate(s=>s.tagName);if(!Gl(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=es(e);r=!1,n=new M("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await t.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!Gl(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=es(e);r=!1,e.operation==="EXISTS"?n=new M("AssertionFailureError",`The style property ${e.property} ${s}`):n=new M("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:r,data:o,err:n}}function RI(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as mq}from"jimp";async function Pc(t,e){let r=await t.screenshot(e),n=await mq.fromBuffer(r);return{buffer:r,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as AI}from"jimp";import Ty from"jpeg-js";import hq from"pixelmatch";async function wI({ctx:t,tracer:e,command:r,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(r.target&&!Ao(r.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},l;r.target?.elementDescriptor?l=(await i({ctx:t,tracer:e,command:r,target:r.target,cache:r.cache?.target,action:async j=>Pc(o,{locator:j.locator,...c}),options:{...r,disableCache:n,disableGlobalLocatorRedirect:!0,memory:r.cache?.target?.memory,targetName:"target"}})).result:l=await Pc(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,r,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let U=`${l.width}x${l.height}`,j=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${U}) does not match saved screenshot dimensions (${j}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await AI.fromBuffer(l.buffer),p={width:l.width,height:l.height},m=await AI.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,S=g.width*g.height,y=Math.abs(p.height-g.height),E=Math.abs(p.width-g.width);if(f>S){let U=d.cover({w:g.width,h:g.height});l.buffer=await U.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(S>f){let U=m.cover({w:p.width,h:p.height});u.buffer=await U.getBuffer("image/jpeg"),h="saved"}let T={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=r.threshold??.1,C=hq(Ty.decode(u.buffer).data,Ty.decode(l.buffer).data,T.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,_=C>v*100,N=`Visual diff of ${C.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${v*100}%.`;if(h&&(N+=` The ${h} screenshot was cropped since it was taller by ${y} pixels and wider by ${E} pixels.`),_)throw new M("ActionFailureError",N);return{fail:_,thoughts:N,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Ty.encode(T,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var gq=3e4;function fq(t){if(!t.body)return{};switch(t.body.type){case"json":return{content:t.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(t.body.content).forEach(([r,n])=>{e.append(r,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function CI({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??gq/1e3,i=Object.fromEntries(Object.entries(t.headers||{}).filter(([g,h])=>g&&h)),a=new URLSearchParams;Object.entries(t.params||{}).filter(([g,h])=>g&&h).forEach(([g,h])=>{a.append(g,h)});let s=a.toString(),c;if(as(t.url)&&(c=t.url),r&&ss(t.url,r)&&(c=new URL(t.url,r).toString()),!c)throw new M("ActionFailureError",`Invalid URL: ${t.url}`);let l=c;e.info({url:l,searchParams:s,headers:i,body:t.body,method:t.method},"Making HTTP request");let d=await $((async()=>{let g=s?`${l}?${s}`:l;try{let h=fq(t),f=new Headers(i);return h.contentType&&!f.has("Content-Type")&&f.set("Content-Type",h.contentType),await n(g,{headers:f,method:t.method,body:h.content})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new M("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let g;try{g=await d.text()}catch(h){g=`Failed to read response body: ${h}`}throw new M("ActionFailureError",`Fetch request failed with status ${d.status}: ${g}`)}let p={};d.headers.forEach((g,h)=>{p[h]=g});let m={status:d.status,headers:p,request:{url:d.url,method:t.method,headers:i}};if(t.body?.type==="json"&&t.body.content)try{m.request.json=JSON.parse(t.body.content)}catch{}if(d.headers.get("content-type")?.includes("json"))try{m.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(m.text=await d.text());return m}var Sq=5e3;async function lm({timeout:t=Tn,...e}){let r=Date.now(),n=t*1e3,o=n+1e4,i,a=0,s=500;for(;a-r<n;){if(Date.now()-r>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal?.throwIfAborted();let c=Date.now();i=await xI(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await le(s,e.signal),s=Math.min(Math.floor(s*1.5),Sq);else return i}return i=await xI(e),i}async function xI({assertion:t,browser:e,autoExpandIframes:r}){switch(t.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(r){let c=await e.evaluateFunctionInAllFrames(_I,{value:t.value,negated:!!t.negated,returnHtml:!1});i=t.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(_I,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!i){let c=t.negated?oo.CONTAINS:io.CONTAINS;a=new M("AssertionFailureError",`The page ${c} '${t.value}'.`),o=s}}catch(s){a=new M("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function _I({value:t,negated:e,returnHtml:r}){let n=document.documentElement.outerHTML,o=n.includes(t)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&r?n:void 0}}var yq=3e4;async function MI({command:t,logger:e,baseUrl:r,fetchImplementation:n=fetch}){let o=t.timeout??yq/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(as(t.url)&&(s=t.url),r&&ss(t.url,r)&&(s=new URL(t.url,r).toString()),!s)throw new M("ActionFailureError",`Invalid URL: ${t.url}`);let l=await $((async()=>{try{return await n(s,{headers:a,method:"POST",body:JSON.stringify({query:t.query,variables:t.variables?JSON.parse(t.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!l)throw new M("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new M("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new M("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new M("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var oi=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:r,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=r,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:r,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([jn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await ra({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:r,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...je(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:r,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([jn(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await ra({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),m={url:c,browserState:p,startingScreenshot:r,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...je(a)},langfuseSessionId:s})}catch(g){throw new M("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return jn(this.browser,e)}async locateElement(e){return await by({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,r){return Qr({action:async()=>{let n=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:n}},frameConfig:r?{type:"url",url:r}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:r,command:n,targetNames:o,descriptions:i,caches:a,action:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await s(...u.map(g=>g.result)),p=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",m=u.map((g,h)=>g.thoughts?`${p(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:m}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:r,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new M("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let r=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await Qr({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:r})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Sh(i)){r.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(bh(i)||yh(i))){r.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Th(i)){r.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Rn&&i.retryableWithAI){r.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof M?n:new M("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:r,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(r.type!=="description")throw new M("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:r.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await le(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:r,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,S=!1,y=PI(e.cache);if((!y||l)&&!ih(o))throw new M("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),S=!0,y=void 0),y&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&y.targetSource==="HEURISTIC_HEALED"&&(S=!0,y=void 0),y?.inputDescription&&!fI(o.elementDescriptor,y.inputDescription)&&(g.warn({old:y.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),S=!0,y=void 0);let E=v=>!!v&&ru(v),T=!0;if(!E(y)){T=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:S,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(S||!i)&&await EI({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:m,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(r)),f--;let v;try{v=await by({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:m,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(r))}catch(_){if(_ instanceof Ia&&_.updatedLocatorMemory){let N={id:-1,...i,memory:_.updatedLocatorMemory};vd({cmd:c,key:d,newTarget:N,logger:g,updatedWithAI:!0})}throw new M("ActionFailureError",_.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let w=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),C=await a(w);return vd({cmd:c,key:d,newTarget:v.target,logger:g,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=je(g)),{result:C,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(r,y,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let w=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),C=await a(w);if(kt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!y.requirements}`,`hasAdditionalElements:${!!y.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.29.5"]),vd({cmd:c,key:d,newTarget:y,logger:g,updatedWithAI:!1}),T){let _=v.decisions.filter(N=>N.matched);if(_.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let N=_[0].type;n.recordTargetAutoHeal({healType:N})}}return{result:C,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let w="unknown";v instanceof kr&&v.cacheMissReason&&(w=v.cacheMissReason),kt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!y.requirements}`,`hasAdditionalElements:${!!y.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:2.29.5",`missReason:${w}`]);let C=!1;if((v instanceof Rn||Sh(v)||bh(v)||Th(v)||zb(v)||yh(v)||Hb(v))&&(C=!0),v instanceof M&&!C)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let _;return y.memory&&nu(y.memory)&&(_=y.memory),this.wrapElementTargetingCommand({ctx:r,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:_,retriesWithAI:f,targetHealingInProgress:!0}})}throw new M("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,r){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,r):{locator:e}}async screenshotWithDimensions(e){return Pc(this.browser,e)}async executePresetCommand(e,r,n,o,i){this.options?.slowMoMs&&await le(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new M("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,r,n,o,i);return this.browser.userBrowserSettings.visualActions&&rb(n)?await this.browser.waitForDOMStability({timeout:Ne}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:de}),this.options?.autoFollowNewTabs&&await sI({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{xC(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Hf(e)}}async resolveCommandTemplateStrings(e,r){return Xd({obj:e,context:r,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,r,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let s=n.condition;return s?.assertion.trim()?am({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new M("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new M("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return am({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new M("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let h=iA(n.schema);if(h)throw new M("UserConfigurationError",h)}let m=await this.browser.getCondensedHtml(),g=await this.browser.screenshot({retries:2});try{let h=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${g.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:je(a)});if(h.result==="NOT_FOUND")throw new M("ActionFailureError","No relevant data found for extraction goal on this page");if(h.thoughts?.includes("MaxGenerationLengthExceededError"))throw new M("UserConfigurationError",h.thoughts);return{thoughts:h.thoughts||void 0,data:h.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(h){let f=h.message;throw f.includes("MaxGenerationLengthExceededError")?new M("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):f.includes("AIProviderError")&&f.includes("time")?new M("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:h}}):h}}case"NAVIGATE":if(!as(n.url)&&!ss(n.url,this.browser.baseUrl))throw new M("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":throw new M("UserConfigurationError","Captcha solving is no longer available on Momentic");case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let m,g;if(n.target&&bn(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:S,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:n.target,cache:n.cache?.target,action:E=>this.browser.hover(E),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=S,g=y}let h=this.browser.getViewport()?.height??Kt.height,f=this.browser.getViewport()?.width??Kt.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??h));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??h);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??f));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??f);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:g}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new M("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new M("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let c=n.delay*1e3;await le(c,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(bn(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=this.browser.url(),{elementInteractedDisplayString:g,result:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,target:n.target,command:n,cache:n.cache?.target,action:y=>this.browser.click(y,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:f,data:h.downloadedFile?{downloadedFile:h.downloadedFile}:void 0};return Dd(m,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"COPY":return await this.browser.copy(n.value),{succeedImmediately:!1,data:n.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(bn(n.fromTarget)&&bn(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0});break}if(bn(n.fromTarget)||bn(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,thoughts:g}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:r,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(h,f)=>this.browser.dragAndDrop(h.locator,f.locator,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m[0],thoughts:g}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),g=parseInt(n.deltaY),h=n.steps??5;if(isNaN(m)||isNaN(g))throw new M("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&bn(n.target)){await this.browser.mouseDragUsingVisualCoordinates({deltaX:m,deltaY:g,steps:h,fromTarget:n.target.pixels});break}let f,S;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:y,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:n.target,cache:n.cache?.target,action:async T=>this.browser.mouseDrag(m,g,h,T.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});f=y,S=E}else await this.browser.mouseDrag(m,g,h,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:S}}case"SELECT_OPTION":{if(!Ao(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,g=n.choice,{elementInteractedDisplayString:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:S=>this.browser.selectOption(S,g,n.force),options:{...n,targetName:"target",disableCache:i,source:Ri(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,thoughts:f}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let l=await this.browser.setCookie(n.value);a.debug({results:l},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let m;try{n.environment==="BROWSER"?(m=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:m},"Executed JavaScript in browser")):m=await qo({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async g=>{if(!this.options?.scratchPadId){a.warn({updates:g},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:g,logger:a})}}})}catch(g){throw this.throwIfClosed(),new M("ActionFailureError",g instanceof Error?g.message:`${g}`,{errOptions:{cause:g}})}try{JSON.stringify(m)}catch(g){throw new M("ActionFailureError",`Return value is not serializable: ${g instanceof Error?g.message:`${g}`}`,{errOptions:{cause:g}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&bn(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let m=this.browser.url(),g,h,f=PI(n.target),S=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(f){let{elementInteractedDisplayString:E,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:f,cache:n.cache?.target,action:v=>this.browser.typeIntoTarget(n.value,v,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!S,source:Ri(n)}});g=E,h=T}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let y={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:h};return Dd(m,y.urlAfterCommand)&&(y.succeedImmediately=!0,y.succeedImmediatelyReason="URL changed"),y}case"HOVER":{if(bn(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:n.target,cache:n.cache?.target,action:h=>this.browser.hover(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:g}}case"FOCUS":{if(!Ao(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,command:n,target:n.target,cache:n.cache?.target,action:h=>this.browser.focus(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:g}}case"BLUR":{if(n.target&&!Ao(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:m,thoughts:g}=await this.wrapElementTargetingCommand({ctx:e,tracer:r,target:n.target,command:n,cache:n.cache?.target,action:h=>this.browser.blur(h),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:g}}case"PRESS":let u=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let d={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Dd(u,d.urlAfterCommand)&&(d.succeedImmediately=!0,d.succeedImmediatelyReason="URL changed"),d;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let m=new bq,g=Eq(fetch,m),h;try{h=new URL(n.url).hostname}catch{}let f=await CI({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:g});return{data:al.parse({...f,cookies:Lv(m,h)}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await MI({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return wI({ctx:e,tracer:r,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,g;if(n.fileSource.type==="URL"?(g=n.fileSource.url,m=await UC({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(g=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new M("UserConfigurationError",`Attempted to use non-existent file for upload step: ${g}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await qo({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new M("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let g;try{g=Qu.optional().parse(m)}catch(h){throw new M("ActionFailureError",`Credentials provided do not follow the required format: ${h}`)}await this.browser.loadAuthState(g);break}case"ELEMENT_CHECK":{let m=(n.timeout??Tn)*1e3,g=this.generator.getAgentConfig()?.assertion;if(RI(n.assertion)&&!n.useSelector&&n.target.type==="description"&&g&&g!=="v1"){let f={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let S=await am({command:f,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${S.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:S.afterScreenshotOverride}}finally{f.cache?.memory&&Vl(n,f.cache?.memory.traces,a)}}let h=await vI({command:n,tracer:r,timeoutMs:m,targetingWrapper:f=>this.wrapElementTargetingCommand(f),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!h.success,data:h.data,elementInteracted:h.elementInteractedDisplayString,thoughts:h.err?.message??h.thoughts??`Element assertion ${h.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let m=await Qr({action:async()=>lm({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new Yo(n.requestMatcher),g=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=g.then(async h=>await Wf(h)).catch(h=>{a.error({err:h},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new M("ActionFailureError",`No listener registered with key: ${n.key}`);let g=n.timeout??10;return{data:await $(m,{milliseconds:g*1e3,message:`Request listener timed out after ${g} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new Yo(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:g=>m.matches({url:g.request.url,method:g.request.method}),onRequestStart:(g,h)=>{this.recordedRequests[n.key][g]=tp(h)},onRequestComplete:(g,h)=>{this.recordedRequests[n.key]?.[g]&&(this.recordedRequests[n.key][g]=tp(h))}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new M("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new Yo(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new Yo(n.requestMatcher),async(g,h)=>{let f=await qo({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:g,response:h},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),S=Nv.parse(f);return new Response(S.body,{status:S.status,headers:S.headers})},n.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:r,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:r,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:je(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:r,isClickToRecord:n}){this.recordAbortController=r;let o=new sp({signal:r.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,n),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:je(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:je(this.logger)})}};var vy=async t=>{let{step:e,resolvedInputs:r}=t.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:s}=t.fixtures,c=s.browser,{orgId:l,runId:u}=t.inputs,d=s.executeAbortController.signal;Object.keys(r).length>0&&(o.setInputs(r),n.info(is({json:{inputs:r,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=!1,g,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await pr({orgId:l,s:f,context:o,logger:n,localTools:a,signal:d});h={orgId:l,cacheKeys:[S,...Object.entries(r).map(([E,T])=>`${E}:${T}`)]},n.info({original:f,keyParams:h},"Module cache key params");let y=Date.now();for(;Date.now()-y<aR;){d?.throwIfAborted();let E=await i.getCacheResult(h);if(E){n.info({cacheResult:tt(E,1e3,!0)},"Got result from module execution cache"),p=cm(e,r,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(E),m=!0;break}else n.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let T=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${Tq()};runId:${u}`},d);if(T.acquired){g=T.keyPrefix,n.info({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else n.debug({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await le(2500+Math.random()*1e4,d)}}try{if(!p)p=await vq(t);else if(e.autoAuth){let f=Qu.safeParse(p.data);if(!f.success)throw new M("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);n.debug("Automatically loading auth state after cached module result"),await c.loadAuthState(f.data);let S=!1,y=e.advanced?.cacheInvalidation;if(y&&y.type==="PAGE_CHECK"){let E={type:"CONTENT",value:y.substring},T=await lm({timeout:Tn,assertion:E,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});T.success?n.debug({invalResult:T},"Cached result still valid after page check, continuing..."):(n.info({invalResult:T},"Invalidating cached result due to page check failure"),S=!0)}if(h&&S)return await i.deleteCacheResult(h),vy(t)}}finally{try{g!==void 0&&!m&&p?.status==="SUCCESS"&&await Rq({step:e,result:p,browser:s.browser,cacheKeyPrefix:g,logger:n,storage:i})}finally{g!==void 0&&await i.releaseCacheLock(g)}}return p},vq=async t=>{let{step:e,tracer:r}=t.moduleParams,n=cm(e,t.moduleParams.resolvedInputs,"SUCCESS"),o=await r.startSubSteps(),{status:i,results:a}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return n.results=a,n.status=i,n.finishedAt=new Date,mn({asyncTasks:t.work.asyncTasks,nestedResults:a,result:n,logger:t.fixtures.logger}),n};function cm(t,e,r){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:t.id,moduleId:t.moduleId,moduleName:t.name,startedAt:new Date,cacheConfig:t.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:r}}async function II({orgId:t,step:e,context:r,logger:n,codeEvalTools:o,signal:i}){let a={};try{for(let s of e.parameters??[]){let c=e.inputs?.[s]??e.defaultParameters?.[s];if(!c){n.warn(`No value or default found for parameter '${s}' that is required by module '${e.name}'`);continue}a[s]=await qo({orgId:t,code:c,fragment:!0,context:r,logger:n,localTools:o,signal:i})}return a}catch(s){throw i?.throwIfAborted(),new M("UserConfigurationError",`Failed to evaluate module inputs: ${s}`)}}async function Rq({step:t,result:e,browser:r,cacheKeyPrefix:n,logger:o,storage:i}){let a=t.cacheConfig?.cacheExpiryMs;(!a||a===XR)&&(a=t.defaultCacheTtl??JR);let s;t.autoAuth?s=JSON.stringify(await r.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:is({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:n,ttlMs:a})}async function na(t,e,r){return Aq(t,e,r)}async function Aq(t,e,r){let n=new Date;try{return r.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(r.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof M?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,t.type==="RESOLVED_MODULE"){let c=cm(t,{},"FAILED");return c.message=s,c.startedAt=n,c.finishedAt=i,c}return{...Ld(t),startedAt:n,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function Os(t,e){let r=!1;try{return t&&!t.state.failureRecoveryDisabled&&(t.state.failureRecoveryDisabled=!0,r=!0),await e()}finally{t&&r&&(t.state.failureRecoveryDisabled=void 0)}}import{cloneDeep as kq}from"lodash-es";import{randomUUID as OI}from"crypto";import{diff as wq}from"deep-object-diff";import{cloneDeep as LI}from"lodash-es";var um=async t=>{let{step:e,tracer:r}=t.presetParams,{logger:n,controller:o,context:i}=t.fixtures,{collectDebugData:a}=t.options,{testMetadata:s}=t.inputs,c=e.command.type,l=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u="cache"in e.command&&e.command.cache?LI(e.command.cache):{},d=o.browser.url(),p=new Date,m,g=OI(),h=OI();if(a)try{if(m=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let T=await o.browser.getRawCondensedHtml();r.attachBeforeHtmlSnapshot({logger:l,snapshotId:g,html:T})}}catch(T){l.debug({err:T},"Failed to take before screenshot, continuing...")}let f,S,y,E=zu();try{let T=await o.executePresetCommand(E,r,e.command,i,s?.advanced.disableAICaching??!1);T.beforeScreenshotOverride&&(m=T.beforeScreenshotOverride),y=T.afterScreenshotOverride;let v=new Date,w=o.browser.url();S={beforeUrl:d,afterUrl:w,startedAt:p,finishedAt:v,viewport:o.browser.getViewport(),status:T.fail?"FAILED":"SUCCESS",elementInteracted:T.elementInteracted},f={...e,message:T.thoughts??"Successfully executed preset action.",beforeUrl:d,afterUrl:w,finishedAt:v,startedAt:p,status:T.fail?"FAILED":"SUCCESS",data:T.data,results:[S],details:E.details},"assertion"in e.command&&(f.message=T.thoughts||"Assertion passed.")}catch(T){l.error({message:T.message,stack:T.stack},`Failed executing preset step ${ao(e.command)}`);let v=o.browser.url(),w=new Date,C=T instanceof Error?T.message:`${T}`;S={beforeUrl:d,afterUrl:v,startedAt:p,finishedAt:w,viewport:o.browser.getViewport(),status:T instanceof DOMException&&T.name==="AbortError"?"CANCELLED":"FAILED",message:C},f={...e,startedAt:p,finishedAt:w,beforeUrl:d,afterUrl:v,status:T instanceof DOMException&&T.name==="AbortError"?"CANCELLED":"FAILED",message:C,failureReason:T instanceof M?T.reason:void 0,results:[S],details:E.details}}finally{let T="cache"in e.command&&e.command.cache?LI(e.command.cache):{},v=wq(u,T);v&&Object.keys(v).length>0&&l.info({diffs:qu(v)},"Updated cache")}if(a)try{if(y||(y=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let T=await o.browser.getRawCondensedHtml();r.attachAfterHtmlSnapshot({logger:l,snapshotId:h,html:T})}}catch(T){l.debug({err:T},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return S.beforeSnapshot=g,f.beforeSnapshot=g,S.afterSnapshot=h,f.afterSnapshot=h,m&&r.attachBeforeScreenshot({logger:l,snapshotId:g,screenshot:m}),y&&r.attachAfterScreenshot({logger:l,snapshotId:h,screenshot:y}),f};async function NI(t){let{step:e,tracer:r}=t.conditionalParams,{logger:n,controller:o}=t.fixtures,i=new Date,a=Ld(e),s=e.elseSteps,c=!0,l=[],u,d=zu();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let S=e.blocks[f];try{let y=await um({...t,presetParams:{tracer:r,step:S.assertion}});l.push(y),u=y,y.status==="SUCCESS"?(n.info(`Condition ${f} resolved to true, executing the corresponding ${S.steps.length} steps`),c=!1,s=S.steps):n.info(y.message,`Condition ${f} resolved to false`)}catch(y){n.info({err:y},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(s)c&&n.info("No conditions resolved to true, executing the else block steps");else{n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped");let f={...a,assertionResult:u,status:"SUCCESS",startedAt:i,data:l[l.length-1]?.data,message:l[l.length-1]?.message,results:[],finishedAt:new Date,details:d.details};return mn({asyncTasks:t.work.asyncTasks,nestedResults:[...l],result:f,logger:n}),f}n.info(`Executing ${s.length} steps in the selected conditional block`);let p=await t.conditionalParams.tracer.startSubSteps(),m=await t.executeStepList({...t,listParams:{steps:s,containerName:"conditional block",tracer:p}}),h={...a,assertionResult:u,...m,startedAt:i,finishedAt:new Date};return mn({asyncTasks:t.work.asyncTasks,nestedResults:[...l,...m.results],result:h,logger:n}),h}import{randomUUID as DI}from"crypto";var kI=async t=>{let{tracer:e}=t.aiStepParams,{controller:r,logger:n}=t.fixtures;await r.browser.waitForDOMStability();let o=await r.browser.screenshot({}),i=await Cq(t);i.finishedAt=new Date,mn({asyncTasks:t.work.asyncTasks,result:i,nestedResults:i.results,logger:t.fixtures.logger});let a=await r.browser.screenshot({}),s=DI();i.beforeSnapshot=s,e.attachBeforeScreenshot({logger:n,snapshotId:s,screenshot:o});let c=DI();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:a}),i},Cq=async t=>{let{step:e,tracer:r}=t.aiStepParams,{controller:n,context:o,logger:i}=t.fixtures,a={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new M("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await r.startSubSteps(),{status:l}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:c}});return a.finishedAt=new Date,a.status=l,a}catch(c){i.warn({err:c},"Failed executing saved deprecated AI action steps");let l=n.executeAbortController.signal.aborted;a.message=c instanceof Error?c.message:`${c}`,a.status=l?"CANCELLED":"FAILED"}return a};import{randomUUID as Ry}from"crypto";var FI=15,xq=7,UI=async t=>{let{tracer:e}=t.aiStepParams,{logger:r,controller:n}=t.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({quality:75}),i=await _q(t);i.finishedAt=new Date,mn({asyncTasks:t.work.asyncTasks,result:i,nestedResults:i.results,logger:t.fixtures.logger});let a=await n.browser.screenshot({quality:75}),s=Ry();i.beforeSnapshot=s,e.attachBeforeScreenshot({logger:r,snapshotId:s,screenshot:o});let c=Ry();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:r,snapshotId:c,screenshot:a}),i},_q=async t=>{let{step:e,tracer:r}=t.aiStepParams,{testMetadata:n,orgId:o}=t.inputs,{controller:i,context:a,logger:s,codeEvalTools:c}=t.fixtures,{step:l}=t.callbacks,u=`${e.id}-${Date.now()}`,d=s.child({stepId:e.id,langfuseSessionId:u}),p={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await pr({orgId:o,s:e.text,context:a,logger:d,localTools:c});await i.browser.waitForDOMStability({logger:d});let h=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],S=0,y=0,E,T;for(;;){if(S>FI)return p.message=`Exceeded the maximum number of commands allowed per AI step (${FI})`,p.status="FAILED",p;if(i.executeAbortController.signal.aborted)return p.message="Test execution was cancelled",p.status="CANCELLED",p;l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let v=await i.evaluateAiAction({goal:m,startingScreenshot:S===0?void 0:h,history:f,logger:d,langfuseSessionId:u,lastError:T}),{evaluation:w,reasoning:C,summary:_}=v;d.info(v,"Got AI evaluation");let N=p.results[S-1]?.id;switch(w.type){case"DONE":return p.message=`Our AI evaluator confirmed all tasks are complete: ${C}`,p.status="SUCCESS",N&&l.onDynamicAIActionEvaluatingEvent?.({stepId:N,status:"SUCCESS",message:`${_}
4374
4374
  ${C}`}),p;case"RIGHT_TRACK":{E=void 0,S===0?l.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:C}):N&&l.onDynamicAIActionEvaluatingEvent?.({stepId:N,status:"SUCCESS",message:C});break}case"WRONG_TRACK":{if(E=`${C}
4375
4375
  ${w.feedback}`,y++,y>=xq)return p.message=`Our AI agent requires additional information to achieve this goal:
4376
4376
  ${C}
4377
- ${w.feedback}`,p.status="FAILED",l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:p.message}),p;N&&l.onDynamicAIActionEvaluatingEvent?.({stepId:N,status:"FAILED",message:w.feedback});break}case"IMPOSSIBLE":return p.message=`Our AI evaluator determined this task cannot be achieved: ${C}`,p.status="FAILED",l.onDynamicAIActionEvaluatingEvent?.({stepId:N??e.id,status:"FAILED",message:p.message}),p}let U=setTimeout(()=>{l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:S,lastActionHint:E},`Generating new sub-command ${S} within AI action`);let j,O;try{({command:j,reasoning:O}=await i.promptToCommand({goal:m,history:f,startingScreenshot:h,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:E,langfuseSessionId:u})),d.info({command:j,reasoning:O},"Got proposed command")}finally{clearTimeout(U)}if(j.type==="FAILURE")return clearTimeout(U),p.status="FAILED",p.message=`Our AI agent determined that no supported actions can fulfill the goals: ${O}`,p;let B={id:Ry(),type:"PRESET_ACTION",command:j},W={substepIndex:S+1,message:O||"Generated new command."};l.onDynamicCommandGenerated?.({...W,step:B,parentStepId:e.id}),d.info({commandId:j.id},`Executing sub-command ${S} within AI step: ${ao(j)}`);let q=await r.startSubSteps(),Y=(await t.executeStepList({...t,options:{...t.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[B],tracer:q}})).results[0];l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let st=await i.browser.screenshot({clearHighlights:!0,retries:1});p.results.push(Y),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${st.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:ao(j),elementInteracted:Y.results[0]?.elementInteracted,thoughts:O});let Le={substepIndex:S,output:{...Y,message:Y.message??"Successfully executed preset action."},step:B,parentStepId:e.id};if(l.onDynamicCommandExecuted?.(Le),await r.finish({output:Ou.parse(Y),step:Y,message:Y.message,attempt:1}),Y.status==="FAILED")if(p.status="FAILED",p.message=Y.message,y<3)y++,T=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${Y.message}`;else return p;else if(Y.status==="CANCELLED")return p.status="CANCELLED",p.message=Y.message,p;S++}};import{randomUUID as Mq}from"crypto";var Pq=3;async function zI(t){let{logger:e}=t.fixtures,{results:r}=t.failureRecoveryParams,n=r[r.length-1],o=Oq(t.work,n);if(o)return e.info({failedResult:n,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};e.info({failedResult:n},"Attempting failure recovery"),t.work.state.failureRecoveryAttempts=(t.work.state.failureRecoveryAttempts??0)+1;try{return await Iq(t)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function Iq(t){let{fixtures:e,work:r,failureRecoveryParams:n}=t,{controller:o,logger:i}=e,{testMetadata:a}=t.inputs,{results:s,failedStep:c,nextSteps:l,tracer:u}=n;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(r.asyncTasks??[]);let d=o.browser.url(),p=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,m=(await o.browser.getBrowserState({})).serialize(),{results:g}=await os(i,u,s,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=l.map(_=>lo(_)),f=a?.description?.trim(),S=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:y,thoughts:E,instructions:T}=await o.getFailureRecoveryPlan({currentUrl:d,currentScreenshot:p,failedResults:g,currentPageState:m,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:S||void 0});if(y!=="RECOVERABLE")return i.info({scenario:y,thoughts:E,instructions:T},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${E}`};if(!T)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let v={id:Mq(),type:"AI_ACTION_DYNAMIC",text:T},w=await Os(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures},listParams:{steps:[v,c],containerName:"AI-recovered step list",tracer:u}})),C=w.results[0];if(C&&C.type==="AI_ACTION_DYNAMIC")if(Ed({results:w.results,onPresetAction:_=>{_.aiSuggested=!0},onSimpleStepContainer:_=>{_.aiSuggested=!0}}),w.status==="SUCCESS"){let _=`The following steps were automatically executed by the failure recovery agent. Analysis: ${E}`;return C.message=_,kt.increment("test_event",1,["name:failure_recovery_success",`orgId:${t.inputs.orgId}`]),i.info({thoughts:E},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:w,message:_}}else{kt.increment("test_event",1,["name:failure_recovery_failure",`orgId:${t.inputs.orgId}`]);let _=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${E}`;return C.message=_,i.info({thoughts:E,aiActionResult:C},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:w,message:_}}return null}function Oq(t,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let r=e.message;return r?r.includes("AbortError:")?"The user aborted the test":Ub.some(n=>r.includes(n))?"The failed step is an irrecoverable configuration error":(t.state.failureRecoveryAttempts??0)>Pq?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as dm}from"crypto";import Lq from"fast-json-patch";import{cloneDeep as Nq}from"lodash-es";async function HI(t){let e=t.failedResults,r=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:s,tracer:c}=t,{step:l}=n,{controller:u,logger:d}=o,p=l?.autohealingConfig,m=p?.restartBehavior??{type:"GO_TO_SECTION_START"},g=p?.attempts??1;for(let h=0;h<g;h++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=Nq(l.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:S}=await os(d,c,e.results,{numStepsWithScreenshots:4}),y=await u.runSectionAutohealing({results:S,errorMessage:e.terminalResult?.message,goal:l.description});f=Lq.applyPatch(f,y.patches).newDocument;let E=lr.fromSnapshot({snapshot:s,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await Dq({logger:d,controller:u,tracer:c,context:E,restartConfig:m,startingUrl:a});let T=await Os(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures,context:E},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(r.push(T.results),T.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:f},listResult:T,context:E},healingAttempts:r};e=T}return{healingAttempts:r}}async function Dq({logger:t,controller:e,tracer:r,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:dm(),type:"PRESET_ACTION",command:{id:dm(),type:"NAVIGATE",url:n.url}},s=await r.startStep({logger:t,step:a,attempt:1});await e.executePresetCommand(null,s,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:dm(),type:"PRESET_ACTION",command:{id:dm(),type:"NAVIGATE",url:i}},s=await r.startStep({logger:t,step:a,attempt:1});await e.executePresetCommand(null,s,a.command,o,!1);break}}}function GI(t,e){switch(t||(t="ON_FAILURE"),t){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&nb(e.command.type))}}async function jI(t){let{step:e,tracer:r}=t.sectionParams,{logger:n,controller:o,context:i}=t.fixtures,a=new Date,s=o.browser.url(),c=i.toObjectCopy(),l=await r.startSubSteps(),u=async()=>t.executeStepList({...t,listParams:{steps:e.steps,containerName:"section step list",tracer:l}}),d=e.autohealingConfig?await Os(t.work,u):await u(),p,m;if(d.status==="FAILED"&&e.autohealingConfig&&!t.work.state.autoHealingDisabled&&GI(e.autohealingConfig.trigger,d.terminalResult)){let h=await r.startSubSteps(),f=await HI({...t,startingContextSnapshot:c,startingUrl:s,failedResults:d,tracer:h});f.successfulHealing&&(p=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,t.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let g={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:p,healingAttempts:m};return mn({asyncTasks:t.work.asyncTasks,nestedResults:d.results,result:g,logger:n}),g}var Fq=60*60*1e3;async function Sn(t){let{results:e=[],containerName:r,steps:n,tracer:o}=t.listParams,{logger:i}=t.fixtures,a=o.getParentStepIdChain(),{fromStep:s,toStep:c}=t.inputs,l="SUCCESS",u,d=0;for(d;d<n.length;d++){let p=n[d];if(p.skipped)continue;if(t.work.fastForwardingToStep&&s){let y=JSON.stringify(a);if(p.id===s.fromStepId&&y===JSON.stringify(s.parentStepIdChain))t.work.fastForwardingToStep=!1;else if(!NA(p,a,s.fromStepId,s.parentStepIdChain))continue}let m=lo(p),g=0,h=1,f=Date.now();"retries"in p&&p.retries&&p.retries>0&&(h+=p.retries);let S;for(;g<h&&Date.now()-f<Fq;){g++,i.info({step:p,currentAttempt:g},`Executing step ${d+1}/${n.length} in ${r}: ${m}`);let y=Date.now(),{stepResult:E,status:T,failureRecoveryResults:v,shouldStopExecuting:w}=await Uq({attempt:g,params:t,step:p,i:d,steps:n,results:e,currentParentIdChain:a,fromStep:s,toStep:c,lastRetry:g===h});if(T==="FAILED"&&g<h){S=[...S??[],E],Date.now()-y<1e3&&await le(1e3-(Date.now()-y));continue}else e.push(E),S&&(E.previousAttempts=S);if(v&&e.push(...v),w)return l=T,u=E,{status:l,results:e,terminalResult:u};break}}return{status:l,results:e,terminalResult:u}}async function Uq({attempt:t,params:e,step:r,i:n,steps:o,results:i,currentParentIdChain:a,fromStep:s,toStep:c,lastRetry:l}){let{tracer:u}=e.listParams,{logger:d,context:p,controller:m,codeEvalTools:g,usageTracker:h}=e.fixtures,{orgId:f}=e.inputs,S=new Date,y=await u.startStep({logger:d,step:r,attempt:t}),E=kq(r),T=p.toRedactedDisplayCopy(),v=m.browser.url(),w=m.executeAbortController.signal;h.trackStepExecution(r);let C,_;switch(r.type){case"PRESET_ACTION":{C="Preset action",_=await na(r,async()=>await um({...e,presetParams:{tracer:y,step:r}}),w);break}case"AI_ACTION":{C="AI action",_=await na(r,()=>kI({...e,aiStepParams:{step:r,tracer:y},executeStepList:Sn}),w);break}case"AI_ACTION_DYNAMIC":{C="AI action",_=await na(r,()=>UI({...e,aiStepParams:{step:r,tracer:y},executeStepList:Sn}),w);break}case"RESOLVED_MODULE":{C=`Module (${r.name})`,_=await na(r,async()=>{let B=await II({orgId:f,step:r,context:p,logger:d,codeEvalTools:g,signal:w});return vy({...e,executeStepList:Sn,moduleParams:{step:r,resolvedInputs:B,tracer:y}})},w);break}case"CONDITIONAL":{C="Conditional step",_=await na(r,()=>NI({...e,conditionalParams:{step:r,tracer:y},executeStepList:Sn}),w);break}case"SECTION":{C="Section",_=await na(r,()=>jI({...e,sectionParams:{step:r,tracer:y},executeStepList:Sn}),w);break}default:return(W=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}_.beforeUrl=_.beforeUrl??v,_.beforeTestContext=T,r.envKey&&p.setVariable(r.envKey,_.data);let N=m.browser.url();p.setCurrentUrl(N),_.afterUrl=_.afterUrl??N,_.afterTestContext=p.toRedactedDisplayCopy(),await Bq({step:r,startedAt:S,stepTypeName:C,result:_,callbacks:e.callbacks,globalWorkRef:e.work,tracer:y,attempt:t});let U,j;if(l&&_.status==="FAILED"&&!e.work.state.failureRecoveryDisabled&&s?.fromStepId===void 0&&c?.toStepId===void 0){let B=await zI({...e,executeStepList:Sn,failureRecoveryParams:{failedStep:E,nextSteps:o.slice(n+1),results:i.concat(_),tracer:u}});B&&(B.type==="ATTEMPTED"?(U=B.result.results,j=B.status):B.type==="NOT_ELIGIBLE"&&(_.message=_.message?`${_.message} ${B.message}`:B.message),_.type==="PRESET_ACTION"&&(_.failureRecoveryStatus={type:B.type,message:B.message}))}return e.work.fastForwardingToStep&&s&&(s.fromStepId===r.id&&JSON.stringify(a)===JSON.stringify(s.parentStepIdChain)&&(e.work.fastForwardingToStep=!1),r.type==="RESOLVED_MODULE"&&ef(a,s.parentStepIdChain)&&(e.work.fastForwardingToStep=!1)),_.status!=="SUCCESS"&&j!=="SUCCESS"||m.closed?{shouldStopExecuting:!0,status:_.status,stepResult:_,failureRecoveryResults:U}:c&&r.id===c.toStepId&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)?(m.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:_,failureRecoveryResults:U}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:_,failureRecoveryResults:U}}async function Bq({stepTypeName:t,step:e,result:r,tracer:n,attempt:o,startedAt:i}){let a=t.toLowerCase(),s=t.charAt(0).toUpperCase()+t.slice(1);n.recordStepDuration({step:e,durationMs:Date.now()-i.getTime()});let c="";switch(r.status){case"SUCCESS":c=r.message??`${s} executed successfully.`;break;case"FAILED":c=r.message??`${s} failed.`;break;case"CANCELLED":c=r.message??`${s} cancelled.`;break;default:throw new Error(`Unexpected ${a} status: ${r.status}`)}await n.finish({step:r,message:c,output:Ou.parse(r),attempt:o})}var VI="MOMENTIC_RUN_ID",$I="FINAL_SCREENSHOT_URL";import{randomUUID as WI}from"crypto";async function qI({browser:t,signal:e}){let r=new Date;try{return await t.navigate({url:t.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:WI(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:r,finishedAt:new Date,results:[],command:{id:WI(),type:"NAVIGATE",url:t.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var pm=async t=>{let{orgId:e,runId:r,testMetadata:n,steps:o,beforeSteps:i,afterSteps:a}=t.inputs;t.fixtures.logger=t.fixtures.logger.child({orgId:e,runId:r,testId:n?.id});let{logger:s,controller:c}=t.fixtures,{onTestComplete:l,onTestSuccess:u,onTestFailure:d}=t.callbacks.test,p=n_(s);if(t.options.reinitializeBrowser){let g=await qI({browser:c.browser,signal:c.executeAbortController.signal});if(g.status!=="PASSED")return await l?.(),clearInterval(p?.interval),g}let m;try{return s.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:n?.labels,orgSettings:sR.parse(t.inputs.orgSettings)},`Starting run for Momentic test '${n?.name??"Unnamed test"}'`),m=await Hq(t),m}finally{s.info({status:m?.status,labels:n?.labels},"Momentic test final result"),clearInterval(p?.interval),await l?.(),m?.status==="PASSED"?await u?.({steps:o,beforeSteps:i,afterSteps:a}):m?.status==="FAILED"&&await d?.({steps:o,beforeSteps:i,afterSteps:a})}};function zq({beforeStatus:t,mainStatus:e,afterStatus:r}){return t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":r==="FAILED"?"FAILED":r==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var Hq=async t=>{let{tracer:e}=t.testParams,{fromStep:r,toStep:n,steps:o,beforeSteps:i,afterSteps:a}=t.inputs,{logger:s,controller:c,context:l,storage:u}=t.fixtures,{collectDebugData:d,disableHealing:p}=t.options;l.setCurrentUrl(c.browser.url());let m="test",g=o,h=[],f=p||r!==void 0||n!==void 0||void 0,S={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},y=!1;r?.fromStepId&&r.fromStepId===n?.toStepId?(m="filtered step",S.fastForwardingToStep=!0):r?.fromStepId?(m="partial steps list from step",S.fastForwardingToStep=!0):n?m="partial steps list until step":(m="entire test",y=!0);let E,T,v;if(y&&i&&i.length>0){let O=await KI(i,"beforeSteps",t);E=O.status,T=O.results,v=O.terminalResult?{...O.terminalResult,failureReason:"SetupFailureError"}:void 0,S.state.failureRecoveryAttempts=(S.state.failureRecoveryAttempts??0)+(O.failureRecoveryAttempts??0)}let w,C;if(E===void 0||E==="PASSED"){s.info({fromStep:r,toStep:n},`Starting execution of ${m}`);let O=await e.startMainStepList(),B=await Sn({...t,work:S,listParams:{steps:g,containerName:m,results:h,tracer:O}});w=B.status,C=B.terminalResult}let _,N,U;if(y&&a&&a.length>0){let O=await KI(a,"afterSteps",t);_=O.status,N=O.results,U=O.terminalResult?{...O.terminalResult,failureReason:"TeardownFailureError"}:void 0,S.state.failureRecoveryAttempts=(S.state.failureRecoveryAttempts??0)+(O.failureRecoveryAttempts??0)}let j=zq({beforeStatus:E,mainStatus:w,afterStatus:_});if(d&&Gq({tracer:e,work:S,controller:c,storage:u,context:l,logger:s,status:j}),await Promise.allSettled(S.asyncTasks),S.asyncTasks.push(Promise.resolve(t.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:T,afterResults:N}))),j==="FAILED"){let O=E==="FAILED"?v:void 0,B=_==="FAILED"?U:void 0;return{status:"FAILED",results:h,beforeResults:T,afterResults:N,failedStepResult:O??C??B}}else if(j==="CANCELLED")return{status:"CANCELLED",results:h,beforeResults:T,afterResults:N};return{status:"PASSED",failureRecoveryDetails:S.state.failureRecoveryAttempts?{attempts:S.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:T,afterResults:N}};async function KI(t,e,r){let n=r.fixtures.logger,o=e==="beforeSteps"?await r.testParams.tracer.startBeforeStepList():await r.testParams.tracer.startAfterStepList();n.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{}},a={...r.callbacks,test:{...r.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:s,results:c,terminalResult:l}=await Sn({...r,work:i,callbacks:a,listParams:{steps:t,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let u;return s==="SUCCESS"?u="PASSED":s==="CANCELLED"?u="CANCELLED":u="FAILED",{status:u,results:c,terminalResult:l,failureRecoveryAttempts:i.state.failureRecoveryAttempts}}function Gq({tracer:t,work:e,controller:r,storage:n,logger:o,context:i,status:a}){let s=r.browser,c=s.retrieveAndClearDebugData(),l=zA(c.logsPerPage);t.attachConsoleLogs({logger:o,logs:l}),a!=="PASSED"&&a!=="SUCCESS"&&(t.attachBrowserCrashDump({crashReportDirFetcher:()=>s.browserCrashDumpDir,logger:o}),e.asyncTasks.push((async()=>{try{let u=await s.screenshot({quality:75}),d=await aI({codePath:"test-complete-final",storage:n,screenshotBuff:u,logger:o}),p=await $(s.html(),{milliseconds:2e3});i.setVariable($I,d),o.debug({finalPageHtml:p.slice(0,1e4)},"Final page state HTML"),o.debug({finalScreenshotUrl:d},"Uploaded final screenshot URL")}catch{}})()))}async function mm({settings:t,customHeaders:e,envVariables:r,envName:n,testName:o,baseUrl:i,logger:a,localTools:s,orgId:c}){let l=Nu.parse(t);e&&(l.extraHeaders={...l.extraHeaders,...e});let u=new lr({baseUrl:i,envName:n,testName:o,variablesFromEnvironment:r,currentUrl:i});await Xd({obj:l,context:u,bannedKeys:[],allowList:PT,localTools:s,logger:a,orgId:c});try{return Nu.parse(l)}catch(d){throw new M("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}async function hm({orgId:t,testName:e,envName:r,baseEnvVariables:n,parameters:o,logger:i,localTools:a}){if(!o||o.length===0)return{...n};let s={...n};return await Promise.all(o.map(async c=>{let l=await pr({orgId:t,s:c.defaultValue,context:lr.dummyContext(e,r,s),logger:i,localTools:a});s[c.name]=l})),s}import{cloneDeep as qq}from"lodash-es";import{cloneDeep as jq}from"lodash-es";var Vq={showOverlay:!1},gm=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:r,cleanup:n,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:r,cleanup:n,clientIp:o,browserBehavior:jq(Vq),socket:a}),i}removeSession(e,r){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(a){r.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){r.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}};function YI(t,e,r,n){let o=Date.now(),i=Date.now(),a,s,c,l,u=!1,d=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let S=c;c=void 0;let y=h.url(),E=f.toEditorDisplayCopy();JSON.stringify(E)===JSON.stringify(a)&&y===l&&o>i||(t.emit("browserState",{logsPerPage:S?.logsPerPage,viewport:h.getViewport(),url:y,iframeSrcUrls:s??[],context:E,isInPageLoad:h.isInPageLoad}),o=Date.now()),l=y,a=E}catch(S){if(!t.connected)return;let y=S instanceof Error?S.message:`${S}`;if(y.includes("Frame was detached")||y.includes("Not attached to an active page")||y.includes("browser has been closed")||y.includes("UserInfrastructureError"))return;r.error({err:S,sessionId:e},"Error grabbing browser state")}},p=setInterval(()=>{let h=n.getSession(e),f=h?.controller?.browser;if(!f||f.closed){r.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(p);return}d(f,h.context)},1e3),m=(h,f)=>!!(JSON.stringify(h)!==JSON.stringify(s)||f.logsPerPage.some(S=>S.length>0)),g=setInterval(async()=>{let f=n.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(g);return}else if(u)return;u=!0;try{let S=await f.getAllFrameUrls(),y=f.retrieveAndClearDebugData();m(S,y)&&(s=S,c=y,i=Date.now())}catch(S){r.warn({err:S},"Failed to fetch extended details")}finally{u=!1}},2500);return{timers:[p,g]}}var $q=3;async function XI({socket:t,logger:e,storageFactory:r,uploadedFileStorage:n,visualDiffScreenshotStorage:o,devicePixelRatio:i,generatorFactory:a,enricherFactory:s,authorization:c,settingsFactory:l,getOrgId:u,branchGetter:d,globalE2eStateManager:p}){let m=t.id,g=t.handshake.query.testId;if(!g)throw new Error("Socket connection request is missing testId");let h=await u({type:"e2e",testId:g}),f=await d?.();e=e.child({testId:g,orgId:h,sessionId:m,branch:f});let S=await a(h,e),y=await s(h,e),E=await l(h,e),T=await r(h),{testMetadata:v,baseUrl:w,envName:C,browserConfig:_,aiSettings:N,environmentVariables:U,localCodeEvalTools:j}=await oa({testId:g,orgId:h,logger:e,storage:T,authorization:c,settings:E}),O=p.getSession(m);if(O)return e.info("Associating connection with existing session (likely reconnect)"),await O.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:m,orgId:h,testId:g};let B=t.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:B,event:"connect",args:t.handshake.query},"Websocket event (connect)"),B&&p.getCurrentConnectionsByIp(B)>=$q)throw e.error({clientIp:B,sessions:p.getCurrentSessionsByIp(),...t.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(B);try{await Wq({socket:t,baseUrl:w,envName:C,testMetadata:v,orgId:h,sessionId:m,logger:e,environmentVariables:U,clientIp:B,devicePixelRatio:i,storage:T,uploadedFileStorage:n,visualDiffScreenshotStorage:o,localCodeEvalTools:j,generator:S,enricher:y,browserConfig:_,aiSettings:N,globalE2eStateManager:p})}catch(W){throw e.warn({err:W},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(B),W}return{type:"e2e",sessionId:m,testId:g,orgId:h}}async function Wq({socket:t,baseUrl:e,envName:r,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:s,storage:c,uploadedFileStorage:l,visualDiffScreenshotStorage:u,localCodeEvalTools:d,generator:p,environmentVariables:m,browserConfig:g,aiSettings:h,clientIp:f,enricher:S,globalE2eStateManager:y}){let E={viewport:o.advanced?.viewport??Kt,locale:o.advanced?.locale??Io,timezoneId:o.advanced?.timezone??Oo,geolocation:o.advanced?.geolocation??Lo,colorScheme:o.advanced?.colorScheme};n&&(E.deviceScaleFactor=n);let T=o.id,v=await mm({settings:g,orgId:i,baseUrl:e,envName:r,testName:o.name,localTools:d,envVariables:m,logger:s,customHeaders:void 0});s=s.child({orgId:i,sessionId:a,testId:T});let w=await qr.init({baseUrl:e,userBrowserSettings:v,enricher:S,storage:c,logger:s,contextArgs:E,iconKnowledgeBase:null,callbacks:{onTabsChange:(j,O)=>{t.emit("tabs",{tabs:j,activeTab:O})},onScreencastFrame:(j,O)=>{let B=t;wr&&(B=t.compress(!0)),B.emit("screenshot",{buffer:j},()=>{O()})},onSvgsCollected:j=>{t.emit("newIconDetected",{numIcons:j.newSvgs.length}),c.saveNewIcons(j,s)},onNetworkLogs:j=>{t.emit("networkLogs",{harEntries:j})}}});await w.navigate({url:e,initialNavigation:!0});let C=new oi({browser:w,generator:p,logger:s,orgId:i,options:{scratchPadId:void 0,slowMoMs:v.slowMoMs,autoFollowNewTabs:v.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering},storage:c,localCodeEvalTools:d,uploadedFileStorage:l,visualDiffScreenshotStorage:u}),_=YI(t,a,s,y),N=async()=>{_.timers.forEach(j=>clearInterval(j))},U=new lr({baseUrl:e,testName:o.name,currentUrl:C.browser.url(),variablesFromEnvironment:m,envName:r});if(!t.connected)throw await w.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");t.emit("session",{url:e,userAgent:qr.USER_AGENT,viewport:C.browser.getViewport(),sessionId:a}),y.registerSession({controller:C,context:U,sessionId:a,cleanup:N,clientIp:f,socket:t})}async function oa({testId:t,orgId:e,logger:r,storage:n,authorization:o,settings:i}){let a=await n.fetchTestMetadata(t,r);if(!a)throw new Error(`Test metadata could not found for test ${t}`);let s;o?.type==="API_KEY"&&(s=new On({httpClient:new zt({...o,logger:r,mode:"interactive"}),fakerSeed:void 0}));let c=a.envs?.find(h=>h.default),l;c&&(l=await n.fetchEnvironment(c.name,r));let u=l&&"browser"in l?l.browser:void 0,d={...i.browser,...u,...a.advanced};d.browserType=xu({browserType:d.browserType,orgDefaultBrowserType:i.browser?.defaultBrowserType});let p=a.baseUrl||l?.variables?.[Rt];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let m={...l?.variables};m=await hm({orgId:e,testName:a.name,envName:l?.name,baseEnvVariables:m,parameters:a.parameters,logger:r,localTools:s});let g={...i.ai,...a.advanced};return{localCodeEvalTools:s,baseUrl:p,envName:l?.name,testName:a.name,browserConfig:d,environmentVariables:m,testMetadata:a,aiSettings:g}}var Ay=class{parentTracer=null;socket;step;orgId;constructor({step:e,socket:r,parentTracer:n,orgId:o}){this.socket=r,this.parentTracer=n,this.step=e,this.orgId=o}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}recordStepDuration(e){let r=e.step.type!=="PRESET_ACTION"?e.step.type:e.step.command.type;kt.distribution("test_step_duration",e.durationMs,[`type:${r}`,"platform:browser","executor:editor",`orgId:${this.orgId}`])}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new fo({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},fo=class{stepFrequenciesByType={};parentTracer;parentStep;socket;orgId;recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,r]of Object.entries(this.stepFrequenciesByType))kt.increment("test_step_execution",r,[`type:${e}`,"platform:browser","executor:editor",`orgId:${this.orgId}`])}constructor({parentStep:e,socket:r,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=r,this.orgId=o}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.recordStepStat(e.step),this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Ay({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async finish(){this.sendFinalizedStepStats()}},fm=class{constructor(e,r,n,o){this.socket=e;this.storage=r;this.orgId=n;this.testId=o}children=[];loggerBindings;setActiveVideo(){}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}onNetworkPage(){}onNetworkLogs(){}attachConsoleLogs(){}attachBrowserCrashDump(){}async finish(){this.socket.emit("finished"),await Promise.all(this.children.map(e=>e.finish()))}async startBeforeStepList(){let e=new fo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startMainStepList(){let e=new fo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startAfterStepList(){let e=new fo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}};var wy={currentlyExecutingRequests:{}},Kq=t=>async(e,r)=>{let{testId:n,orgId:o}=t.metadata,i=await t.settingsFactory(o,t.logger),a=await t.storageFactory(o),s,c=await oa({testId:n,orgId:o,logger:t.logger,storage:a,authorization:t.authorization,settings:i}),l=`${n}|${c.baseUrl}`;try{let u=wy.currentlyExecutingRequests[l]??0;wy.currentlyExecutingRequests[l]=u+1,s=await Yq({...t,...e,...c,done:r})}finally{t.logger.info({result:s,sessionId:t.metadata.sessionId},"Test execution complete"),wy.currentlyExecutingRequests[l]--}},Yq=async({socket:t,steps:e,baseUrl:r,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storageFactory:s,aiSettings:c,browserConfig:l,metadata:u,logger:d,envName:p,testName:m,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:S,globalE2eStateManager:y})=>{let{testId:E,sessionId:T,orgId:v}=u,w=T,C=y.getSession(T);if(!C)throw new Error("No active session found");let{controller:_,context:N}=C;_.setOpen(),d=d.child({testId:E,orgId:v,sessionId:T,runId:w}),d.info({steps:e.map(se=>`${se.type}${"command"in se?` - ${se.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:p,testName:m,baseUrl:r,context:N,browserConfig:l,aiSettings:c},"Socket execution parameters");let U=g??{},j=async()=>{o&&(await _.browser.reset({newUrl:r}),N.reset({baseUrl:r,currentUrl:_.browser.url(),variablesFromEnvironment:U,envName:p,testName:m}))},O=await s(v),B=await S(v),W=async()=>{let se=Date.now();try{await B.resolveStepCacheEntries({schemaVersion:n.schemaVersion,testId:E,stepLists:{steps:e},logger:d})}catch(qe){d.error({err:qe},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}finally{kt.distribution("cache-resolution",Date.now()-se,["executor:editor"])}};try{await Wl({promiseGenerator:async()=>Promise.all([j(),W()]),signal:_.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),_.setOpen()}catch(se){if(t.emit("finished"),se.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${se}`)}let q=qq(e),ve={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},Y={orgId:v,runId:w,testMetadata:n,steps:e,fromStep:a,toStep:i,orgSettings:{ai:c,browser:l}},st={controller:_,context:N,storage:O,codeEvalTools:h,usageTracker:new Wa,logger:d},Le={test:{},step:{onDynamicAIActionStatusUpdateEvent:se=>{t.emit("dynamicCommandStatusUpdate",se)},onDynamicAIActionEvaluatingEvent:se=>{t.emit("dynamicCommandEvaluating",se)},onDynamicCommandGenerated:se=>{t.emit("dynamicCommandGenerated",se)},onDynamicCommandExecuted:se=>{t.emit("dynamicCommandExecuted",se)}}},gt=new fm(t,O,v,E),rr=await pm({fixtures:st,options:ve,callbacks:Le,inputs:Y,testParams:{tracer:gt}}),Ge={logger:d,cacheStorage:B,orgId:v,testId:E,originalStepsWithCaches:{steps:q},updatedStepsWithCaches:{steps:e}};return rr?.status==="PASSED"?await Md(Ge):rr?.status==="FAILED"&&await Pd(Ge),await gt.finish(),f?.(rr),rr.status};var JI={event:"execute",createHandler:Kq};import{cloneDeep as Xq}from"lodash-es";var Jq=t=>async({command:e},r)=>{let{logger:n,generatorFactory:o,metadata:i}=t,a=Xq(e),s=ww(a);if(s.category!=="NO_DESCRIPTION_PROVIDED"){if(s.category!=="NONE"){r?.({result:s});return}"cache"in a&&(a.cache=void 0);try{let l=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});r?.({result:l})}catch(c){n.error({event:"lint",err:c},"Failed to lint step"),r?.({result:void 0})}}},QI={event:"lintStep",createHandler:Jq};var Qq=({metadata:t,logger:e,storageFactory:r,globalE2eStateManager:n})=>{let{sessionId:o,orgId:i}=t;return async(a,s)=>{let{description:c,command:l,testMetadata:u,returnScreenshot:d}=a;e.info({params:a},`Locate handler called - ${c}`);let p=n.getSession(o);if(!p)throw new Error("No active session found");let{controller:m,context:g}=p;m.setOpen();let h=await r(i),f=_i.parse(u.advanced??{}),S={},y;if(c){if("useSelector"in l&&l.useSelector)try{let E=await m.locateElementWithSelector(c,"iframeUrl"in l?l.iframeUrl:void 0);y=E.resolution.locator,S={target:E.target,thoughts:E.thoughts}}catch(E){e.warn({err:E},"Failed resolving target with selector"),s({err:`Failed locating element: ${E.message}`,decisions:E instanceof kr?E.decisions:void 0});return}else try{let E=await m.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Ri(l),iframeUrl:"iframeUrl"in l?l.iframeUrl:void 0,memory:"cache"in l&&l.cache&&"target"in l.cache&&nu(l.cache.target.memory)?l.cache.target.memory:void 0,logger:e});S={target:E.target,thoughts:E.thoughts},y=E.resolution.locator}catch(E){(async()=>{try{let T=await m.browser.getCondensedHtml({skipWait:!0});e.warn({err:E,html:T.slice(0,1e5)},"Failed locating element with AI")}catch(T){e.warn({err:T},"Failed grabbing HTML after trying to locate element with AI")}})(),s({err:`${E.message}`});return}if(l.type==="SELECT_OPTION"&&y)try{S.options=await m.browser.getSelectOptions(y)}catch(E){e.warn({err:E},"Failed getting select options"),s({err:`Failed getting select options: ${E.message}`});return}e.info({result:S},"Locate handler result")}if(d)try{let{buffer:E,width:T,height:v}=await m.screenshotWithDimensions({clearHighlights:!0,locator:y}),w=await h.uploadScreenshot(E);S.screenshot={data:w,width:T,height:v},e.info({width:T,height:v},"Captured screenshot during locate")}catch(E){e.error({err:E},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${E.message}`});return}if(s({result:S}),y)try{await Promise.all([m.browser.scrollIntoViewIfNeeded(y),m.browser.highlight(y)])}catch(E){e.warn({err:E},"Error highlighting element, continuing...")}}},ZI={event:"locate",createHandler:Qq};var Zq=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async({event:o,percentX:i,percentY:a})=>{let s=r.getSession(n);if(!s)throw new Error("No active session found");let c=s.controller.browser;if(c.closed||c.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await c.clickMouseFromPositionPercentages(o,i,a)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode")}}},eO={event:"mouseClickEvent",createHandler:Zq};var eK=({metadata:t,generatorFactory:e,logger:r,socket:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:s}=t;return async({stepId:c,parentStepIdChain:l,attribute:u})=>{let d=o.getSession(i);if(!d)throw new Error("No active session found");let{controller:p}=d,m=await e(a,r);p.setOpen(),d.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{d.browserBehavior.showOverlay=!1,await p.stopRecordMode()}catch(S){r.warn({err:S},"Failed to stop record mode in target click socket handler")}},{once:!0});let h=!1,f=(S,y)=>{y.type!=="PRESET_ACTION"||y.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:S,stepId:c,parentStepIdChain:l,command:y.command,attribute:u}),g.abort(),h=!0)};setTimeout(()=>{h||(g.abort(),n.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:c,parentStepIdChain:l,attribute:u}))},1e4),await p.startRecordMode({params:{generator:m,logger:r,testId:s,orgId:a,callbacks:{onActionReceived:S=>f("clickReceived",S),onStepRecorded:S=>f("descriptionGenerated",S)}},abortController:g,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:l,attribute:u})}},tO={event:"recordTargetClick",createHandler:eK};var tK=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async({key:o})=>{let i=r.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyDown(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:n,err:s},"Browser is closed, ignoring key down socket event error");return}throw s}}},rO={event:"keyDownEvent",createHandler:tK};var rK=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async({key:o})=>{let i=r.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyUp(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:n,err:s},"Browser is closed, ignoring key up socket event error");return}throw s}}},nO={event:"keyUpEvent",createHandler:rK};var nK=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t,o,i=0,a=(l,u)=>{let d=async()=>{o=void 0};clearTimeout(o),o=setTimeout(d,Math.min(1e3,250*(i+1)))},s,c=0;return async l=>{let u=r.getSession(n);if(!u)throw new Error("No active session found");let{controller:d,browserBehavior:p}=u,m=d.browser;if(m.closed||m.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(l.event==="scroll"){let g=await m.scrollFromPositionPercentages(l.percentX,l.percentY,s?.x??0,s?.y??0),h=u.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}p.showOverlay&&a(m,l);try{let g=await m.moveMouseFromPositionPercentages(l.percentX,l.percentY);c=0,s=g}catch(g){c++,c%5===0&&e.warn({err:g,mouseErrors:c},"Error in socket mouse move handler")}}},oO={event:"mouseMoveEvent",createHandler:nK};var oK=({metadata:t,generatorFactory:e,socket:r,logger:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:s}=t;return async({stepId:c})=>{let l=o.getSession(i);if(!l)throw new Error("No active session found");let{controller:u,browserBehavior:d}=l,p=await e(a,n);n.info("Starting cloud recording");let m=new AbortController,g=await u.startRecordMode({params:{generator:p,logger:n,testId:s,orgId:a,callbacks:{onActionReceived:(h,f)=>{r.emit("stepRecorded",{stepId:c,step:h,offset:f})},onStepRecorded:(h,f)=>{r.emit("stepRecorded",{stepId:c,step:h,offset:f})}}},abortController:m,isClickToRecord:!1});d.recordingState={transformer:g}}},iO={event:"recordingStart",createHandler:oK};var iK=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async()=>{let o=r.getSession(n);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},aO={event:"recordingStop",createHandler:iK};var aK=({socket:t,metadata:e,logger:r,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async(s,c)=>{let{testId:l,sessionId:u,orgId:d}=e;r.info({testId:l,sessionId:u},"Refresh event received");let p=await i(d,r),m=await n(d),{baseUrl:g}=await oa({testId:l,orgId:d,logger:r,storage:m,authorization:o,settings:p}),h=a.getSession(u);if(!h){t.emit("error",{message:"No session to refresh"});return}let{controller:f}=h;f.setOpen(),await f.browser.refresh();let S=f.browser.getViewport();r.info({baseUrl:g,viewport:S},`Session refreshed for test ${l} at ${g}`),c()},sO={event:"refresh",createHandler:aK};var sK=({socket:t,metadata:e,logger:r,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async()=>{let{testId:s,sessionId:c,orgId:l}=e;r.info({testId:s,sessionId:c},"Reset event received");let u=await i(l,r),d=await n(l),{baseUrl:p,envName:m,testName:g,environmentVariables:h}=await oa({testId:s,orgId:l,logger:r,storage:d,authorization:o,settings:u}),f=a.getSession(c);if(!f){t.emit("error",{message:"No session to reset"});return}let{controller:S,context:y}=f;await S.browser.reset({newUrl:p});let E=S.browser.baseUrl;y.reset({baseUrl:E,currentUrl:S.browser.url(),variablesFromEnvironment:h,envName:m,testName:g});let T=S.browser.getViewport(),v=qr.USER_AGENT;r.info({baseUrl:p,viewport:T},`Session reset for test ${s} at ${E}`),t.emit("session",{url:E,userAgent:v,viewport:T,sessionId:c})},lO={event:"reset",createHandler:sK};var lK=({metadata:t,globalE2eStateManager:e})=>{let{sessionId:r}=t;return async({url:n})=>{let o=e.getSession(r);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:n})}},cO={event:"switchTab",createHandler:lK};async function uO(t){return XI(t)}var dO=[EC,JI,ZI,lO,sO,fC,cO,QI,tO,iO,aO,oO,eO,rO,nO,yC,SC];var pO=t=>{let{logger:e}=t,r=new cK(t.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return r.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await uO({...t,socket:n,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}dO.forEach(i=>uK(i,{...t,socket:n,metadata:o,logger:e}))}),r},uK=(t,e)=>{let r=t.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(t.event)||e.logger.debug({...e.metadata,event:t.event},`Websocket event (${t.event})`);let i=a=>{e.logger.error({event:t.event,type:"websocket",err:a instanceof Error?a:new Error(`${a}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:a instanceof Error?a.message:`${a}`})};try{let a=r.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(t.event,n)};import{Router as gK}from"express";import{Router as pK}from"express";import Lc from"fs";import Oc from"path";import{v4 as mK}from"uuid";import hK from"yaml";import{hostname as dK}from"os";var Ic="2.29.4",nt=Xa({app:"desktop-server",hostname:dK(),disableConsoleLogs:!0}).child({cliVersion:Ic});(async()=>{try{let t=await po(nt);t.gitBranchName&&nt.addBinding("branch",t.gitBranchName)}catch{}})();var Ls=pK();async function Cy(t){return(await Gd(t,nt)).map(n=>{let o=t.modules[n.moduleId];if(!o){b.warn(`Found a dangling module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}Ls.get("/",Oe(async(t,e)=>{let r=me(),n=await ee(r),o=await Cy(n);e.status(200).json(o)}));Ls.post("/",Oe(async(t,e)=>{let r;try{r=qv.parse(t.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{Mo(r.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let n=me(),o=(await ee(n)).modules;if(Object.values(o).find(s=>s.name===r.name)){e.status(400).send(`A module with the name "${r.name}" already exists. Please choose a different name.`);return}let i=Oc.join(n.rootDir,r.folderPath??"");if(!Lc.existsSync(i)||!Lc.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Hd({...r,folder:i,project:n});e.status(201).json(a)}));Ls.get("/:moduleId",Oe(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r=await ee(me()),n=r.modules[t.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await dn(n,r,b);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ls.post("/:moduleId/duplicate",Oe(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=Wv.parse(t.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Mo(r.name)}catch(h){e.status(400).json({error:h.message});return}let n=me(),o=await ee(n),i=o.modules[t.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===r.name)){e.status(400).send(`A module with the name "${r.name}" already exists. Please choose a different name.`);return}let a=await dn(i,o,b),s=Oc.join(n.rootDir,Oc.dirname(i.relativePath));if(!Lc.existsSync(s)||!Lc.statSync(s).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let c=ze(r.name),l=Oc.join(s,`${c}.module.yaml`),u=mK(),{stepsToSave:d}=await it({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:xt()}}),p={fileType:Se.MODULE,schemaVersion:_e,moduleId:u,name:r.name,description:"",enabled:!0,steps:d.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced},m=hK.stringify(p);Lc.writeFileSync(l,m,"utf-8");let g={relativeFilePath:Oc.relative(n.rootDir,l)};e.status(201).json(g)}));Ls.patch("/:moduleId/metadata",Oe(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=Kv.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=me(),o=await ee(n);Vw({moduleId:t.params.moduleId,content:r,momenticFiles:o,logger:b,project:n}),e.status(201).json({message:"ok"})}));var mO=Ls;var hO=gK();hO.get("/",Oe(async(t,e)=>{let r=me(),n=await ee(r),o=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),s=await Cy(n),c={labels:i,tests:a,modules:s};e.status(200).json(c)}));var gO=hO;import{Router as fK}from"express";var xy=fK();xy.get("/",Oe((t,e)=>{let r=jd(me(),nt);e.status(200).json(r)}));xy.get("/names",Oe((t,e)=>{let n=me().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var fO=xy;import{Router as SK}from"express";var SO=SK();SO.get("/",Oe((t,e)=>{let r={userId:jo(),orgId:xt(),cliVersion:Ic??"0.0.0"};e.status(200).json(r)}));var yO=SO;import{StreamableHTTPServerTransport as j2}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as V2}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as $2}from"crypto";import{Router as W2}from"express";import{McpServer as H2}from"@modelcontextprotocol/sdk/server/mcp.js";import{SSEServerTransport as G2}from"@modelcontextprotocol/sdk/server/sse.js";import{streamObject as vK}from"ai";import bm from"dedent";import RK from"path";import{z as ii}from"zod";import{tool as yK}from"ai";import{z as EK}from"zod";var EO=(t,e)=>({builder:n=>yK({description:t.schema.description,inputSchema:EK.object(t.schema.inputSchema),execute:async o=>{let i=e(n);n.logger.info({input:o},`Executing tool ${t.schema.name}`);try{await t.handle(n,o,i,void 0)}catch(s){i.addError(String(s))}let a=await i.serialize();return a.isError?n.logger.error({toolName:t.schema.name,input:o,err:a.content.map(s=>s.text).join(`
4377
+ ${w.feedback}`,p.status="FAILED",l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:p.message}),p;N&&l.onDynamicAIActionEvaluatingEvent?.({stepId:N,status:"FAILED",message:w.feedback});break}case"IMPOSSIBLE":return p.message=`Our AI evaluator determined this task cannot be achieved: ${C}`,p.status="FAILED",l.onDynamicAIActionEvaluatingEvent?.({stepId:N??e.id,status:"FAILED",message:p.message}),p}let U=setTimeout(()=>{l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:S,lastActionHint:E},`Generating new sub-command ${S} within AI action`);let j,O;try{({command:j,reasoning:O}=await i.promptToCommand({goal:m,history:f,startingScreenshot:h,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:E,langfuseSessionId:u})),d.info({command:j,reasoning:O},"Got proposed command")}finally{clearTimeout(U)}if(j.type==="FAILURE")return clearTimeout(U),p.status="FAILED",p.message=`Our AI agent determined that no supported actions can fulfill the goals: ${O}`,p;let B={id:Ry(),type:"PRESET_ACTION",command:j},W={substepIndex:S+1,message:O||"Generated new command."};l.onDynamicCommandGenerated?.({...W,step:B,parentStepId:e.id}),d.info({commandId:j.id},`Executing sub-command ${S} within AI step: ${ao(j)}`);let q=await r.startSubSteps(),Y=(await t.executeStepList({...t,options:{...t.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[B],tracer:q}})).results[0];l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let st=await i.browser.screenshot({clearHighlights:!0,retries:1});p.results.push(Y),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${st.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:ao(j),elementInteracted:Y.results[0]?.elementInteracted,thoughts:O});let Le={substepIndex:S,output:{...Y,message:Y.message??"Successfully executed preset action."},step:B,parentStepId:e.id};if(l.onDynamicCommandExecuted?.(Le),await r.finish({output:Ou.parse(Y),step:Y,message:Y.message,attempt:1}),Y.status==="FAILED")if(p.status="FAILED",p.message=Y.message,y<3)y++,T=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${Y.message}`;else return p;else if(Y.status==="CANCELLED")return p.status="CANCELLED",p.message=Y.message,p;S++}};import{randomUUID as Mq}from"crypto";var Pq=3;async function zI(t){let{logger:e}=t.fixtures,{results:r}=t.failureRecoveryParams,n=r[r.length-1],o=Oq(t.work,n);if(o)return e.info({failedResult:n,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};e.info({failedResult:n},"Attempting failure recovery"),t.work.state.failureRecoveryAttempts=(t.work.state.failureRecoveryAttempts??0)+1;try{return await Iq(t)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function Iq(t){let{fixtures:e,work:r,failureRecoveryParams:n}=t,{controller:o,logger:i}=e,{testMetadata:a}=t.inputs,{results:s,failedStep:c,nextSteps:l,tracer:u}=n;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(r.asyncTasks??[]);let d=o.browser.url(),p=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,m=(await o.browser.getBrowserState({})).serialize(),{results:g}=await os(i,u,s,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=l.map(_=>lo(_)),f=a?.description?.trim(),S=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:y,thoughts:E,instructions:T}=await o.getFailureRecoveryPlan({currentUrl:d,currentScreenshot:p,failedResults:g,currentPageState:m,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:S||void 0});if(y!=="RECOVERABLE")return i.info({scenario:y,thoughts:E,instructions:T},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${E}`};if(!T)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let v={id:Mq(),type:"AI_ACTION_DYNAMIC",text:T},w=await Os(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures},listParams:{steps:[v,c],containerName:"AI-recovered step list",tracer:u}})),C=w.results[0];if(C&&C.type==="AI_ACTION_DYNAMIC")if(Ed({results:w.results,onPresetAction:_=>{_.aiSuggested=!0},onSimpleStepContainer:_=>{_.aiSuggested=!0}}),w.status==="SUCCESS"){let _=`The following steps were automatically executed by the failure recovery agent. Analysis: ${E}`;return C.message=_,kt.increment("test_event",1,["name:failure_recovery_success",`orgId:${t.inputs.orgId}`]),i.info({thoughts:E},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:w,message:_}}else{kt.increment("test_event",1,["name:failure_recovery_failure",`orgId:${t.inputs.orgId}`]);let _=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${E}`;return C.message=_,i.info({thoughts:E,aiActionResult:C},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:w,message:_}}return null}function Oq(t,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let r=e.message;return r?r.includes("AbortError:")?"The user aborted the test":Ub.some(n=>r.includes(n))?"The failed step is an irrecoverable configuration error":(t.state.failureRecoveryAttempts??0)>Pq?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as dm}from"crypto";import Lq from"fast-json-patch";import{cloneDeep as Nq}from"lodash-es";async function HI(t){let e=t.failedResults,r=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:s,tracer:c}=t,{step:l}=n,{controller:u,logger:d}=o,p=l?.autohealingConfig,m=p?.restartBehavior??{type:"GO_TO_SECTION_START"},g=p?.attempts??1;for(let h=0;h<g;h++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=Nq(l.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:S}=await os(d,c,e.results,{numStepsWithScreenshots:4}),y=await u.runSectionAutohealing({results:S,errorMessage:e.terminalResult?.message,goal:l.description});f=Lq.applyPatch(f,y.patches).newDocument;let E=lr.fromSnapshot({snapshot:s,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await Dq({logger:d,controller:u,tracer:c,context:E,restartConfig:m,startingUrl:a});let T=await Os(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures,context:E},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(r.push(T.results),T.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:f},listResult:T,context:E},healingAttempts:r};e=T}return{healingAttempts:r}}async function Dq({logger:t,controller:e,tracer:r,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:dm(),type:"PRESET_ACTION",command:{id:dm(),type:"NAVIGATE",url:n.url}},s=await r.startStep({logger:t,step:a,attempt:1});await e.executePresetCommand(null,s,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:dm(),type:"PRESET_ACTION",command:{id:dm(),type:"NAVIGATE",url:i}},s=await r.startStep({logger:t,step:a,attempt:1});await e.executePresetCommand(null,s,a.command,o,!1);break}}}function GI(t,e){switch(t||(t="ON_FAILURE"),t){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&nb(e.command.type))}}async function jI(t){let{step:e,tracer:r}=t.sectionParams,{logger:n,controller:o,context:i}=t.fixtures,a=new Date,s=o.browser.url(),c=i.toObjectCopy(),l=await r.startSubSteps(),u=async()=>t.executeStepList({...t,listParams:{steps:e.steps,containerName:"section step list",tracer:l}}),d=e.autohealingConfig?await Os(t.work,u):await u(),p,m;if(d.status==="FAILED"&&e.autohealingConfig&&!t.work.state.autoHealingDisabled&&GI(e.autohealingConfig.trigger,d.terminalResult)){let h=await r.startSubSteps(),f=await HI({...t,startingContextSnapshot:c,startingUrl:s,failedResults:d,tracer:h});f.successfulHealing&&(p=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,t.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let g={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:p,healingAttempts:m};return mn({asyncTasks:t.work.asyncTasks,nestedResults:d.results,result:g,logger:n}),g}var Fq=60*60*1e3;async function Sn(t){let{results:e=[],containerName:r,steps:n,tracer:o}=t.listParams,{logger:i}=t.fixtures,a=o.getParentStepIdChain(),{fromStep:s,toStep:c}=t.inputs,l="SUCCESS",u,d=0;for(d;d<n.length;d++){let p=n[d];if(p.skipped)continue;if(t.work.fastForwardingToStep&&s){let y=JSON.stringify(a);if(p.id===s.fromStepId&&y===JSON.stringify(s.parentStepIdChain))t.work.fastForwardingToStep=!1;else if(!NA(p,a,s.fromStepId,s.parentStepIdChain))continue}let m=lo(p),g=0,h=1,f=Date.now();"retries"in p&&p.retries&&p.retries>0&&(h+=p.retries);let S;for(;g<h&&Date.now()-f<Fq;){g++,i.info({step:p,currentAttempt:g},`Executing step ${d+1}/${n.length} in ${r}: ${m}`);let y=Date.now(),{stepResult:E,status:T,failureRecoveryResults:v,shouldStopExecuting:w}=await Uq({attempt:g,params:t,step:p,i:d,steps:n,results:e,currentParentIdChain:a,fromStep:s,toStep:c,lastRetry:g===h});if(T==="FAILED"&&g<h){S=[...S??[],E],Date.now()-y<1e3&&await le(1e3-(Date.now()-y));continue}else e.push(E),S&&(E.previousAttempts=S);if(v&&e.push(...v),w)return l=T,u=E,{status:l,results:e,terminalResult:u};break}}return{status:l,results:e,terminalResult:u}}async function Uq({attempt:t,params:e,step:r,i:n,steps:o,results:i,currentParentIdChain:a,fromStep:s,toStep:c,lastRetry:l}){let{tracer:u}=e.listParams,{logger:d,context:p,controller:m,codeEvalTools:g,usageTracker:h}=e.fixtures,{orgId:f}=e.inputs,S=new Date,y=await u.startStep({logger:d,step:r,attempt:t}),E=kq(r),T=p.toRedactedDisplayCopy(),v=m.browser.url(),w=m.executeAbortController.signal;h.trackStepExecution(r);let C,_;switch(r.type){case"PRESET_ACTION":{C="Preset action",_=await na(r,async()=>await um({...e,presetParams:{tracer:y,step:r}}),w);break}case"AI_ACTION":{C="AI action",_=await na(r,()=>kI({...e,aiStepParams:{step:r,tracer:y},executeStepList:Sn}),w);break}case"AI_ACTION_DYNAMIC":{C="AI action",_=await na(r,()=>UI({...e,aiStepParams:{step:r,tracer:y},executeStepList:Sn}),w);break}case"RESOLVED_MODULE":{C=`Module (${r.name})`,_=await na(r,async()=>{let B=await II({orgId:f,step:r,context:p,logger:d,codeEvalTools:g,signal:w});return vy({...e,executeStepList:Sn,moduleParams:{step:r,resolvedInputs:B,tracer:y}})},w);break}case"CONDITIONAL":{C="Conditional step",_=await na(r,()=>NI({...e,conditionalParams:{step:r,tracer:y},executeStepList:Sn}),w);break}case"SECTION":{C="Section",_=await na(r,()=>jI({...e,sectionParams:{step:r,tracer:y},executeStepList:Sn}),w);break}default:return(W=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}_.beforeUrl=_.beforeUrl??v,_.beforeTestContext=T,r.envKey&&p.setVariable(r.envKey,_.data);let N=m.browser.url();p.setCurrentUrl(N),_.afterUrl=_.afterUrl??N,_.afterTestContext=p.toRedactedDisplayCopy(),await Bq({step:r,startedAt:S,stepTypeName:C,result:_,callbacks:e.callbacks,globalWorkRef:e.work,tracer:y,attempt:t});let U,j;if(l&&_.status==="FAILED"&&!e.work.state.failureRecoveryDisabled&&s?.fromStepId===void 0&&c?.toStepId===void 0){let B=await zI({...e,executeStepList:Sn,failureRecoveryParams:{failedStep:E,nextSteps:o.slice(n+1),results:i.concat(_),tracer:u}});B&&(B.type==="ATTEMPTED"?(U=B.result.results,j=B.status):B.type==="NOT_ELIGIBLE"&&(_.message=_.message?`${_.message} ${B.message}`:B.message),_.type==="PRESET_ACTION"&&(_.failureRecoveryStatus={type:B.type,message:B.message}))}return e.work.fastForwardingToStep&&s&&(s.fromStepId===r.id&&JSON.stringify(a)===JSON.stringify(s.parentStepIdChain)&&(e.work.fastForwardingToStep=!1),r.type==="RESOLVED_MODULE"&&ef(a,s.parentStepIdChain)&&(e.work.fastForwardingToStep=!1)),_.status!=="SUCCESS"&&j!=="SUCCESS"||m.closed?{shouldStopExecuting:!0,status:_.status,stepResult:_,failureRecoveryResults:U}:c&&r.id===c.toStepId&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)?(m.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:_,failureRecoveryResults:U}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:_,failureRecoveryResults:U}}async function Bq({stepTypeName:t,step:e,result:r,tracer:n,attempt:o,startedAt:i}){let a=t.toLowerCase(),s=t.charAt(0).toUpperCase()+t.slice(1);n.recordStepDuration({step:e,durationMs:Date.now()-i.getTime()});let c="";switch(r.status){case"SUCCESS":c=r.message??`${s} executed successfully.`;break;case"FAILED":c=r.message??`${s} failed.`;break;case"CANCELLED":c=r.message??`${s} cancelled.`;break;default:throw new Error(`Unexpected ${a} status: ${r.status}`)}await n.finish({step:r,message:c,output:Ou.parse(r),attempt:o})}var VI="MOMENTIC_RUN_ID",$I="FINAL_SCREENSHOT_URL";import{randomUUID as WI}from"crypto";async function qI({browser:t,signal:e}){let r=new Date;try{return await t.navigate({url:t.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:WI(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:r,finishedAt:new Date,results:[],command:{id:WI(),type:"NAVIGATE",url:t.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var pm=async t=>{let{orgId:e,runId:r,testMetadata:n,steps:o,beforeSteps:i,afterSteps:a}=t.inputs;t.fixtures.logger=t.fixtures.logger.child({orgId:e,runId:r,testId:n?.id});let{logger:s,controller:c}=t.fixtures,{onTestComplete:l,onTestSuccess:u,onTestFailure:d}=t.callbacks.test,p=n_(s);if(t.options.reinitializeBrowser){let g=await qI({browser:c.browser,signal:c.executeAbortController.signal});if(g.status!=="PASSED")return await l?.(),clearInterval(p?.interval),g}let m;try{return s.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:n?.labels,orgSettings:sR.parse(t.inputs.orgSettings)},`Starting run for Momentic test '${n?.name??"Unnamed test"}'`),m=await Hq(t),m}finally{s.info({status:m?.status,labels:n?.labels},"Momentic test final result"),clearInterval(p?.interval),await l?.(),m?.status==="PASSED"?await u?.({steps:o,beforeSteps:i,afterSteps:a}):m?.status==="FAILED"&&await d?.({steps:o,beforeSteps:i,afterSteps:a})}};function zq({beforeStatus:t,mainStatus:e,afterStatus:r}){return t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":r==="FAILED"?"FAILED":r==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var Hq=async t=>{let{tracer:e}=t.testParams,{fromStep:r,toStep:n,steps:o,beforeSteps:i,afterSteps:a}=t.inputs,{logger:s,controller:c,context:l,storage:u}=t.fixtures,{collectDebugData:d,disableHealing:p}=t.options;l.setCurrentUrl(c.browser.url());let m="test",g=o,h=[],f=p||r!==void 0||n!==void 0||void 0,S={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},y=!1;r?.fromStepId&&r.fromStepId===n?.toStepId?(m="filtered step",S.fastForwardingToStep=!0):r?.fromStepId?(m="partial steps list from step",S.fastForwardingToStep=!0):n?m="partial steps list until step":(m="entire test",y=!0);let E,T,v;if(y&&i&&i.length>0){let O=await KI(i,"beforeSteps",t);E=O.status,T=O.results,v=O.terminalResult?{...O.terminalResult,failureReason:"SetupFailureError"}:void 0,S.state.failureRecoveryAttempts=(S.state.failureRecoveryAttempts??0)+(O.failureRecoveryAttempts??0)}let w,C;if(E===void 0||E==="PASSED"){s.info({fromStep:r,toStep:n},`Starting execution of ${m}`);let O=await e.startMainStepList(),B=await Sn({...t,work:S,listParams:{steps:g,containerName:m,results:h,tracer:O}});w=B.status,C=B.terminalResult}let _,N,U;if(y&&a&&a.length>0){let O=await KI(a,"afterSteps",t);_=O.status,N=O.results,U=O.terminalResult?{...O.terminalResult,failureReason:"TeardownFailureError"}:void 0,S.state.failureRecoveryAttempts=(S.state.failureRecoveryAttempts??0)+(O.failureRecoveryAttempts??0)}let j=zq({beforeStatus:E,mainStatus:w,afterStatus:_});if(d&&Gq({tracer:e,work:S,controller:c,storage:u,context:l,logger:s,status:j}),await Promise.allSettled(S.asyncTasks),S.asyncTasks.push(Promise.resolve(t.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:T,afterResults:N}))),j==="FAILED"){let O=E==="FAILED"?v:void 0,B=_==="FAILED"?U:void 0;return{status:"FAILED",results:h,beforeResults:T,afterResults:N,failedStepResult:O??C??B}}else if(j==="CANCELLED")return{status:"CANCELLED",results:h,beforeResults:T,afterResults:N};return{status:"PASSED",failureRecoveryDetails:S.state.failureRecoveryAttempts?{attempts:S.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:T,afterResults:N}};async function KI(t,e,r){let n=r.fixtures.logger,o=e==="beforeSteps"?await r.testParams.tracer.startBeforeStepList():await r.testParams.tracer.startAfterStepList();n.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{}},a={...r.callbacks,test:{...r.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:s,results:c,terminalResult:l}=await Sn({...r,work:i,callbacks:a,listParams:{steps:t,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let u;return s==="SUCCESS"?u="PASSED":s==="CANCELLED"?u="CANCELLED":u="FAILED",{status:u,results:c,terminalResult:l,failureRecoveryAttempts:i.state.failureRecoveryAttempts}}function Gq({tracer:t,work:e,controller:r,storage:n,logger:o,context:i,status:a}){let s=r.browser,c=s.retrieveAndClearDebugData(),l=zA(c.logsPerPage);t.attachConsoleLogs({logger:o,logs:l}),a!=="PASSED"&&a!=="SUCCESS"&&(t.attachBrowserCrashDump({crashReportDirFetcher:()=>s.browserCrashDumpDir,logger:o}),e.asyncTasks.push((async()=>{try{let u=await s.screenshot({quality:75}),d=await aI({codePath:"test-complete-final",storage:n,screenshotBuff:u,logger:o}),p=await $(s.html(),{milliseconds:2e3});i.setVariable($I,d),o.debug({finalPageHtml:p.slice(0,1e4)},"Final page state HTML"),o.debug({finalScreenshotUrl:d},"Uploaded final screenshot URL")}catch{}})()))}async function mm({settings:t,customHeaders:e,envVariables:r,envName:n,testName:o,baseUrl:i,logger:a,localTools:s,orgId:c}){let l=Nu.parse(t);e&&(l.extraHeaders={...l.extraHeaders,...e});let u=new lr({baseUrl:i,envName:n,testName:o,variablesFromEnvironment:r,currentUrl:i});await Xd({obj:l,context:u,bannedKeys:[],allowList:PT,localTools:s,logger:a,orgId:c});try{return Nu.parse(l)}catch(d){throw new M("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}async function hm({orgId:t,testName:e,envName:r,baseEnvVariables:n,parameters:o,logger:i,localTools:a}){if(!o||o.length===0)return{...n};let s={...n};return await Promise.all(o.map(async c=>{let l=await pr({orgId:t,s:c.defaultValue,context:lr.dummyContext(e,r,s),logger:i,localTools:a});s[c.name]=l})),s}import{cloneDeep as qq}from"lodash-es";import{cloneDeep as jq}from"lodash-es";var Vq={showOverlay:!1},gm=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:r,cleanup:n,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:r,cleanup:n,clientIp:o,browserBehavior:jq(Vq),socket:a}),i}removeSession(e,r){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(a){r.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){r.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}};function YI(t,e,r,n){let o=Date.now(),i=Date.now(),a,s,c,l,u=!1,d=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let S=c;c=void 0;let y=h.url(),E=f.toEditorDisplayCopy();JSON.stringify(E)===JSON.stringify(a)&&y===l&&o>i||(t.emit("browserState",{logsPerPage:S?.logsPerPage,viewport:h.getViewport(),url:y,iframeSrcUrls:s??[],context:E,isInPageLoad:h.isInPageLoad}),o=Date.now()),l=y,a=E}catch(S){if(!t.connected)return;let y=S instanceof Error?S.message:`${S}`;if(y.includes("Frame was detached")||y.includes("Not attached to an active page")||y.includes("browser has been closed")||y.includes("UserInfrastructureError"))return;r.error({err:S,sessionId:e},"Error grabbing browser state")}},p=setInterval(()=>{let h=n.getSession(e),f=h?.controller?.browser;if(!f||f.closed){r.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(p);return}d(f,h.context)},1e3),m=(h,f)=>!!(JSON.stringify(h)!==JSON.stringify(s)||f.logsPerPage.some(S=>S.length>0)),g=setInterval(async()=>{let f=n.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(g);return}else if(u)return;u=!0;try{let S=await f.getAllFrameUrls(),y=f.retrieveAndClearDebugData();m(S,y)&&(s=S,c=y,i=Date.now())}catch(S){r.warn({err:S},"Failed to fetch extended details")}finally{u=!1}},2500);return{timers:[p,g]}}var $q=3;async function XI({socket:t,logger:e,storageFactory:r,uploadedFileStorage:n,visualDiffScreenshotStorage:o,devicePixelRatio:i,generatorFactory:a,enricherFactory:s,authorization:c,settingsFactory:l,getOrgId:u,branchGetter:d,globalE2eStateManager:p}){let m=t.id,g=t.handshake.query.testId;if(!g)throw new Error("Socket connection request is missing testId");let h=await u({type:"e2e",testId:g}),f=await d?.();e=e.child({testId:g,orgId:h,sessionId:m,branch:f});let S=await a(h,e),y=await s(h,e),E=await l(h,e),T=await r(h),{testMetadata:v,baseUrl:w,envName:C,browserConfig:_,aiSettings:N,environmentVariables:U,localCodeEvalTools:j}=await oa({testId:g,orgId:h,logger:e,storage:T,authorization:c,settings:E}),O=p.getSession(m);if(O)return e.info("Associating connection with existing session (likely reconnect)"),await O.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:m,orgId:h,testId:g};let B=t.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:B,event:"connect",args:t.handshake.query},"Websocket event (connect)"),B&&p.getCurrentConnectionsByIp(B)>=$q)throw e.error({clientIp:B,sessions:p.getCurrentSessionsByIp(),...t.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(B);try{await Wq({socket:t,baseUrl:w,envName:C,testMetadata:v,orgId:h,sessionId:m,logger:e,environmentVariables:U,clientIp:B,devicePixelRatio:i,storage:T,uploadedFileStorage:n,visualDiffScreenshotStorage:o,localCodeEvalTools:j,generator:S,enricher:y,browserConfig:_,aiSettings:N,globalE2eStateManager:p})}catch(W){throw e.warn({err:W},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(B),W}return{type:"e2e",sessionId:m,testId:g,orgId:h}}async function Wq({socket:t,baseUrl:e,envName:r,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:s,storage:c,uploadedFileStorage:l,visualDiffScreenshotStorage:u,localCodeEvalTools:d,generator:p,environmentVariables:m,browserConfig:g,aiSettings:h,clientIp:f,enricher:S,globalE2eStateManager:y}){let E={viewport:o.advanced?.viewport??Kt,locale:o.advanced?.locale??Io,timezoneId:o.advanced?.timezone??Oo,geolocation:o.advanced?.geolocation??Lo,colorScheme:o.advanced?.colorScheme};n&&(E.deviceScaleFactor=n);let T=o.id,v=await mm({settings:g,orgId:i,baseUrl:e,envName:r,testName:o.name,localTools:d,envVariables:m,logger:s,customHeaders:void 0});s=s.child({orgId:i,sessionId:a,testId:T});let w=await qr.init({baseUrl:e,userBrowserSettings:v,enricher:S,storage:c,logger:s,contextArgs:E,iconKnowledgeBase:null,callbacks:{onTabsChange:(j,O)=>{t.emit("tabs",{tabs:j,activeTab:O})},onScreencastFrame:(j,O)=>{let B=t;wr&&(B=t.compress(!0)),B.emit("screenshot",{buffer:j},()=>{O()})},onSvgsCollected:j=>{t.emit("newIconDetected",{numIcons:j.newSvgs.length}),c.saveNewIcons(j,s)},onNetworkLogs:j=>{t.emit("networkLogs",{harEntries:j})}}});await w.navigate({url:e,initialNavigation:!0});let C=new oi({browser:w,generator:p,logger:s,orgId:i,options:{scratchPadId:void 0,slowMoMs:v.slowMoMs,autoFollowNewTabs:v.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering},storage:c,localCodeEvalTools:d,uploadedFileStorage:l,visualDiffScreenshotStorage:u}),_=YI(t,a,s,y),N=async()=>{_.timers.forEach(j=>clearInterval(j))},U=new lr({baseUrl:e,testName:o.name,currentUrl:C.browser.url(),variablesFromEnvironment:m,envName:r});if(!t.connected)throw await w.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");t.emit("session",{url:e,userAgent:qr.USER_AGENT,viewport:C.browser.getViewport(),sessionId:a}),y.registerSession({controller:C,context:U,sessionId:a,cleanup:N,clientIp:f,socket:t})}async function oa({testId:t,orgId:e,logger:r,storage:n,authorization:o,settings:i}){let a=await n.fetchTestMetadata(t,r);if(!a)throw new Error(`Test metadata could not found for test ${t}`);let s;o?.type==="API_KEY"&&(s=new On({httpClient:new zt({...o,logger:r,mode:"interactive"}),fakerSeed:void 0}));let c=a.envs?.find(h=>h.default),l;c&&(l=await n.fetchEnvironment(c.name,r));let u=l&&"browser"in l?l.browser:void 0,d={...i.browser,...u,...a.advanced};d.browserType=xu({browserType:d.browserType,orgDefaultBrowserType:i.browser?.defaultBrowserType});let p=a.baseUrl||l?.variables?.[Rt];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let m={...l?.variables};m=await hm({orgId:e,testName:a.name,envName:l?.name,baseEnvVariables:m,parameters:a.parameters,logger:r,localTools:s});let g={...i.ai,...a.advanced};return{localCodeEvalTools:s,baseUrl:p,envName:l?.name,testName:a.name,browserConfig:d,environmentVariables:m,testMetadata:a,aiSettings:g}}var Ay=class{parentTracer=null;socket;step;orgId;constructor({step:e,socket:r,parentTracer:n,orgId:o}){this.socket=r,this.parentTracer=n,this.step=e,this.orgId=o}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}recordStepDuration(e){let r=e.step.type!=="PRESET_ACTION"?e.step.type:e.step.command.type;kt.distribution("test_step_duration",e.durationMs,[`type:${r}`,"platform:browser","executor:editor",`orgId:${this.orgId}`])}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new fo({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},fo=class{stepFrequenciesByType={};parentTracer;parentStep;socket;orgId;recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,r]of Object.entries(this.stepFrequenciesByType))kt.increment("test_step_execution",r,[`type:${e}`,"platform:browser","executor:editor",`orgId:${this.orgId}`])}constructor({parentStep:e,socket:r,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=r,this.orgId=o}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.recordStepStat(e.step),this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Ay({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async finish(){this.sendFinalizedStepStats()}},fm=class{constructor(e,r,n,o){this.socket=e;this.storage=r;this.orgId=n;this.testId=o}children=[];loggerBindings;setActiveVideo(){}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}onNetworkPage(){}onNetworkLogs(){}attachConsoleLogs(){}attachBrowserCrashDump(){}async finish(){this.socket.emit("finished"),await Promise.all(this.children.map(e=>e.finish()))}async startBeforeStepList(){let e=new fo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startMainStepList(){let e=new fo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startAfterStepList(){let e=new fo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}};var wy={currentlyExecutingRequests:{}},Kq=t=>async(e,r)=>{let{testId:n,orgId:o}=t.metadata,i=await t.settingsFactory(o,t.logger),a=await t.storageFactory(o),s,c=await oa({testId:n,orgId:o,logger:t.logger,storage:a,authorization:t.authorization,settings:i}),l=`${n}|${c.baseUrl}`;try{let u=wy.currentlyExecutingRequests[l]??0;wy.currentlyExecutingRequests[l]=u+1,s=await Yq({...t,...e,...c,done:r})}finally{t.logger.info({result:s,sessionId:t.metadata.sessionId},"Test execution complete"),wy.currentlyExecutingRequests[l]--}},Yq=async({socket:t,steps:e,baseUrl:r,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storageFactory:s,aiSettings:c,browserConfig:l,metadata:u,logger:d,envName:p,testName:m,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:S,globalE2eStateManager:y})=>{let{testId:E,sessionId:T,orgId:v}=u,w=T,C=y.getSession(T);if(!C)throw new Error("No active session found");let{controller:_,context:N}=C;_.setOpen(),d=d.child({testId:E,orgId:v,sessionId:T,runId:w}),d.info({steps:e.map(se=>`${se.type}${"command"in se?` - ${se.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:p,testName:m,baseUrl:r,context:N,browserConfig:l,aiSettings:c},"Socket execution parameters");let U=g??{},j=async()=>{o&&(await _.browser.reset({newUrl:r}),N.reset({baseUrl:r,currentUrl:_.browser.url(),variablesFromEnvironment:U,envName:p,testName:m}))},O=await s(v),B=await S(v),W=async()=>{let se=Date.now();try{await B.resolveStepCacheEntries({schemaVersion:n.schemaVersion,testId:E,stepLists:{steps:e},logger:d})}catch(Ke){d.error({err:Ke},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}finally{kt.distribution("cache-resolution",Date.now()-se,["executor:editor"])}};try{await Wl({promiseGenerator:async()=>Promise.all([j(),W()]),signal:_.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),_.setOpen()}catch(se){if(t.emit("finished"),se.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${se}`)}let q=qq(e),ve={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},Y={orgId:v,runId:w,testMetadata:n,steps:e,fromStep:a,toStep:i,orgSettings:{ai:c,browser:l}},st={controller:_,context:N,storage:O,codeEvalTools:h,usageTracker:new Wa,logger:d},Le={test:{},step:{onDynamicAIActionStatusUpdateEvent:se=>{t.emit("dynamicCommandStatusUpdate",se)},onDynamicAIActionEvaluatingEvent:se=>{t.emit("dynamicCommandEvaluating",se)},onDynamicCommandGenerated:se=>{t.emit("dynamicCommandGenerated",se)},onDynamicCommandExecuted:se=>{t.emit("dynamicCommandExecuted",se)}}},gt=new fm(t,O,v,E),rr=await pm({fixtures:st,options:ve,callbacks:Le,inputs:Y,testParams:{tracer:gt}}),Ge={logger:d,cacheStorage:B,orgId:v,testId:E,originalStepsWithCaches:{steps:q},updatedStepsWithCaches:{steps:e}};return rr?.status==="PASSED"?await Md(Ge):rr?.status==="FAILED"&&await Pd(Ge),await gt.finish(),f?.(rr),rr.status};var JI={event:"execute",createHandler:Kq};import{cloneDeep as Xq}from"lodash-es";var Jq=t=>async({command:e},r)=>{let{logger:n,generatorFactory:o,metadata:i}=t,a=Xq(e),s=ww(a);if(s.category!=="NO_DESCRIPTION_PROVIDED"){if(s.category!=="NONE"){r?.({result:s});return}"cache"in a&&(a.cache=void 0);try{let l=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});r?.({result:l})}catch(c){n.error({event:"lint",err:c},"Failed to lint step"),r?.({result:void 0})}}},QI={event:"lintStep",createHandler:Jq};var Qq=({metadata:t,logger:e,storageFactory:r,globalE2eStateManager:n})=>{let{sessionId:o,orgId:i}=t;return async(a,s)=>{let{description:c,command:l,testMetadata:u,returnScreenshot:d}=a;e.info({params:a},`Locate handler called - ${c}`);let p=n.getSession(o);if(!p)throw new Error("No active session found");let{controller:m,context:g}=p;m.setOpen();let h=await r(i),f=_i.parse(u.advanced??{}),S={},y;if(c){if("useSelector"in l&&l.useSelector)try{let E=await m.locateElementWithSelector(c,"iframeUrl"in l?l.iframeUrl:void 0);y=E.resolution.locator,S={target:E.target,thoughts:E.thoughts}}catch(E){e.warn({err:E},"Failed resolving target with selector"),s({err:`Failed locating element: ${E.message}`,decisions:E instanceof kr?E.decisions:void 0});return}else try{let E=await m.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Ri(l),iframeUrl:"iframeUrl"in l?l.iframeUrl:void 0,memory:"cache"in l&&l.cache&&"target"in l.cache&&nu(l.cache.target.memory)?l.cache.target.memory:void 0,logger:e});S={target:E.target,thoughts:E.thoughts},y=E.resolution.locator}catch(E){(async()=>{try{let T=await m.browser.getCondensedHtml({skipWait:!0});e.warn({err:E,html:T.slice(0,1e5)},"Failed locating element with AI")}catch(T){e.warn({err:T},"Failed grabbing HTML after trying to locate element with AI")}})(),s({err:`${E.message}`});return}if(l.type==="SELECT_OPTION"&&y)try{S.options=await m.browser.getSelectOptions(y)}catch(E){e.warn({err:E},"Failed getting select options"),s({err:`Failed getting select options: ${E.message}`});return}e.info({result:S},"Locate handler result")}if(d)try{let{buffer:E,width:T,height:v}=await m.screenshotWithDimensions({clearHighlights:!0,locator:y}),w=await h.uploadScreenshot(E);S.screenshot={data:w,width:T,height:v},e.info({width:T,height:v},"Captured screenshot during locate")}catch(E){e.error({err:E},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${E.message}`});return}if(s({result:S}),y)try{await Promise.all([m.browser.scrollIntoViewIfNeeded(y),m.browser.highlight(y)])}catch(E){e.warn({err:E},"Error highlighting element, continuing...")}}},ZI={event:"locate",createHandler:Qq};var Zq=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async({event:o,percentX:i,percentY:a})=>{let s=r.getSession(n);if(!s)throw new Error("No active session found");let c=s.controller.browser;if(c.closed||c.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await c.clickMouseFromPositionPercentages(o,i,a)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode")}}},eO={event:"mouseClickEvent",createHandler:Zq};var eK=({metadata:t,generatorFactory:e,logger:r,socket:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:s}=t;return async({stepId:c,parentStepIdChain:l,attribute:u})=>{let d=o.getSession(i);if(!d)throw new Error("No active session found");let{controller:p}=d,m=await e(a,r);p.setOpen(),d.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{d.browserBehavior.showOverlay=!1,await p.stopRecordMode()}catch(S){r.warn({err:S},"Failed to stop record mode in target click socket handler")}},{once:!0});let h=!1,f=(S,y)=>{y.type!=="PRESET_ACTION"||y.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:S,stepId:c,parentStepIdChain:l,command:y.command,attribute:u}),g.abort(),h=!0)};setTimeout(()=>{h||(g.abort(),n.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:c,parentStepIdChain:l,attribute:u}))},1e4),await p.startRecordMode({params:{generator:m,logger:r,testId:s,orgId:a,callbacks:{onActionReceived:S=>f("clickReceived",S),onStepRecorded:S=>f("descriptionGenerated",S)}},abortController:g,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:l,attribute:u})}},tO={event:"recordTargetClick",createHandler:eK};var tK=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async({key:o})=>{let i=r.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyDown(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:n,err:s},"Browser is closed, ignoring key down socket event error");return}throw s}}},rO={event:"keyDownEvent",createHandler:tK};var rK=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async({key:o})=>{let i=r.getSession(n);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:n},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyUp(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:n,err:s},"Browser is closed, ignoring key up socket event error");return}throw s}}},nO={event:"keyUpEvent",createHandler:rK};var nK=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t,o,i=0,a=(l,u)=>{let d=async()=>{o=void 0};clearTimeout(o),o=setTimeout(d,Math.min(1e3,250*(i+1)))},s,c=0;return async l=>{let u=r.getSession(n);if(!u)throw new Error("No active session found");let{controller:d,browserBehavior:p}=u,m=d.browser;if(m.closed||m.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(l.event==="scroll"){let g=await m.scrollFromPositionPercentages(l.percentX,l.percentY,s?.x??0,s?.y??0),h=u.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}p.showOverlay&&a(m,l);try{let g=await m.moveMouseFromPositionPercentages(l.percentX,l.percentY);c=0,s=g}catch(g){c++,c%5===0&&e.warn({err:g,mouseErrors:c},"Error in socket mouse move handler")}}},oO={event:"mouseMoveEvent",createHandler:nK};var oK=({metadata:t,generatorFactory:e,socket:r,logger:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:s}=t;return async({stepId:c})=>{let l=o.getSession(i);if(!l)throw new Error("No active session found");let{controller:u,browserBehavior:d}=l,p=await e(a,n);n.info("Starting cloud recording");let m=new AbortController,g=await u.startRecordMode({params:{generator:p,logger:n,testId:s,orgId:a,callbacks:{onActionReceived:(h,f)=>{r.emit("stepRecorded",{stepId:c,step:h,offset:f})},onStepRecorded:(h,f)=>{r.emit("stepRecorded",{stepId:c,step:h,offset:f})}}},abortController:m,isClickToRecord:!1});d.recordingState={transformer:g}}},iO={event:"recordingStart",createHandler:oK};var iK=({metadata:t,logger:e,globalE2eStateManager:r})=>{let{sessionId:n}=t;return async()=>{let o=r.getSession(n);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},aO={event:"recordingStop",createHandler:iK};var aK=({socket:t,metadata:e,logger:r,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async(s,c)=>{let{testId:l,sessionId:u,orgId:d}=e;r.info({testId:l,sessionId:u},"Refresh event received");let p=await i(d,r),m=await n(d),{baseUrl:g}=await oa({testId:l,orgId:d,logger:r,storage:m,authorization:o,settings:p}),h=a.getSession(u);if(!h){t.emit("error",{message:"No session to refresh"});return}let{controller:f}=h;f.setOpen(),await f.browser.refresh();let S=f.browser.getViewport();r.info({baseUrl:g,viewport:S},`Session refreshed for test ${l} at ${g}`),c()},sO={event:"refresh",createHandler:aK};var sK=({socket:t,metadata:e,logger:r,storageFactory:n,authorization:o,settingsFactory:i,globalE2eStateManager:a})=>async()=>{let{testId:s,sessionId:c,orgId:l}=e;r.info({testId:s,sessionId:c},"Reset event received");let u=await i(l,r),d=await n(l),{baseUrl:p,envName:m,testName:g,environmentVariables:h}=await oa({testId:s,orgId:l,logger:r,storage:d,authorization:o,settings:u}),f=a.getSession(c);if(!f){t.emit("error",{message:"No session to reset"});return}let{controller:S,context:y}=f;await S.browser.reset({newUrl:p});let E=S.browser.baseUrl;y.reset({baseUrl:E,currentUrl:S.browser.url(),variablesFromEnvironment:h,envName:m,testName:g});let T=S.browser.getViewport(),v=qr.USER_AGENT;r.info({baseUrl:p,viewport:T},`Session reset for test ${s} at ${E}`),t.emit("session",{url:E,userAgent:v,viewport:T,sessionId:c})},lO={event:"reset",createHandler:sK};var lK=({metadata:t,globalE2eStateManager:e})=>{let{sessionId:r}=t;return async({url:n})=>{let o=e.getSession(r);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:n})}},cO={event:"switchTab",createHandler:lK};async function uO(t){return XI(t)}var dO=[EC,JI,ZI,lO,sO,fC,cO,QI,tO,iO,aO,oO,eO,rO,nO,yC,SC];var pO=t=>{let{logger:e}=t,r=new cK(t.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return r.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await uO({...t,socket:n,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}dO.forEach(i=>uK(i,{...t,socket:n,metadata:o,logger:e}))}),r},uK=(t,e)=>{let r=t.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(t.event)||e.logger.debug({...e.metadata,event:t.event},`Websocket event (${t.event})`);let i=a=>{e.logger.error({event:t.event,type:"websocket",err:a instanceof Error?a:new Error(`${a}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:a instanceof Error?a.message:`${a}`})};try{let a=r.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(t.event,n)};import{Router as gK}from"express";import{Router as pK}from"express";import Lc from"fs";import Oc from"path";import{v4 as mK}from"uuid";import hK from"yaml";import{hostname as dK}from"os";var Ic="2.29.5",nt=Xa({app:"desktop-server",hostname:dK(),disableConsoleLogs:!0}).child({cliVersion:Ic});(async()=>{try{let t=await po(nt);t.gitBranchName&&nt.addBinding("branch",t.gitBranchName)}catch{}})();var Ls=pK();async function Cy(t){return(await Gd(t,nt)).map(n=>{let o=t.modules[n.moduleId];if(!o){b.warn(`Found a dangling module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}Ls.get("/",Oe(async(t,e)=>{let r=me(),n=await te(r),o=await Cy(n);e.status(200).json(o)}));Ls.post("/",Oe(async(t,e)=>{let r;try{r=qv.parse(t.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{Mo(r.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let n=me(),o=(await te(n)).modules;if(Object.values(o).find(s=>s.name===r.name)){e.status(400).send(`A module with the name "${r.name}" already exists. Please choose a different name.`);return}let i=Oc.join(n.rootDir,r.folderPath??"");if(!Lc.existsSync(i)||!Lc.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Hd({...r,folder:i,project:n});e.status(201).json(a)}));Ls.get("/:moduleId",Oe(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r=await te(me()),n=r.modules[t.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await dn(n,r,b);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ls.post("/:moduleId/duplicate",Oe(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=Wv.parse(t.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Mo(r.name)}catch(h){e.status(400).json({error:h.message});return}let n=me(),o=await te(n),i=o.modules[t.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===r.name)){e.status(400).send(`A module with the name "${r.name}" already exists. Please choose a different name.`);return}let a=await dn(i,o,b),s=Oc.join(n.rootDir,Oc.dirname(i.relativePath));if(!Lc.existsSync(s)||!Lc.statSync(s).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let c=ze(r.name),l=Oc.join(s,`${c}.module.yaml`),u=mK(),{stepsToSave:d}=await it({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:xt()}}),p={fileType:Se.MODULE,schemaVersion:_e,moduleId:u,name:r.name,description:"",enabled:!0,steps:d.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced},m=hK.stringify(p);Lc.writeFileSync(l,m,"utf-8");let g={relativeFilePath:Oc.relative(n.rootDir,l)};e.status(201).json(g)}));Ls.patch("/:moduleId/metadata",Oe(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let r;try{r=Kv.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=me(),o=await te(n);Vw({moduleId:t.params.moduleId,content:r,momenticFiles:o,logger:b,project:n}),e.status(201).json({message:"ok"})}));var mO=Ls;var hO=gK();hO.get("/",Oe(async(t,e)=>{let r=me(),n=await te(r),o=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),s=await Cy(n),c={labels:i,tests:a,modules:s};e.status(200).json(c)}));var gO=hO;import{Router as fK}from"express";var xy=fK();xy.get("/",Oe((t,e)=>{let r=jd(me(),nt);e.status(200).json(r)}));xy.get("/names",Oe((t,e)=>{let n=me().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var fO=xy;import{Router as SK}from"express";var SO=SK();SO.get("/",Oe((t,e)=>{let r={userId:jo(),orgId:xt(),cliVersion:Ic??"0.0.0"};e.status(200).json(r)}));var yO=SO;import{StreamableHTTPServerTransport as j2}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as V2}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as $2}from"crypto";import{Router as W2}from"express";import{McpServer as H2}from"@modelcontextprotocol/sdk/server/mcp.js";import{SSEServerTransport as G2}from"@modelcontextprotocol/sdk/server/sse.js";import{streamObject as vK}from"ai";import bm from"dedent";import RK from"path";import{z as ii}from"zod";import{tool as yK}from"ai";import{z as EK}from"zod";var EO=(t,e)=>({builder:n=>yK({description:t.schema.description,inputSchema:EK.object(t.schema.inputSchema),execute:async o=>{let i=e(n);n.logger.info({input:o},`Executing tool ${t.schema.name}`);try{await t.handle(n,o,i,void 0)}catch(s){i.addError(String(s))}let a=await i.serialize();return a.isError?n.logger.error({toolName:t.schema.name,input:o,err:a.content.map(s=>s.text).join(`
4378
4378
  `)},"Tool execution resulted in error"):n.logger.info({toolName:t.schema.name,input:o},"Tool execution completed"),a}}),tool:t});var Nc=class{results=[];isError;addResult(e){this.results.push(e)}addError(e){this.results.push(`Error: ${e}`),this.isError=!0}getResult(){return this.results.join(`
4379
4379
  `)}async serialize(){let e=[];return this.results.length&&(e.push("### Result"),e.push(this.results.join(`
4380
4380
  `)),e.push("")),{content:[{type:"text",text:e.join(`
4381
- `)}],isError:this.isError}}};var yn=t=>{let e=(n,o)=>{let i=async(a,s)=>{let c=s.sessionId??void 0,l=Date.now(),u=n.logger.child({...c&&{sessionId:c},toolName:t.schema.name});u.debug({toolName:t.schema.name,params:is({json:a,maxJsonStringSize:500}),sessionId:c},`MCP tool invoked: ${t.schema.name}`);let d=new Nc,p;try{await t.handle(n,a,d,s)}catch(h){h instanceof Error?(p=h,d.addError(String(h))):d.addError(`Unknown value thrown: ${String(h)}`)}let m=Date.now()-l,g=await d.serialize();if(p)u.error({toolName:t.schema.name,sessionId:c,duration:m,err:p},`MCP tool failed: ${t.schema.name}`);else{let h=g.content.filter(f=>f.type==="text");u.debug({toolName:t.schema.name,sessionId:c,duration:m,responseIsError:g.isError,response:is({json:h,maxJsonStringSize:500})},`MCP tool completed: ${t.schema.name}`)}return g};o.registerTool(t.schema.name,{title:t.schema.name,description:t.schema.description,inputSchema:t.schema.inputSchema},i)};return{...EO(t,()=>new Nc),addToolToMcpServer:e,name:t.schema.name}};import{randomUUID as bK}from"crypto";function Sm(t){return Hl({baseUrl:Cr(),apiKey:xr(),sessionId:t})}var ym=async({step:t,controller:e,storage:r,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:s})=>{let{results:c}=await _y({steps:[t],controller:e,storage:r,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:s});return c[0]},_y=async({steps:t,controller:e,storage:r,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:s})=>{let c={controller:e,storage:r,codeEvalTools:n,logger:o,context:a,usageTracker:new Wa},l=i?new fo({orgId:s,parentStep:null,parentTracer:null,socket:i}):new Fl;return e.setOpen(),Sn({listParams:{containerName:"copilot-steps",steps:t,tracer:l},fixtures:c,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:s,runId:bK(),steps:t,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};async function Vn(t,e,r){let n=await ee(t),o=r==="test"?n.tests:r==="module"?n.modules:n.mobileTests,i=TK(o,e);if(e.id){if(i.length===0)throw new ot(`No ${r} found with id '${e.id}' in project '${t.rootDir}'.`);return Em(i,n)}else if(e.name){if(i.length===0)throw new ot(`No ${r} found with exact name '${e.name}' in project '${t.rootDir}'.`);if(i.length>1){let a=i.map(s=>({id:s.id,path:s.relativePath}));throw new ot([`Multiple ${r}s found with exact name '${e.name}'. Please disambiguate by id or path.`,JSON.stringify(a,null,2)].join(`
4381
+ `)}],isError:this.isError}}};var yn=t=>{let e=(n,o)=>{let i=async(a,s)=>{let c=s.sessionId??void 0,l=Date.now(),u=n.logger.child({...c&&{sessionId:c},toolName:t.schema.name});u.debug({toolName:t.schema.name,params:is({json:a,maxJsonStringSize:500}),sessionId:c},`MCP tool invoked: ${t.schema.name}`);let d=new Nc,p;try{await t.handle(n,a,d,s)}catch(h){h instanceof Error?(p=h,d.addError(String(h))):d.addError(`Unknown value thrown: ${String(h)}`)}let m=Date.now()-l,g=await d.serialize();if(p)u.error({toolName:t.schema.name,sessionId:c,duration:m,err:p},`MCP tool failed: ${t.schema.name}`);else{let h=g.content.filter(f=>f.type==="text");u.debug({toolName:t.schema.name,sessionId:c,duration:m,responseIsError:g.isError,response:is({json:h,maxJsonStringSize:500})},`MCP tool completed: ${t.schema.name}`)}return g};o.registerTool(t.schema.name,{title:t.schema.name,description:t.schema.description,inputSchema:t.schema.inputSchema},i)};return{...EO(t,()=>new Nc),addToolToMcpServer:e,name:t.schema.name}};import{randomUUID as bK}from"crypto";function Sm(t){return Hl({baseUrl:Cr(),apiKey:xr(),sessionId:t})}var ym=async({step:t,controller:e,storage:r,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:s})=>{let{results:c}=await _y({steps:[t],controller:e,storage:r,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:s});return c[0]},_y=async({steps:t,controller:e,storage:r,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:s})=>{let c={controller:e,storage:r,codeEvalTools:n,logger:o,context:a,usageTracker:new Wa},l=i?new fo({orgId:s,parentStep:null,parentTracer:null,socket:i}):new Fl;return e.setOpen(),Sn({listParams:{containerName:"copilot-steps",steps:t,tracer:l},fixtures:c,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:s,runId:bK(),steps:t,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};async function Vn(t,e,r){let n=await te(t),o=r==="test"?n.tests:r==="module"?n.modules:n.mobileTests,i=TK(o,e);if(e.id){if(i.length===0)throw new ot(`No ${r} found with id '${e.id}' in project '${t.rootDir}'.`);return Em(i,n)}else if(e.name){if(i.length===0)throw new ot(`No ${r} found with exact name '${e.name}' in project '${t.rootDir}'.`);if(i.length>1){let a=i.map(s=>({id:s.id,path:s.relativePath}));throw new ot([`Multiple ${r}s found with exact name '${e.name}'. Please disambiguate by id or path.`,JSON.stringify(a,null,2)].join(`
4382
4382
  `))}return Em(i,n)}else if(e.path){let a=e.path;if(i.length===0)throw new ot(`No ${r} found at path '${a}'. Provide an absolute path or a path relative to '${t.rootDir}'.`);if(i.length>1){let s=i.filter(l=>l.fullFilePath===a||l.relativePath===a||l.fullFilePath.endsWith(`/${a}`)||l.relativePath.endsWith(`/${a}`));if(s.length===1)return Em(s,n);let c=i.map(l=>({id:l.id,path:l.fullFilePath}));throw new ot([`Multiple ${r}s matched the provided path '${a}'. Please pass the absolute path.`,JSON.stringify(c,null,2)].join(`
4383
- `))}return Em(i,n)}else throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Em(t,e){let r=t[0];if(!r)throw t.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return{entity:r,momenticFiles:e}}function TK(t,e){if(e.id){let r=Object.values(t).find(n=>n.id===e.id);return r?[r]:[]}else{if(e.name)return Object.values(t).filter(r=>r.name===e.name);if(e.path){let r=e.path;return Object.values(t).filter(n=>n.fullFilePath.includes(r)||n.relativePath.includes(r))}else throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}}var AK=yn({schema:{name:"momentic_module_get",description:"Get a single fully loaded module by id, exact name, or file path. This returns complete module details including: parameters (required input names), defaultParameters (optional inputs with defaults), parameterEnums (allowed values for enum params), and the full step list. REQUIRED: Always call this before inserting a module step to understand what inputs to provide. Exactly one selector must be provided. Module names must follow valid entity name rules.",inputSchema:{selector:Po}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t;try{let a=await Vn(o,e.selector,"module"),s=await dn(a.entity,a.momenticFiles,i);r.addResult(JSON.stringify({module:s},null,2))}catch(a){r.addError(String(a));return}}}),wK=yn({schema:{name:"momentic_module_list",description:"List all modules in the project with basic metadata (id, name, description, path). Use this to discover available modules. IMPORTANT: This does NOT include parameter definitions. You MUST call momentic_module_get to inspect parameter requirements (parameters, defaultParameters, parameterEnums) before inserting any module into a test.",inputSchema:{}},handle:async(t,e,r,n)=>{let{project:o}=t,i=await ee(o),s=Object.values(i.modules).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type}));r.addResult(JSON.stringify({modules:s,note:"Parameters are not included in this list. Use momentic_module_get to inspect parameter requirements before inserting modules."},null,2))}}),My=ii.object({recommendations:ii.array(ii.object({moduleId:ii.string().describe("The UUID of the recommended module"),moduleName:ii.string().describe("The name of the module"),reasoning:ii.string().describe("Why this module might be useful for the test"),confidence:ii.enum(["high","medium","low"]).describe("Confidence level of the recommendation")})).describe("List of module IDs that could be useful for this test")});function CK(t){let e=t.parameters&&t.parameters.length>0?t.parameters.join(", "):"none",r=t.defaultParameters?Object.entries(t.defaultParameters).map(([i,a])=>`${i}: ${a}`).join(", "):"none",n=t.parameterEnums?Object.entries(t.parameterEnums).map(([i,a])=>`${i}: [${a.join(", ")}]`).join(", "):"none",o=t.steps.length>0?t.steps.map((i,a)=>{try{return` ${a+1}. ${lo(i)}`}catch{return` ${a+1}. [Unsupported step type: ${i.type}]`}}).join(`
4383
+ `))}return Em(i,n)}else throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Em(t,e){let r=t[0];if(!r)throw t.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return{entity:r,momenticFiles:e}}function TK(t,e){if(e.id){let r=Object.values(t).find(n=>n.id===e.id);return r?[r]:[]}else{if(e.name)return Object.values(t).filter(r=>r.name===e.name);if(e.path){let r=e.path;return Object.values(t).filter(n=>n.fullFilePath.includes(r)||n.relativePath.includes(r))}else throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}}var AK=yn({schema:{name:"momentic_module_get",description:"Get a single fully loaded module by id, exact name, or file path. This returns complete module details including: parameters (required input names), defaultParameters (optional inputs with defaults), parameterEnums (allowed values for enum params), and the full step list. REQUIRED: Always call this before inserting a module step to understand what inputs to provide. Exactly one selector must be provided. Module names must follow valid entity name rules.",inputSchema:{selector:Po}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t;try{let a=await Vn(o,e.selector,"module"),s=await dn(a.entity,a.momenticFiles,i);r.addResult(JSON.stringify({module:s},null,2))}catch(a){r.addError(String(a));return}}}),wK=yn({schema:{name:"momentic_module_list",description:"List all modules in the project with basic metadata (id, name, description, path). Use this to discover available modules. IMPORTANT: This does NOT include parameter definitions. You MUST call momentic_module_get to inspect parameter requirements (parameters, defaultParameters, parameterEnums) before inserting any module into a test.",inputSchema:{}},handle:async(t,e,r,n)=>{let{project:o}=t,i=await te(o),s=Object.values(i.modules).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type}));r.addResult(JSON.stringify({modules:s,note:"Parameters are not included in this list. Use momentic_module_get to inspect parameter requirements before inserting modules."},null,2))}}),My=ii.object({recommendations:ii.array(ii.object({moduleId:ii.string().describe("The UUID of the recommended module"),moduleName:ii.string().describe("The name of the module"),reasoning:ii.string().describe("Why this module might be useful for the test"),confidence:ii.enum(["high","medium","low"]).describe("Confidence level of the recommendation")})).describe("List of module IDs that could be useful for this test")});function CK(t){let e=t.parameters&&t.parameters.length>0?t.parameters.join(", "):"none",r=t.defaultParameters?Object.entries(t.defaultParameters).map(([i,a])=>`${i}: ${a}`).join(", "):"none",n=t.parameterEnums?Object.entries(t.parameterEnums).map(([i,a])=>`${i}: [${a.join(", ")}]`).join(", "):"none",o=t.steps.length>0?t.steps.map((i,a)=>{try{return` ${a+1}. ${lo(i)}`}catch{return` ${a+1}. [Unsupported step type: ${i.type}]`}}).join(`
4384
4384
  `):" (no steps)";return bm`
4385
4385
  Module ID: ${t.moduleId}
4386
4386
  Name: ${t.name}
@@ -4437,7 +4437,7 @@ ${o}
4437
4437
  Steps:
4438
4438
  ${e}
4439
4439
  </test>
4440
- `}var PK=yn({schema:{name:"momentic_module_recommend",description:"Use AI to recommend modules that might be useful for a test based on test context and available modules. Returns a list of module IDs with reasoning.",inputSchema:{userRequest:ii.string().describe("The user's desired changes to the test and any other relevant context. Include any specific information helpful for finding where in the test they want changes, what pages these changes will happen on, etc.")}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t,a="testPath"in t?t.testPath:void 0,s,c=n?.sessionId??("sessionId"in t?t.sessionId:void 0);try{s=xr()}catch{r.addError("API key is not configured. Please ensure the desktop server is properly initialized with an API key.");return}try{let l=await ee(o),u=Object.values(l.modules);if(u.length===0){r.addResult(JSON.stringify({recommendations:[],message:"No modules found in project"},null,2));return}i.info({moduleCount:u.length},"Fetching full module details for recommendation");let d=await Promise.all(u.map(v=>dn(v,l,i))),p=Sm(c),m=`Use this description:
4440
+ `}var PK=yn({schema:{name:"momentic_module_recommend",description:"Use AI to recommend modules that might be useful for a test based on test context and available modules. Returns a list of module IDs with reasoning.",inputSchema:{userRequest:ii.string().describe("The user's desired changes to the test and any other relevant context. Include any specific information helpful for finding where in the test they want changes, what pages these changes will happen on, etc.")}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t,a="testPath"in t?t.testPath:void 0,s,c=n?.sessionId??("sessionId"in t?t.sessionId:void 0);try{s=xr()}catch{r.addError("API key is not configured. Please ensure the desktop server is properly initialized with an API key.");return}try{let l=await te(o),u=Object.values(l.modules);if(u.length===0){r.addResult(JSON.stringify({recommendations:[],message:"No modules found in project"},null,2));return}i.info({moduleCount:u.length},"Fetching full module details for recommendation");let d=await Promise.all(u.map(v=>dn(v,l,i))),p=Sm(c),m=`Use this description:
4441
4441
 
4442
4442
  `;m+=bm`
4443
4443
  <description>
@@ -4451,7 +4451,7 @@ with this test we are editing:
4451
4451
 
4452
4452
  to pick which of these modules are relevant:
4453
4453
 
4454
- `;let g=_K(d);m+=g;let h=vK({schema:My,model:p("claude-sonnet-4-5-20250929"),system:xK,messages:[{role:"user",content:m}]}),f=[];for await(let v of h.textStream)f.push(v);let S=f.join(""),y;try{let v=JSON.parse(S);y=My.parse(v)}catch(v){i.error({rawResponse:S,parseError:v},"Failed to parse AI response as JSON"),r.addError(`Failed to parse AI response: ${String(v)}. Raw response: ${S}`);return}let E=new Set(d.map(v=>v.moduleId)),T=y.recommendations.filter(v=>E.has(v.moduleId)?!0:(i.warn({moduleId:v.moduleId,moduleName:v.moduleName},"AI recommended a module that doesn't exist"),!1));r.addResult(JSON.stringify({recommendations:T,totalModulesAnalyzed:d.length},null,2))}catch(l){i.error({err:l},"Error in module recommendation"),r.addError(`Failed to recommend modules: ${String(l)}`)}}}),Tm=[PK,AK,wK];var IK=yn({schema:{name:"momentic_environment_list",description:"List environments defined in the project's momentic.config.yaml file.",inputSchema:{}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t,a=jd(o,i);r.addResult(JSON.stringify({environments:a},null,2))}}),bO=[IK];import{streamText as M2}from"ai";import P2 from"path";import{z as I2}from"zod";var vm=new gm;var ai=class extends Qa{constructor(r,n){super(r,n);this.client=r;this.orgId=n}async fetchTestMetadata(r){let n=me(),i=(await ee(n)).tests[r];if(i)return Ql(i.relativePath,n)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(r,n){let o=me();return Gi(r,o,Pn)}async fetchIconKnowledgeBase(r){try{return await this.client.fetchIconKnowledgeBase(r)}catch(n){return r.error({err:n},"Failed to fetch icon knowledge base"),null}}};var ia=class{async prepareGoldenScreenshotForComparison(e,r,n){return await new ps(me(),!1).prepareGoldenScreenshotForComparison(e,r,n)}};import TO from"path";import{v4 as OK}from"uuid";async function Rm({project:t,input:e}){try{Mo(e.name)}catch(l){throw new ot(`${l} when validating the test entity name`)}if(!e.baseUrl&&!e.environment)throw new ot("Either 'baseUrl' or 'environment' must be provided when creating a test.");let r=await ee(t);if(Object.values(r.tests).find(l=>l.name===e.name))throw new ot(`A test with the name "${e.name}" already exists. Please use a different name.`);let i={id:OK(),name:e.name,description:e.description,baseUrl:e.baseUrl,schemaVersion:_e,advanced:{browserType:e.browserType??"Chromium",viewport:e.viewport??Kt},retries:1,steps:[]};e.environment&&(i.envs=[{name:e.environment,default:!0}]);let a=TO.join(t.rootDir,...e.pathSegments||[]),s=await Ww({test:i,name:e.name,folder:a});return{...i,relativeFilePath:TO.relative(t.rootDir,s)}}import{convertToModelMessages as s2,pruneMessages as l2,stepCountIs as c2}from"ai";import Am from"dedent";var Ns="3",LK=Am`
4454
+ `;let g=_K(d);m+=g;let h=vK({schema:My,model:p("claude-sonnet-4-5-20250929"),system:xK,messages:[{role:"user",content:m}]}),f=[];for await(let v of h.textStream)f.push(v);let S=f.join(""),y;try{let v=JSON.parse(S);y=My.parse(v)}catch(v){i.error({rawResponse:S,parseError:v},"Failed to parse AI response as JSON"),r.addError(`Failed to parse AI response: ${String(v)}. Raw response: ${S}`);return}let E=new Set(d.map(v=>v.moduleId)),T=y.recommendations.filter(v=>E.has(v.moduleId)?!0:(i.warn({moduleId:v.moduleId,moduleName:v.moduleName},"AI recommended a module that doesn't exist"),!1));r.addResult(JSON.stringify({recommendations:T,totalModulesAnalyzed:d.length},null,2))}catch(l){i.error({err:l},"Error in module recommendation"),r.addError(`Failed to recommend modules: ${String(l)}`)}}}),Tm=[PK,AK,wK];var IK=yn({schema:{name:"momentic_environment_list",description:"List environments defined in the project's momentic.config.yaml file.",inputSchema:{}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t,a=jd(o,i);r.addResult(JSON.stringify({environments:a},null,2))}}),bO=[IK];import{streamText as M2}from"ai";import P2 from"path";import{z as I2}from"zod";var vm=new gm;var ai=class extends Qa{constructor(r,n){super(r,n);this.client=r;this.orgId=n}async fetchTestMetadata(r){let n=me(),i=(await te(n)).tests[r];if(i)return Ql(i.relativePath,n)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(r,n){let o=me();return Gi(r,o,Pn)}async fetchIconKnowledgeBase(r){try{return await this.client.fetchIconKnowledgeBase(r)}catch(n){return r.error({err:n},"Failed to fetch icon knowledge base"),null}}};var ia=class{async prepareGoldenScreenshotForComparison(e,r,n){return await new ps(me(),!1).prepareGoldenScreenshotForComparison(e,r,n)}};import TO from"path";import{v4 as OK}from"uuid";async function Rm({project:t,input:e}){try{Mo(e.name)}catch(l){throw new ot(`${l} when validating the test entity name`)}if(!e.baseUrl&&!e.environment)throw new ot("Either 'baseUrl' or 'environment' must be provided when creating a test.");let r=await te(t);if(Object.values(r.tests).find(l=>l.name===e.name))throw new ot(`A test with the name "${e.name}" already exists. Please use a different name.`);let i={id:OK(),name:e.name,description:e.description,baseUrl:e.baseUrl,schemaVersion:_e,advanced:{browserType:e.browserType??"Chromium",viewport:e.viewport??Kt},retries:1,steps:[]};e.environment&&(i.envs=[{name:e.environment,default:!0}]);let a=TO.join(t.rootDir,...e.pathSegments||[]),s=await Ww({test:i,name:e.name,folder:a});return{...i,relativeFilePath:TO.relative(t.rootDir,s)}}import{convertToModelMessages as s2,pruneMessages as l2,stepCountIs as c2}from"ai";import Am from"dedent";var Ns="3",LK=Am`
4455
4455
  <ai-actions>
4456
4456
  AI actions (type: AI_ACTION_DYNAMIC) are special steps that dynamically generate up to 15 sub-steps to achieve a complex goal. They are useful for:
4457
4457
  - Multi-step workflows that require decision-making (e.g., "Find and click the first available appointment slot")
@@ -4735,10 +4735,10 @@ ${n}`:`${e}
4735
4735
 
4736
4736
  ${vO}
4737
4737
 
4738
- ${n}`}import{tool as zK}from"ai";import{z as HK}from"zod";import NK from"path";function AO(t,e){return e?[{type:"text",text:`<${e}>`},...t,{type:"text",text:`</${e}>`}]:t}function ne({text:t,xmlTag:e}){return AO([{type:"text",text:t}],e)}function DK({imageDataUri:t,xmlTag:e}){return AO([{type:"media",data:t,mediaType:"image/jpeg"}],e)}function we(t){if(t.length===0)throw new ot("No content parts provided to construct the tool response content.");return{type:"content",value:t}}async function $n(t,e){let r=t.getActivePage(),n=await t.getBrowserState({skipWait:!1}),o=["### Page state",`- Page URL: ${r.url()}`,`- Page Title: ${await r.title()}`,"- Page Snapshot:","```xml",n.serialize(),"```"].join(`
4739
- `);return e!==void 0&&Pe(o)>e?ne({text:["### Page state",`- Page URL: ${r.url()}`,`- Page Title: ${await r.title()}`,"- Page Snapshot:","<WARNING>","The page state was too long and we had to truncate the page state.","</WARNING>"].join(`
4740
- `),xmlTag:"PageState"}):ne({text:o,xmlTag:"PageState"})}async function kK(t){let r=(await t.screenshot({retries:2})).toString("base64");return DK({imageDataUri:r,xmlTag:"Screenshot"})}async function FK(t,e,r){let n=await ee(t),o=await pt(NK.join(t.rootDir,e),r,n);try{let a=new et({baseUrl:Cr(),apiKey:xr(),logger:r}),s=await Vr(r,a,t),c=Go({orgId:xt(),client:a,gitMetadata:s,regenerateCache:!1,alwaysSaveCache:!1,noCache:!1,bustOldestCachePercentage:void 0}),{steps:l,beforeSteps:u,afterSteps:d}=await Rd({cacheStorage:c,logger:r,schemaVersion:o.schemaVersion,stepLists:{steps:o.steps,beforeSteps:o.beforeSteps,afterSteps:o.afterSteps},testId:o.id});o.beforeSteps=u,o.steps=l,o.afterSteps=d}catch(a){r.error({err:a},"Failed to resolve step cache entries for copilot test view")}let i=[];return i.push("### Test"),i.push(`Name: ${o.name}`),o.description&&i.push(`Description: ${o.description}`),i.push(""),o.beforeSteps&&o.beforeSteps.length>0&&(i.push(Fd(o.beforeSteps,"Setup Steps")),i.push("")),i.push(Fd(o.steps,"Main Steps")),o.afterSteps&&o.afterSteps.length>0&&(i.push(""),i.push(Fd(o.afterSteps,"Teardown Steps"))),ne({text:i.join(`
4741
- `),xmlTag:"TestContent"})}async function wO(t,e){let[r,n]=await Promise.all([$n(t,e),kK(t)]);return we([...r,...n])}async function Py(t,e,r){return we(await FK(t,e,r))}function UK(t,e=2e4){let r={};for(let[n,o]of Object.entries(t)){if(typeof o=="object"&&o!==null){let i=JSON.stringify(o,null,2);if(Pe(i)>e){r[n]="[too large truncated]";continue}r[n]=o;continue}r[n]=o}return r}function BK(t,e){let r={},n=0,o=Object.entries(t).map(([i,a])=>{let s=JSON.stringify(a,null,2),c=Pe(s);return{key:i,value:a,tokens:c}}).sort((i,a)=>i.tokens-a.tokens);for(let{key:i,value:a,tokens:s}of o)n+s<=e&&(r[i]=a,n+=s);return r}function aa(t,e){let r=e?.tokenLimit,n=e?.perItemLimit??2e4,o=t.toObjectCopy(),i=JSON.stringify(o,null,2);if(r===void 0)return ne({text:i,xmlTag:"EnvironmentVariables"});if(Pe(i)<=r)return ne({text:i,xmlTag:"EnvironmentVariables"});let s=UK(o,n),c=JSON.stringify(s,null,2);if(Pe(c)<=r)return ne({text:c,xmlTag:"EnvironmentVariables"});let u=BK(s,r);return ne({text:JSON.stringify(u,null,2),xmlTag:"EnvironmentVariables"})}async function CO(t,e){return we(aa(t,e))}var GK=1,xO=t=>({name:"get_browser_state",tool:zK({description:"Return the current browser state, including URL, title, and serialized accessibility snapshot.",inputSchema:HK.object({}),toModelOutput:r=>r,execute:async()=>{let r=t.controller.browser,n=t.conversationTokenTarget/GK;return wO(r,n)}})});import{tool as HO}from"ai";import t2 from"fs";import _m from"path";import{z as Ve}from"zod";var zy=Symbol.for("immer-nothing"),Dc=Symbol.for("immer-draftable"),Ir=Symbol.for("immer-state");function er(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var la=Object.getPrototypeOf;function ca(t){return!!t&&!!t[Ir]}function si(t){return t?OO(t)||Array.isArray(t)||!!t[Dc]||!!t.constructor?.[Dc]||zc(t)||Hc(t):!1}var jK=Object.prototype.constructor.toString();function OO(t){if(!t||typeof t!="object")return!1;let e=la(t);if(e===null)return!0;let r=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===jK}function kc(t,e){ua(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function ua(t){let e=t[Ir];return e?e.type_:Array.isArray(t)?1:zc(t)?2:Hc(t)?3:0}function Fc(t,e){return ua(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function Iy(t,e){return ua(t)===2?t.get(e):t[e]}function LO(t,e,r){let n=ua(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function VK(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function zc(t){return t instanceof Map}function Hc(t){return t instanceof Set}function sa(t){return t.copy_||t.base_}function Ny(t,e){if(zc(t))return new Map(t);if(Hc(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=OO(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[Ir];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let a=o[i],s=n[a];s.writable===!1&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(n[a]={configurable:!0,writable:!0,enumerable:s.enumerable,value:t[a]})}return Object.create(la(t),n)}else{let n=la(t);if(n!==null&&r)return{...t};let o=Object.create(n);return Object.assign(o,t)}}function Hy(t,e=!1){return xm(t)||ca(t)||!si(t)||(ua(t)>1&&(t.set=t.add=t.clear=t.delete=$K),Object.freeze(t),e&&Object.entries(t).forEach(([r,n])=>Hy(n,!0))),t}function $K(){er(2)}function xm(t){return Object.isFrozen(t)}var Dy={};function da(t){let e=Dy[t];return e||er(0,t),e}function WK(t,e){Dy[t]||(Dy[t]=e)}var Uc;function NO(){return Uc}function qK(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function _O(t,e){e&&(da("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function ky(t){Fy(t),t.drafts_.forEach(KK),t.drafts_=null}function Fy(t){t===Uc&&(Uc=t.parent_)}function MO(t){return Uc=qK(Uc,t)}function KK(t){let e=t[Ir];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function PO(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[Ir].modified_&&(ky(e),er(4)),si(t)&&(t=wm(e,t),e.parent_||Cm(e,t)),e.patches_&&da("Patches").generateReplacementPatches_(r[Ir].base_,t,e.patches_,e.inversePatches_)):t=wm(e,r,[]),ky(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==zy?t:void 0}function wm(t,e,r){if(xm(e))return e;let n=e[Ir];if(!n)return kc(e,(o,i)=>IO(t,n,e,o,i,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return Cm(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,a=!1;n.type_===3&&(i=new Set(o),o.clear(),a=!0),kc(i,(s,c)=>IO(t,n,o,s,c,r,a)),Cm(t,o,!1),r&&t.patches_&&da("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function IO(t,e,r,n,o,i,a){if(ca(o)){let s=i&&e&&e.type_!==3&&!Fc(e.assigned_,n)?i.concat(n):void 0,c=wm(t,o,s);if(LO(r,n,c),ca(c))t.canAutoFreeze_=!1;else return}else a&&r.add(o);if(si(o)&&!xm(o)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;wm(t,o),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Cm(t,o)}}function Cm(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&Hy(e,r)}function YK(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:NO(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Gy;r&&(o=[n],i=Bc);let{revoke:a,proxy:s}=Proxy.revocable(o,i);return n.draft_=s,n.revoke_=a,s}var Gy={get(t,e){if(e===Ir)return t;let r=sa(t);if(!Fc(r,e))return XK(t,r,e);let n=r[e];return t.finalized_||!si(n)?n:n===Oy(t.base_,e)?(Ly(t),t.copy_[e]=By(n,t)):n},has(t,e){return e in sa(t)},ownKeys(t){return Reflect.ownKeys(sa(t))},set(t,e,r){let n=DO(sa(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let o=Oy(sa(t),e),i=o?.[Ir];if(i&&i.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(VK(r,o)&&(r!==void 0||Fc(t.base_,e)))return!0;Ly(t),Uy(t)}return t.copy_[e]===r&&(r!==void 0||e in t.copy_)||Number.isNaN(r)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=r,t.assigned_[e]=!0),!0},deleteProperty(t,e){return Oy(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,Ly(t),Uy(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=sa(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){er(11)},getPrototypeOf(t){return la(t.base_)},setPrototypeOf(){er(12)}},Bc={};kc(Gy,(t,e)=>{Bc[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Bc.deleteProperty=function(t,e){return Bc.set.call(this,t,e,void 0)};Bc.set=function(t,e,r){return Gy.set.call(this,t[0],e,r,t[0])};function Oy(t,e){let r=t[Ir];return(r?sa(r):t)[e]}function XK(t,e,r){let n=DO(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function DO(t,e){if(!(e in t))return;let r=la(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=la(r)}}function Uy(t){t.modified_||(t.modified_=!0,t.parent_&&Uy(t.parent_))}function Ly(t){t.copy_||(t.copy_=Ny(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var JK=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,r,n)=>{if(typeof e=="function"&&typeof r!="function"){let i=r;r=e;let a=this;return function(c=i,...l){return a.produce(c,u=>r.call(this,u,...l))}}typeof r!="function"&&er(6),n!==void 0&&typeof n!="function"&&er(7);let o;if(si(e)){let i=MO(this),a=By(e,void 0),s=!0;try{o=r(a),s=!1}finally{s?ky(i):Fy(i)}return _O(i,n),PO(o,i)}else if(!e||typeof e!="object"){if(o=r(e),o===void 0&&(o=e),o===zy&&(o=void 0),this.autoFreeze_&&Hy(o,!0),n){let i=[],a=[];da("Patches").generateReplacementPatches_(e,o,i,a),n(i,a)}return o}else er(1,e)},this.produceWithPatches=(e,r)=>{if(typeof e=="function")return(a,...s)=>this.produceWithPatches(a,c=>e(c,...s));let n,o;return[this.produce(e,r,(a,s)=>{n=a,o=s}),n,o]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy)}createDraft(t){si(t)||er(8),ca(t)&&(t=QK(t));let e=MO(this),r=By(t,void 0);return r[Ir].isManual_=!0,Fy(e),r}finishDraft(t,e){let r=t&&t[Ir];(!r||!r.isManual_)&&er(9);let{scope_:n}=r;return _O(n,e),PO(void 0,n)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}applyPatches(t,e){let r;for(r=e.length-1;r>=0;r--){let o=e[r];if(o.path.length===0&&o.op==="replace"){t=o.value;break}}r>-1&&(e=e.slice(r+1));let n=da("Patches").applyPatches_;return ca(t)?n(t,e):this.produce(t,o=>n(o,e))}};function By(t,e){let r=zc(t)?da("MapSet").proxyMap_(t,e):Hc(t)?da("MapSet").proxySet_(t,e):YK(t,e);return(e?e.scope_:NO()).drafts_.push(r),r}function QK(t){return ca(t)||er(10,t),kO(t)}function kO(t){if(!si(t)||xm(t))return t;let e=t[Ir],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=Ny(t,e.scope_.immer_.useStrictShallowCopy_)}else r=Ny(t,!0);return kc(r,(n,o)=>{LO(r,n,kO(o))}),e&&(e.finalized_=!1),r}function FO(){let e="replace",r="add",n="remove";function o(p,m,g,h){switch(p.type_){case 0:case 2:return a(p,m,g,h);case 1:return i(p,m,g,h);case 3:return s(p,m,g,h)}}function i(p,m,g,h){let{base_:f,assigned_:S}=p,y=p.copy_;y.length<f.length&&([f,y]=[y,f],[g,h]=[h,g]);for(let E=0;E<f.length;E++)if(S[E]&&y[E]!==f[E]){let T=m.concat([E]);g.push({op:e,path:T,value:d(y[E])}),h.push({op:e,path:T,value:d(f[E])})}for(let E=f.length;E<y.length;E++){let T=m.concat([E]);g.push({op:r,path:T,value:d(y[E])})}for(let E=y.length-1;f.length<=E;--E){let T=m.concat([E]);h.push({op:n,path:T})}}function a(p,m,g,h){let{base_:f,copy_:S}=p;kc(p.assigned_,(y,E)=>{let T=Iy(f,y),v=Iy(S,y),w=E?Fc(f,y)?e:r:n;if(T===v&&w===e)return;let C=m.concat(y);g.push(w===n?{op:w,path:C}:{op:w,path:C,value:v}),h.push(w===r?{op:n,path:C}:w===n?{op:r,path:C,value:d(T)}:{op:e,path:C,value:d(T)})})}function s(p,m,g,h){let{base_:f,copy_:S}=p,y=0;f.forEach(E=>{if(!S.has(E)){let T=m.concat([y]);g.push({op:n,path:T,value:E}),h.unshift({op:r,path:T,value:E})}y++}),y=0,S.forEach(E=>{if(!f.has(E)){let T=m.concat([y]);g.push({op:r,path:T,value:E}),h.unshift({op:n,path:T,value:E})}y++})}function c(p,m,g,h){g.push({op:e,path:[],value:m===zy?void 0:m}),h.push({op:e,path:[],value:p})}function l(p,m){return m.forEach(g=>{let{path:h,op:f}=g,S=p;for(let v=0;v<h.length-1;v++){let w=ua(S),C=h[v];typeof C!="string"&&typeof C!="number"&&(C=""+C),(w===0||w===1)&&(C==="__proto__"||C==="constructor")&&er(19),typeof S=="function"&&C==="prototype"&&er(19),S=Iy(S,C),typeof S!="object"&&er(18,h.join("/"))}let y=ua(S),E=u(g.value),T=h[h.length-1];switch(f){case e:switch(y){case 2:return S.set(T,E);case 3:er(16);default:return S[T]=E}case r:switch(y){case 1:return T==="-"?S.push(E):S.splice(T,0,E);case 2:return S.set(T,E);case 3:return S.add(E);default:return S[T]=E}case n:switch(y){case 1:return S.splice(T,1);case 2:return S.delete(T);case 3:return S.delete(g.value);default:return delete S[T]}default:er(17,f)}}),p}function u(p){if(!si(p))return p;if(Array.isArray(p))return p.map(u);if(zc(p))return new Map(Array.from(p.entries()).map(([g,h])=>[g,u(h)]));if(Hc(p))return new Set(Array.from(p).map(u));let m=Object.create(la(p));for(let g in p)m[g]=u(p[g]);return Fc(p,Dc)&&(m[Dc]=p[Dc]),m}function d(p){return ca(p)?u(p):p}WK("Patches",{applyPatches_:l,generatePatches_:o,generateReplacementPatches_:c})}var Or=new JK,kKe=Or.produce,UO=Or.produceWithPatches.bind(Or),FKe=Or.setAutoFreeze.bind(Or),UKe=Or.setUseStrictShallowCopy.bind(Or),BKe=Or.applyPatches.bind(Or),zKe=Or.createDraft.bind(Or),HKe=Or.finishDraft.bind(Or);import{v4 as ZK}from"uuid";FO();function Ds({logger:t,socket:e,baseState:r,recipe:n,description:o}){let[i,a,s]=UO(r,n),c={id:ZK(),patches:a,inversePatches:s,description:o,timestamp:Date.now()};return e?.emit("copilotPatch",c),t.info({description:o},"Emitting copilot patch"),{patch:c,newState:i}}import e2 from"fs";import ks from"path";function BO(t){let e=t.subDir?ks.join(t.project.rootDir,t.subDir):t.project.rootDir,r=`${ze(t.name)}.module.yaml`,n=ks.join(e,r),o=ks.relative(t.project.rootDir,n),i=e2.statSync(n);return{type:Se.MODULE,name:t.name,id:t.moduleId,description:t.description??void 0,relativePath:o,fullFilePath:n,platformSep:ks.sep,fullPathSegments:n.split(ks.sep),relativePathSegments:o.split(ks.sep),fileName:r,lastModified:i.mtime,createdAt:i.birthtime}}import{randomUUID as jy}from"crypto";import{z as zO}from"zod";function Gc(t){let e=t.config.ai?.aiAction??!1,r=e?"The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use. The AI_ACTION_DYNAMIC is an AI action that will dynamically generate up to 15 steps to achieve a goal.":"The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use.";return e?zO.discriminatedUnion("type",[Dh,kh,nT]).describe(r):zO.discriminatedUnion("type",[Dh,kh]).describe(r)}async function Fs(t,e,r){switch(t.type){case"PRESET_ACTION":{let n=vu(t.action),o=t.envKey&&Nh.includes(n.type)?t.envKey:void 0;return{type:"PRESET_ACTION",command:n,id:jy(),envKey:o}}case"MODULE":{let{selector:n,inputs:o}=t.module,{entity:i,momenticFiles:a}=await Vn(e,n,"module"),s=await dn(i,a,r);oT(o,s);let l=Object.keys(o??{}).length>0?o??{}:(s.parameters?.length??0)>0?{}:void 0,u={id:jy(),inputs:l};return{...s,...u,type:"RESOLVED_MODULE"}}case"AI_ACTION_DYNAMIC":{if(!(e.config.ai?.aiAction??!1))throw new Error("AI actions are disabled. Enable AI actions in your momentic.config.yaml by setting 'ai.aiAction: true' to use this feature.");return{type:"AI_ACTION_DYNAMIC",text:t.text,id:jy()}}default:return(o=>{throw new Error("You missed a case in the switch above")})(t)}}async function GO({moduleMetadata:t,steps:e,momenticFiles:r,project:n}){let{stepsToSave:o}=await it({stepLists:{steps:e}});_r({content:{...t,steps:o.steps},schemaVersion:_e,momenticFiles:r,project:n})}var jO=t=>({name:"module_create",tool:HO({description:"Create a module. If startIndex is provided, the steps will be extracted from the current test, a module will be created with those steps, and the test will be updated to reference the new module. If no startIndex is provided, an unreferenced module will be created. Automatically splices and repairs the test to reference the new module.",inputSchema:Ve.object({name:Ve.string(),description:Ve.string(),enabled:Ve.boolean().default(!0),parameters:Ve.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:Ve.record(Ve.string(),Ve.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Ve.record(Ve.string(),Ve.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:Ve.record(Ve.string(),Ve.string()).optional().describe("Input parameters to pass to the new module when it's inserted into the test. Keys must match the module's defined parameters. Only relevant if startIndex is provided."),subDir:Ve.string().optional().describe("sub directory to create the module in. If not provided, the module will be created in the project's root directory."),startIndex:Ve.number().optional().describe("Start index of steps to extract from the current test (0-based)."),endIndex:Ve.number().optional().describe("End index of steps to extract from the current test (exclusive). If not provided, extracts just the startIndex.")}),execute:async r=>{let{project:n,logger:o,testPath:i,socket:a,saveChangesToDisk:s}=t,c=r.startIndex??0,l=r.endIndex??c+1,u=await ee(n);if(Object.values(u.modules).find(f=>f.name===r.name))return we(ne({text:`Error: A module with the name "${r.name}" already exists. Please use a different name.`,xmlTag:"Error"}));if(r.parameters!==void 0){let f=r.defaultParameters?Object.keys(r.defaultParameters):[],S=r.parameterEnums?Object.keys(r.parameterEnums):[],y=new Set([...f,...S]);for(let E of y)if(!r.parameters.includes(E))return we(ne({text:`Error: Default parameter "${E}" is not defined in parameters array. Available parameters: ${r.parameters.join(", ")}`,xmlTag:"Error"}))}let p=[];if(r.startIndex!==void 0){if(!i)return we(ne({text:"Error: testPath is required when extracting steps from the current test.",xmlTag:"Error"}));let f=await pt(_m.join(n.rootDir,i),o,u);if(c<0||c>=f.steps.length)return we(ne({text:`Error: startIndex ${c} is out of bounds. Test has ${f.steps.length} steps.`,xmlTag:"Error"}));if(l<=c||l>f.steps.length)return we(ne({text:`Error: endIndex ${l} is out of bounds. Must be between ${c+1} and ${f.steps.length}.`,xmlTag:"Error"}));p=f.steps.slice(c,l);for(let S of p)if(S.type==="RESOLVED_MODULE")return we(ne({text:"Error: Modules cannot be nested. Please select steps that do not include module references.",xmlTag:"Error"}))}let m=r.subDir?_m.join(n.rootDir,r.subDir):n.rootDir;r.subDir&&t2.mkdirSync(m,{recursive:!0});let g=await Hd({name:r.name,description:r.description??"",enabled:r.enabled??!0,steps:p,folder:m,project:n}),h=BO({project:n,name:r.name,moduleId:g.moduleId,subDir:r.subDir,description:g.description??void 0});if(u.modules[g.moduleId]=h,r.parameters!==void 0||r.defaultParameters!==void 0||r.parameterEnums!==void 0){let f={moduleId:g.moduleId,name:r.name,description:r.description??g.description,enabled:r.enabled??g.enabled,parameters:r.parameters??[],defaultParameters:r.defaultParameters,parameterEnums:r.parameterEnums};await GO({moduleMetadata:f,steps:p,momenticFiles:u,project:n}),g={...g,name:r.name,description:r.description??g.description,enabled:r.enabled??g.enabled,parameters:r.parameters??[],defaultParameters:r.defaultParameters,parameterEnums:r.parameterEnums}}if(r.startIndex!==void 0){let f=await pt(_m.join(n.rootDir,i),o,u),S={steps:f.steps??[],beforeSteps:f.beforeSteps??[],afterSteps:f.afterSteps??[]},y={type:"MODULE",module:{selector:{id:g.moduleId},inputs:r.moduleInputs??{}}},E;try{E=await Fs(y,n,o)}catch(w){return we(ne({text:`Module "${r.name}" was created successfully, but could not be added to the test. ${String(w)}`,xmlTag:"Error"}))}let T=w=>{w.steps.splice(c,l-c,E)},{newState:v}=Ds({logger:o,socket:a,baseState:S,recipe:T,description:`Create module "${r.name}" from steps ${c}-${l-1}`});if(s){let{stepsToSave:w,moduleUpdates:C}=await it({stepLists:v});C.forEach(_=>{_r({content:_,schemaVersion:_e,momenticFiles:u,project:n})}),Er({relativeTestPath:i,steps:w,schemaVersion:_e,project:n})}}return we(ne({text:JSON.stringify(g,null,2),xmlTag:"ModuleResult"}))}})});function r2(t,e,r,n,o){if(t===void 0&&e!==void 0)throw new ot("Validation Error: startIndex is required when endIndex is provided.");if(t!==void 0&&e===void 0&&r===0)throw new ot("Validation Error: steps are required when startIndex is provided without an endIndex.");if(t!==void 0&&(t>n||t<0))throw new ot(`Validation Error: startIndex is out of bounds for module with ${n} steps.`);if(e!==void 0&&t===void 0)throw new ot("Validation Error: startIndex is required when endIndex is provided.");if(e!==void 0&&t!==void 0&&e<t)throw new ot("Validation Error: endIndex must be greater than or equal to startIndex.");if(e!==void 0&&(e>n||e<0))throw new ot(`Validation Error: endIndex ${e} is out of bounds for module with ${n} steps.`);let i=t??n;if((e??i)===i&&r===0&&!o)throw new ot("Validation Error: Nothing to change. Provide steps, a valid delete range, or metadata updates.")}var VO=t=>{let e=Gc(t.project);return{name:"module_update",tool:HO({description:"Edit a module's steps and/or metadata. Provide startIndex (and optional endIndex) to replace or remove that range; omit endIndex to insert at startIndex; omit both indices to append new steps. Use an empty steps array with both indices to delete the range. Optionally update metadata like parameters. Omit both indices and steps to only update metadata.",inputSchema:Ve.object({selector:Po,steps:e.array(),startIndex:Ve.number().optional(),endIndex:Ve.number().optional(),description:Ve.string().optional().describe("New description for the module."),enabled:Ve.boolean().optional().describe("New enabled state for the module."),parameters:Ve.string().array().optional().describe("New array of parameter names, e.g., ['apiKey', 'userId']. Replaces all existing parameters, resets default parameters and parameter enums if set."),defaultParameters:Ve.record(Ve.string(),Ve.string()).optional().describe("New default values, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Ve.record(Ve.string(),Ve.string().array()).optional().describe("New enum options, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters.")}),execute:async n=>{let{project:o,logger:i,socket:a,testPath:s,saveChangesToDisk:c}=t,l=await Promise.all(n.steps.map(E=>Fs(E,o,i))),{entity:u,momenticFiles:d}=await Vn(o,n.selector,"module"),p=await dn(u,d,i),m=l.find(E=>!Mh(E));if(m)return we(ne({text:`Error: step type ${m.type} cannot be added to a module.`,xmlTag:"Error"}));let g=n.description!==void 0||n.enabled!==void 0||n.parameters!==void 0||n.defaultParameters!==void 0||n.parameterEnums!==void 0;try{r2(n.startIndex,n.endIndex,n.steps.length,p.steps.length,g)}catch(E){return we(ne({text:String(E),xmlTag:"Error"}))}let h=p.steps;if(n.steps.length>0||n.startIndex!==void 0||n.endIndex!==void 0){h=[...p.steps];let E=n.startIndex!==void 0?n.startIndex:h.length,T=n.endIndex!==void 0?n.endIndex:E;h.splice(E,T-E,...l)}let f={moduleId:p.moduleId,name:p.name,description:n.description??p.description,enabled:n.enabled??p.enabled,parameters:n.parameters??p.parameters,defaultParameters:n.defaultParameters??p.defaultParameters,parameterEnums:n.parameterEnums??p.parameterEnums};n.parameters!==void 0&&(f.defaultParameters=n.defaultParameters??{},f.parameterEnums=n.parameterEnums??{});let S=null;if(s){let E=await pt(_m.join(o.rootDir,s),i,d);S={steps:E.steps??[],beforeSteps:E.beforeSteps??[],afterSteps:E.afterSteps??[]}}c&&await GO({moduleMetadata:f,steps:h,momenticFiles:d,project:o}),s&&S&&Ds({logger:i,socket:a,baseState:S,recipe:T=>{let v=w=>{for(let C of w)C.type==="RESOLVED_MODULE"&&C.moduleId===p.moduleId&&(C.steps=h)};v(T.steps),v(T.beforeSteps),v(T.afterSteps)},description:`Update module "${p.name}"`});let y={...f,stepCount:h.length};return we(ne({text:JSON.stringify(y,null,2),xmlTag:"ModuleResult"}))}})}};import{tool as Pm}from"ai";import{randomUUID as Mm}from"crypto";import{z as li}from"zod";var n2=t=>({name:"preview_preflight",tool:Pm({description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:li.object({description:li.string().describe("Description of the element to preview.")}),toModelOutput:r=>r,execute:async({description:r})=>{let{controller:n,logger:o,testContext:i}=t;try{let a=await n.locateElement({description:r,disableCache:!0,skipWait:!0,logger:o,testContext:i});a.resolution.locator&&await Promise.all([n.browser.scrollIntoViewIfNeeded(a.resolution.locator),n.browser.highlight(a.resolution.locator)]);let s=[...ne({text:`Found element matching description: ${a.target.id}`,xmlTag:"Result"})];return a.target.nodeOnlySerializedHtml&&s.push(...ne({text:`HTML: ${a.target.nodeOnlySerializedHtml}`})),s.push(...await $n(n.browser)),we(s)}catch(a){let s=[...ne({text:`Failed to find any element matching description: ${a}`,xmlTag:"Error"}),...await $n(n.browser)];return we(s)}}})}),o2=t=>({name:"preview_ensure",tool:Pm({description:"Confirm page state.",inputSchema:li.object({assertion:li.string().describe("Assertion to confirm page state.")}),toModelOutput:r=>r,execute:async({assertion:r})=>{let{logger:n,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:c,testContext:l}=t,u={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:r,id:Mm()},id:Mm()},d=await ym({step:u,controller:i,storage:o,codeEvalTools:a,logger:n,socket:s,orgId:c,testContext:l}),p=[];return d?d.status==="SUCCESS"?p.push(...ne({text:`Assertion is true: ${d.message}`,xmlTag:"SuccessfulResult"})):p.push(...ne({text:`Assertion is false: ${d.message}`,xmlTag:"Error"})):p.push(...ne({text:"Assertion executed with unknown result.",xmlTag:"Error"})),p.push(...await $n(i.browser)),we(p)}})}),i2=t=>({name:"preview_step",tool:Pm({description:"Execute a step without adding it to the test.",inputSchema:li.object({command:Oa}),toModelOutput:r=>r,execute:async({command:r})=>{let{logger:n,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:c,testContext:l}=t,u=vu(r),d={type:"PRESET_ACTION",command:u,id:Mm()},p=await ym({step:d,controller:i,storage:o,codeEvalTools:a,logger:n,socket:s,orgId:c,testContext:l}),m=[];return p?p.status==="SUCCESS"?m.push(...ne({text:`Step Execution successful: ${p.message}`,xmlTag:"SuccessfulResult"})):m.push(...ne({text:`Step Execution failed: ${p.message}`,xmlTag:"Error"})):m.push(...ne({text:"Step Execution errored for an unknown reason.",xmlTag:"Error"})),m.push(...await $n(i.browser)),m.push(...aa(l)),we(m)}})}),a2=t=>{let{project:e}=t;return e.config.ai?.aiAction??!1?{name:"preview_ai_action",tool:Pm({description:"Execute an AI action without adding it to the test. This will dynamically generate and run steps to achieve the goal. Note this tool will update and move your test state forward, so if it fails you must rerun the test up to this step before trying again.",inputSchema:li.object({text:li.string().describe("The goal description for the AI action. Supports handlebars templates (ex: {{env.PASSWORD}})"),retries:li.number().optional()}),toModelOutput:o=>o,execute:async({text:o,retries:i})=>{let{logger:a,storage:s,controller:c,codeEvalTools:l,socket:u,orgId:d,testContext:p}=t,m={type:"AI_ACTION_DYNAMIC",text:o,id:Mm(),retries:i},g=await ym({step:m,controller:c,storage:s,codeEvalTools:l,logger:a,socket:u,orgId:d,testContext:p}),h=[];return g?g.status==="SUCCESS"?h.push(...ne({text:`AI action completed successfully: ${g.message??"Goal achieved"}`,xmlTag:"SuccessfulResult"})):h.push(...ne({text:`AI action failed: ${g.message??"Unknown error while previewing AI action"}`,xmlTag:"Error"})):h.push(...ne({text:"AI action executed with unknown result.",xmlTag:"Error"})),h.push(...await $n(c.browser)),h.push(...aa(p)),we(h)}})}:void 0},$O=[n2,o2,i2,a2];import{tool as Wy}from"ai";import JO from"path";import{z as jc}from"zod";import{tool as Vy}from"ai";import WO from"path";import{z as ci}from"zod";var $y=t=>{throw new Error(`Unknown test section: ${t}`)},Im=ci.enum(["setup","teardown","main"]).describe("Test section to modify: 'setup' corresponds to beforeSteps (steps that run before the test), 'teardown' corresponds to afterSteps (steps that run after the test), 'main' is synonymous with steps (the main test steps)");function qO(t,e){switch(e){case"setup":return t.beforeSteps;case"teardown":return t.afterSteps;case"main":return t.steps;default:return $y(e)}}var KO=t=>{let e=Gc(t.project);return{name:"test_insert_step",tool:Vy({description:"Insert a step or module into the test.",inputSchema:ci.object({index:ci.number(),step:e,targetSection:Im.default("main")}),execute:async n=>{let{project:o,logger:i,testPath:a,socket:s,saveChangesToDisk:c}=t,l=await ee(o),u=await pt(WO.join(o.rootDir,a),i,l),d={steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]},p=qO(d,n.targetSection);if(n.index<0||n.index>p.length)return we(ne({text:`Error: Invalid index ${n.index} for inserting into ${n.targetSection} section with ${p.length} steps (must be 0-${p.length})`,xmlTag:"Error"}));let m=await Fs(n.step,o,i),g=f=>{switch(n.targetSection){case"setup":f.beforeSteps.splice(n.index,0,m);break;case"teardown":f.afterSteps.splice(n.index,0,m);break;case"main":f.steps.splice(n.index,0,m);break;default:$y(n.targetSection)}},{newState:h}=Ds({logger:i,socket:s,baseState:d,recipe:g,description:`Insert ${m.type} step at index ${n.index} in ${n.targetSection}`});if(c){let{stepsToSave:f,moduleUpdates:S}=await it({stepLists:h});S.forEach(y=>{_r({content:y,schemaVersion:_e,momenticFiles:l,project:o})}),Er({relativeTestPath:a,steps:f,schemaVersion:_e,project:o})}return we(ne({text:`Successfully inserted step at index ${n.index} in the ${n.targetSection} section.`,xmlTag:"Result"}))}})}},YO=t=>{let e=Gc(t.project);return{name:"test_splice_steps",tool:Vy({description:"Splice steps in the test. This is the primary tool for replacing, removing, or bulk inserting steps. Never use this as a means to bypass a failure. Examples: Replace step at index 5: splice(startIndex=5, deleteCount=1, steps=[newStep]). Delete step at index 5: splice(startIndex=5, deleteCount=1, steps=[]). Insert multiple steps at index 5: splice(startIndex=5, deleteCount=0, steps=[step1, step2]).",inputSchema:ci.object({startIndex:ci.number(),deleteCount:ci.number().describe("Number of steps to remove. Use 0 to insert without deleting, 1 to replace a single step, or N to delete N steps."),steps:e.array(),targetSection:Im.default("main"),returnTest:ci.boolean().default(!1).describe("Whether or not you want to see the full test after the splice is complete")}),execute:async n=>{let{project:o,logger:i,testPath:a,socket:s,saveChangesToDisk:c}=t,l=await ee(o),u=await pt(WO.join(o.rootDir,a),i,l),d={steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]},p=qO(d,n.targetSection);if(n.startIndex<0||n.startIndex>p.length)return we(ne({text:`Error: Invalid startIndex ${n.startIndex} for splicing ${n.targetSection} section with ${p.length} steps (must be 0-${p.length})`,xmlTag:"Error"}));let m=await Promise.all(n.steps.map(E=>Fs(E,o,i))),g=E=>{switch(n.targetSection){case"setup":E.beforeSteps.splice(n.startIndex,n.deleteCount,...m);break;case"teardown":E.afterSteps.splice(n.startIndex,n.deleteCount,...m);break;case"main":E.steps.splice(n.startIndex,n.deleteCount,...m);break;default:$y(n.targetSection)}},h=n.steps.length,f=n.deleteCount,{newState:S}=Ds({logger:i,socket:s,baseState:d,recipe:g,description:`Splice ${h} step(s) at index ${n.startIndex} in ${n.targetSection}, removing ${f}`});if(c){let{stepsToSave:E,moduleUpdates:T}=await it({stepLists:S});T.forEach(v=>{_r({content:v,schemaVersion:_e,momenticFiles:l,project:o})}),Er({relativeTestPath:a,steps:E,schemaVersion:_e,project:o})}let y=[...ne({text:`Successfully spliced ${h} step(s) at index ${n.startIndex} in the ${n.targetSection} section, removing ${f} step(s).`,xmlTag:"Result"})];return n.returnTest&&y.push(...ne({text:JSON.stringify(await Py(o,a,i),null,2),xmlTag:"TestContent"})),we(y)}})}},XO=t=>({name:"test_get",tool:Vy({description:"Retrieve the full test contents, including simplified cache data on some steps enabling you to inspect resolved locators and debug targeting issues. For context, the caches are just simplified targeting information",inputSchema:ci.object({}),execute:async()=>Py(t.project,t.testPath,t.logger)})});var QO=3,ZO=t=>({name:"get_environment_variables",tool:Wy({description:"Get the current environment variables.",inputSchema:jc.object({}),toModelOutput:r=>r,execute:async()=>{let r=t.conversationTokenTarget/QO;return CO(t.testContext,{tokenLimit:r})}})}),eL=t=>({name:"reset_session",tool:Wy({description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:jc.object({}),toModelOutput:r=>r,execute:async()=>{let{project:r,logger:n,testPath:o,orgId:i,codeEvalTools:a}=t,s=await ee(r),c=await pt(JO.join(r.rootDir,o),n,s),l=c.baseUrl,u,d={};if(!l&&c.envs){let m=c.envs.find(g=>g.default);if(m)try{let g=Gi(m.name,r,n);u=g.name,d=g.variables;let h=g.variables[Rt];typeof h=="string"&&(l=h)}catch(g){n.warn({err:g,envName:m.name},"Failed to resolve environment for reset")}}l||(l="about:blank"),d=await hm({orgId:i,testName:c.name,envName:u,baseEnvVariables:d,parameters:c.parameters,logger:n,localTools:a}),await t.controller.browser.reset({newUrl:l}),t.testContext.reset({baseUrl:l,testName:c.name,currentUrl:t.controller.browser.url(),variablesFromEnvironment:d,envName:u});let p=[...ne({text:`Session reset to ${l}.`,xmlTag:"Result"}),...await $n(t.controller.browser),...aa(t.testContext)];return we(p)}})}),tL=t=>({name:"run_step",tool:Wy({description:"Run the step in the test at the given startIndex. If there is no endIndex, the step at the startIndex will be executed. EndIndex is the last step that is run (end index is inclusive).",inputSchema:jc.object({fromIndex:jc.number(),toIndex:jc.number().optional(),targetSection:Im.default("main")}),toModelOutput:r=>r,execute:async({fromIndex:r,toIndex:n,targetSection:o})=>{let{project:i,logger:a,testPath:s,storage:c,controller:l,codeEvalTools:u,socket:d,orgId:p,testContext:m,conversationTokenTarget:g}=t,h=r,f=n??h,S=await ee(i),y=await pt(JO.join(i.rootDir,s),a,S),E;switch(o){case"setup":E=y.beforeSteps??[];break;case"teardown":E=y.afterSteps??[];break;case"main":E=y.steps;break;default:return(W=>{throw new Error(`Unknown test section: ${W}`)})(o)}if(h<0||h>=E.length)return we(ne({text:`Error: startIndex is out of bounds for ${o} section with ${E.length} steps.`,xmlTag:"Error"}));if(f<h)return we(ne({text:"Error: toIndex must be greater than or equal to fromIndex.",xmlTag:"Error"}));if(f>=E.length)return we(ne({text:`Error: toIndex is out of bounds for ${o} section with ${E.length} steps.`,xmlTag:"Error"}));let T=E.slice(h,f+1);if(T.length===0)return we(ne({text:"Error: No steps were executed.",xmlTag:"Error"}));l.setOpen();let{results:v}=await _y({steps:T,controller:l,storage:c,codeEvalTools:u,logger:a,socket:d,orgId:p,testContext:m});if(!v||v.length===0)return we(ne({text:"Error: No steps were executed.",xmlTag:"Error"}));let w=v.at(-1);if(!w)return we(ne({text:"Error: No steps were executed.",xmlTag:"Error"}));if(w.status!=="SUCCESS"){let B=h+v.length-1;return we(ne({text:`Error: Step at index ${B} failed: ${w.message}`,xmlTag:"Error"}))}let C=o==="main"?"":` in ${o}`,_=h===f?`Step at index ${f}${C}`:`Steps ${h}-${f}${C}`,N=[];if(w.status==="SUCCESS"){let B=`${_} executed successfully. Last step result: ${w.message}`;N.push(...ne({text:B,xmlTag:"Result"})),w.data&&N.push(...ne({text:`Data: ${JSON.stringify(w.data,null,2)}`,xmlTag:"ResultData"}))}let U=g/QO,[j,O]=await Promise.all([$n(l.browser,U),aa(m,{tokenLimit:U})]);return we([...N,...j,...O])}})});var rL=[xO,ZO,tL,XO,eL,KO,YO,jO,VO,...$O];var u2=1e5,nL=8e4,qy=2,oL="[trimmed: omitted due to context budget]",Ky=50,d2=1600;function p2(t,e){return typeof t=="object"&&t!==null&&t.type===e}function m2(t,e,r){let n=0,o=[];for(let i of t){let a=i.content;if(!Array.isArray(a)){o.push(i);continue}let s=[];for(let c of a){if(n>=e){s.push(c);continue}if(!p2(c,r)){s.push(c);continue}if(r==="image"){n>=e?s.push(c):n+=d2;continue}let l=r==="tool-result"?"output":"input",u=r==="tool-result"?c.output:c.input;if(u===void 0||u===oL){s.push(c);continue}let d=Pe(u);n+=d,s.push({...c,[l]:oL})}s.length!==0&&o.push({...i,content:s})}return{messages:o,trimmedTokens:n}}function h2(t){let e=t[0];return e?"parts"in e&&Array.isArray(e.parts):!1}function g2(t){return l2({messages:t,reasoning:"before-last-message",toolCalls:[{type:"before-last-10-messages",tools:["momentic_module_get","momentic_module_recommend","get_environment_variables"]},{type:"before-last-5-messages",tools:["run_step","preview_ai_action"]},{type:"before-last-3-messages",tools:["test_get","reset_session","test_insert_step","test_splice_steps","preview_ensure","momentic_module_create"]},{type:"before-last-2-messages",tools:["observe_page","momentic_module_list","momentic_module_change"]},{type:"before-last-1-messages",tools:["preview_preflight","preview_step"]}],emptyMessages:"remove"})}var f2=["tool-result","image","tool-call"],S2=.3;function Vc(t,e,r){let n=[...t];for(let o of f2){let i=Pe(n);if(i<=e)break;let a=i-e,s=m2(n,a,o);n=s.messages,s.trimmedTokens>0&&r.debug({contentType:o,trimmedTokens:s.trimmedTokens,newTokenCount:Pe(n)},"Trimmed content")}return n}function y2(t,e,r){let n=Pe(t);if(n<=e||t.length<=1)return t;let o=t[0],i=[],a=[];if(t.length>qy+1?(i=t.slice(1,t.length-qy),a=t.slice(t.length-qy)):a=t.slice(1),i.length>0){i=Vc(i,e,r);let u=[o,...i,...a];if(n=Pe(u),n<=e)return u}let s=Pe(i),c=s/e;if(c<S2){if(a.length>1){let u=a[a.length-1],d=[...i,...a.slice(0,-1)],p=Vc(d,e,r),m=[o,...p,u];if(n=Pe(m),n<=e)return m;let g=Vc([...p,u],e,r),h=[o,...g];if(n=Pe(h),n<=e)return h}else if(a.length===1){let u=[...i,...a],d=Vc(u,e,r),p=[o,...d];if(n=Pe(p),n<=e)return p}}else for(r.debug({headBudgetRatio:c,middleMsgTokens:s,targetTokens:e},"Middle exceeds 30% budget, removing messages");i.length>0;){i.shift();let u=[o,...i,...a];if(n=Pe(u),n<=e)return u}a=Vc(a,e,r);let l=[o,...i,...a];if(n=Pe(l),n<=e)return l;for(;a.length>0;)if(a.shift(),l=[o,...i,...a],n=Pe(l),n<=e)return l;return n>e&&r.warn({targetTokens:e,finalTokenCount:n,remainingMessages:l.length},"Unable to meet token target after all pruning phases"),l}function E2(t,e,r,n){let o=g2(t),i=Pe(o);return i>e&&(n.debug({projected:i,threshold:e,target:r},"Context exceeds threshold, pruning messages"),o=y2(o,r,n)),o}function Om(t){let{testPath:e,messages:r,logger:n,session:o,sessionId:i,hooks:a={},saveChangesToDisk:s=!1}=t,{onStepFinish:c,onPrepareStep:l,onChunk:u,onError:d,onFinish:p}=a,m=xr(),g=xt(),h=Cr(),f=me(),S=new et({apiKey:m,baseUrl:h,logger:n}),y=new ai(S,g),E=new On({httpClient:new zt({baseUrl:S.baseUrl,apiKey:S.apiKey,logger:n,mode:"interactive"}),fakerSeed:f.config.advanced?.fakerConstantSeed?qa:void 0}),T={project:f,apiKey:m,orgId:g,baseUrl:h,sessionId:i,logger:n,storage:y,codeEvalTools:E,saveChangesToDisk:s,testPath:e,testContext:o.context,controller:o.controller,socket:o.socket,conversationTokenTarget:nL},v=Tm.reduce((O,{name:B,builder:W})=>(O[B]=W(T),O),{}),w={};for(let O of rL){let B=O(T);B&&(w[B.name]=B.tool)}let C={...v,...w},_=Sm(i),N=async O=>{let{messages:B}=O;l&&await l(B);let W=E2(B,u2,nL,n),q=Pe(B);return q>rR&&n.debug({originalCount:B.length,prunedCount:W.length,originalTokens:q,prunedTokens:Pe(W)},"Prepared messages for copilot step"),{...O,messages:W}},U={model:_("claude-sonnet-4-5-20250929"),stopWhen:c2(Ky),maxRetries:4,system:RO(f),tools:C,prepareStep:N,onStepFinish:c,onChunk:u,onError:d,onFinish:async({finishReason:O,usage:B,text:W,response:q})=>{n.info({finishReason:O,usage:B,sessionId:i},"Full copilot turn finished"),p&&await p({finishReason:O,usage:B,text:W,response:q})}},j=h2(r)?s2(r,{tools:U.tools}):r;return{...U,messages:j}}var WYe=new Error("timeout while waiting for mutex to become available"),qYe=new Error("mutex already locked"),b2=new Error("request for lock canceled"),T2=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},Yy=class{constructor(e,r=b2){this._value=e,this._cancelError=r,this._queue=[],this._weightedWaiters=[]}acquire(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,o)=>{let i={resolve:n,reject:o,weight:e,priority:r},a=iL(this._queue,s=>r<=s.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return T2(this,arguments,void 0,function*(r,n=1,o=0){let[i,a]=yield this.acquire(n,o);try{return yield r(i)}finally{a()}})}waitForUnlock(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,r)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),v2(this._weightedWaiters[e-1],{resolve:n,priority:r})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let r=this._value;this._value-=e.weight,e.resolve([r,this._newReleaser(e.weight)])}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let r=this._weightedWaiters[e-1];r&&(r.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let r=this._value;r>0;r--){let n=this._weightedWaiters[r-1];if(!n)continue;let o=n.findIndex(i=>i.priority<=e);(o===-1?n:n.splice(0,o)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,r){return(this._queue.length===0||this._queue[0].priority<r)&&e<=this._value}};function v2(t,e){let r=iL(t,n=>e.priority<=n.priority);t.splice(r+1,0,e)}function iL(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1}var R2=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},Lm=class{constructor(e){this._semaphore=new Yy(1,e)}acquire(){return R2(this,arguments,void 0,function*(e=0){let[,r]=yield this._semaphore.acquire(1,e);return r})}runExclusive(e,r=0){return this._semaphore.runExclusive(()=>e(),1,r)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};var Xy=class{mutexes=new Map;activeControllers=new Map;async startOrReplace(e,r){r.throwIfAborted(),this.mutexes.has(e)||this.mutexes.set(e,new Lm);let o=await this.mutexes.get(e).acquire();try{let i=this.activeControllers.get(e);i&&!i.signal.aborted&&i.abort(new Error("Superseded by newer momentic_test_edit invocation. Stop executing edit_test requests to this test and ask the user what to do next."));let a=new AbortController;return this.activeControllers.set(e,a),{signal:AbortSignal.any([r,a.signal]),release:()=>{this.activeControllers.get(e)===a&&this.activeControllers.delete(e),this.activeControllers.has(e)||this.mutexes.delete(e)}}}finally{o()}}},aL=new Xy;import Us from"dedent";function A2(){let t=Object.entries(vh).map(([e,r])=>`- **${e}**: ${r}`).join(`
4738
+ ${n}`}import{tool as zK}from"ai";import{z as HK}from"zod";import NK from"path";function AO(t,e){return e?[{type:"text",text:`<${e}>`},...t,{type:"text",text:`</${e}>`}]:t}function oe({text:t,xmlTag:e}){return AO([{type:"text",text:t}],e)}function DK({imageDataUri:t,xmlTag:e}){return AO([{type:"media",data:t,mediaType:"image/jpeg"}],e)}function we(t){if(t.length===0)throw new ot("No content parts provided to construct the tool response content.");return{type:"content",value:t}}async function $n(t,e){let r=t.getActivePage(),n=await t.getBrowserState({skipWait:!1}),o=["### Page state",`- Page URL: ${r.url()}`,`- Page Title: ${await r.title()}`,"- Page Snapshot:","```xml",n.serialize(),"```"].join(`
4739
+ `);return e!==void 0&&Pe(o)>e?oe({text:["### Page state",`- Page URL: ${r.url()}`,`- Page Title: ${await r.title()}`,"- Page Snapshot:","<WARNING>","The page state was too long and we had to truncate the page state.","</WARNING>"].join(`
4740
+ `),xmlTag:"PageState"}):oe({text:o,xmlTag:"PageState"})}async function kK(t){let r=(await t.screenshot({retries:2})).toString("base64");return DK({imageDataUri:r,xmlTag:"Screenshot"})}async function FK(t,e,r){let n=await te(t),o=await pt(NK.join(t.rootDir,e),r,n);try{let a=new et({baseUrl:Cr(),apiKey:xr(),logger:r}),s=await Vr(r,a,t),c=Go({orgId:xt(),client:a,gitMetadata:s,regenerateCache:!1,alwaysSaveCache:!1,noCache:!1,bustOldestCachePercentage:void 0}),{steps:l,beforeSteps:u,afterSteps:d}=await Rd({cacheStorage:c,logger:r,schemaVersion:o.schemaVersion,stepLists:{steps:o.steps,beforeSteps:o.beforeSteps,afterSteps:o.afterSteps},testId:o.id});o.beforeSteps=u,o.steps=l,o.afterSteps=d}catch(a){r.error({err:a},"Failed to resolve step cache entries for copilot test view")}let i=[];return i.push("### Test"),i.push(`Name: ${o.name}`),o.description&&i.push(`Description: ${o.description}`),i.push(""),o.beforeSteps&&o.beforeSteps.length>0&&(i.push(Fd(o.beforeSteps,"Setup Steps")),i.push("")),i.push(Fd(o.steps,"Main Steps")),o.afterSteps&&o.afterSteps.length>0&&(i.push(""),i.push(Fd(o.afterSteps,"Teardown Steps"))),oe({text:i.join(`
4741
+ `),xmlTag:"TestContent"})}async function wO(t,e){let[r,n]=await Promise.all([$n(t,e),kK(t)]);return we([...r,...n])}async function Py(t,e,r){return we(await FK(t,e,r))}function UK(t,e=2e4){let r={};for(let[n,o]of Object.entries(t)){if(typeof o=="object"&&o!==null){let i=JSON.stringify(o,null,2);if(Pe(i)>e){r[n]="[too large truncated]";continue}r[n]=o;continue}r[n]=o}return r}function BK(t,e){let r={},n=0,o=Object.entries(t).map(([i,a])=>{let s=JSON.stringify(a,null,2),c=Pe(s);return{key:i,value:a,tokens:c}}).sort((i,a)=>i.tokens-a.tokens);for(let{key:i,value:a,tokens:s}of o)n+s<=e&&(r[i]=a,n+=s);return r}function aa(t,e){let r=e?.tokenLimit,n=e?.perItemLimit??2e4,o=t.toObjectCopy(),i=JSON.stringify(o,null,2);if(r===void 0)return oe({text:i,xmlTag:"EnvironmentVariables"});if(Pe(i)<=r)return oe({text:i,xmlTag:"EnvironmentVariables"});let s=UK(o,n),c=JSON.stringify(s,null,2);if(Pe(c)<=r)return oe({text:c,xmlTag:"EnvironmentVariables"});let u=BK(s,r);return oe({text:JSON.stringify(u,null,2),xmlTag:"EnvironmentVariables"})}async function CO(t,e){return we(aa(t,e))}var GK=1,xO=t=>({name:"get_browser_state",tool:zK({description:"Return the current browser state, including URL, title, and serialized accessibility snapshot.",inputSchema:HK.object({}),toModelOutput:r=>r,execute:async()=>{let r=t.controller.browser,n=t.conversationTokenTarget/GK;return wO(r,n)}})});import{tool as HO}from"ai";import t2 from"fs";import _m from"path";import{z as Ve}from"zod";var zy=Symbol.for("immer-nothing"),Dc=Symbol.for("immer-draftable"),Ir=Symbol.for("immer-state");function er(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var la=Object.getPrototypeOf;function ca(t){return!!t&&!!t[Ir]}function si(t){return t?OO(t)||Array.isArray(t)||!!t[Dc]||!!t.constructor?.[Dc]||zc(t)||Hc(t):!1}var jK=Object.prototype.constructor.toString();function OO(t){if(!t||typeof t!="object")return!1;let e=la(t);if(e===null)return!0;let r=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===jK}function kc(t,e){ua(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function ua(t){let e=t[Ir];return e?e.type_:Array.isArray(t)?1:zc(t)?2:Hc(t)?3:0}function Fc(t,e){return ua(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function Iy(t,e){return ua(t)===2?t.get(e):t[e]}function LO(t,e,r){let n=ua(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function VK(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function zc(t){return t instanceof Map}function Hc(t){return t instanceof Set}function sa(t){return t.copy_||t.base_}function Ny(t,e){if(zc(t))return new Map(t);if(Hc(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=OO(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[Ir];let o=Reflect.ownKeys(n);for(let i=0;i<o.length;i++){let a=o[i],s=n[a];s.writable===!1&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(n[a]={configurable:!0,writable:!0,enumerable:s.enumerable,value:t[a]})}return Object.create(la(t),n)}else{let n=la(t);if(n!==null&&r)return{...t};let o=Object.create(n);return Object.assign(o,t)}}function Hy(t,e=!1){return xm(t)||ca(t)||!si(t)||(ua(t)>1&&(t.set=t.add=t.clear=t.delete=$K),Object.freeze(t),e&&Object.entries(t).forEach(([r,n])=>Hy(n,!0))),t}function $K(){er(2)}function xm(t){return Object.isFrozen(t)}var Dy={};function da(t){let e=Dy[t];return e||er(0,t),e}function WK(t,e){Dy[t]||(Dy[t]=e)}var Uc;function NO(){return Uc}function qK(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function _O(t,e){e&&(da("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function ky(t){Fy(t),t.drafts_.forEach(KK),t.drafts_=null}function Fy(t){t===Uc&&(Uc=t.parent_)}function MO(t){return Uc=qK(Uc,t)}function KK(t){let e=t[Ir];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function PO(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[Ir].modified_&&(ky(e),er(4)),si(t)&&(t=wm(e,t),e.parent_||Cm(e,t)),e.patches_&&da("Patches").generateReplacementPatches_(r[Ir].base_,t,e.patches_,e.inversePatches_)):t=wm(e,r,[]),ky(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==zy?t:void 0}function wm(t,e,r){if(xm(e))return e;let n=e[Ir];if(!n)return kc(e,(o,i)=>IO(t,n,e,o,i,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return Cm(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,i=o,a=!1;n.type_===3&&(i=new Set(o),o.clear(),a=!0),kc(i,(s,c)=>IO(t,n,o,s,c,r,a)),Cm(t,o,!1),r&&t.patches_&&da("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function IO(t,e,r,n,o,i,a){if(ca(o)){let s=i&&e&&e.type_!==3&&!Fc(e.assigned_,n)?i.concat(n):void 0,c=wm(t,o,s);if(LO(r,n,c),ca(c))t.canAutoFreeze_=!1;else return}else a&&r.add(o);if(si(o)&&!xm(o)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;wm(t,o),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Cm(t,o)}}function Cm(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&Hy(e,r)}function YK(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:NO(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,i=Gy;r&&(o=[n],i=Bc);let{revoke:a,proxy:s}=Proxy.revocable(o,i);return n.draft_=s,n.revoke_=a,s}var Gy={get(t,e){if(e===Ir)return t;let r=sa(t);if(!Fc(r,e))return XK(t,r,e);let n=r[e];return t.finalized_||!si(n)?n:n===Oy(t.base_,e)?(Ly(t),t.copy_[e]=By(n,t)):n},has(t,e){return e in sa(t)},ownKeys(t){return Reflect.ownKeys(sa(t))},set(t,e,r){let n=DO(sa(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let o=Oy(sa(t),e),i=o?.[Ir];if(i&&i.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(VK(r,o)&&(r!==void 0||Fc(t.base_,e)))return!0;Ly(t),Uy(t)}return t.copy_[e]===r&&(r!==void 0||e in t.copy_)||Number.isNaN(r)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=r,t.assigned_[e]=!0),!0},deleteProperty(t,e){return Oy(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,Ly(t),Uy(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=sa(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){er(11)},getPrototypeOf(t){return la(t.base_)},setPrototypeOf(){er(12)}},Bc={};kc(Gy,(t,e)=>{Bc[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Bc.deleteProperty=function(t,e){return Bc.set.call(this,t,e,void 0)};Bc.set=function(t,e,r){return Gy.set.call(this,t[0],e,r,t[0])};function Oy(t,e){let r=t[Ir];return(r?sa(r):t)[e]}function XK(t,e,r){let n=DO(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function DO(t,e){if(!(e in t))return;let r=la(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=la(r)}}function Uy(t){t.modified_||(t.modified_=!0,t.parent_&&Uy(t.parent_))}function Ly(t){t.copy_||(t.copy_=Ny(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var JK=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,r,n)=>{if(typeof e=="function"&&typeof r!="function"){let i=r;r=e;let a=this;return function(c=i,...l){return a.produce(c,u=>r.call(this,u,...l))}}typeof r!="function"&&er(6),n!==void 0&&typeof n!="function"&&er(7);let o;if(si(e)){let i=MO(this),a=By(e,void 0),s=!0;try{o=r(a),s=!1}finally{s?ky(i):Fy(i)}return _O(i,n),PO(o,i)}else if(!e||typeof e!="object"){if(o=r(e),o===void 0&&(o=e),o===zy&&(o=void 0),this.autoFreeze_&&Hy(o,!0),n){let i=[],a=[];da("Patches").generateReplacementPatches_(e,o,i,a),n(i,a)}return o}else er(1,e)},this.produceWithPatches=(e,r)=>{if(typeof e=="function")return(a,...s)=>this.produceWithPatches(a,c=>e(c,...s));let n,o;return[this.produce(e,r,(a,s)=>{n=a,o=s}),n,o]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy)}createDraft(t){si(t)||er(8),ca(t)&&(t=QK(t));let e=MO(this),r=By(t,void 0);return r[Ir].isManual_=!0,Fy(e),r}finishDraft(t,e){let r=t&&t[Ir];(!r||!r.isManual_)&&er(9);let{scope_:n}=r;return _O(n,e),PO(void 0,n)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}applyPatches(t,e){let r;for(r=e.length-1;r>=0;r--){let o=e[r];if(o.path.length===0&&o.op==="replace"){t=o.value;break}}r>-1&&(e=e.slice(r+1));let n=da("Patches").applyPatches_;return ca(t)?n(t,e):this.produce(t,o=>n(o,e))}};function By(t,e){let r=zc(t)?da("MapSet").proxyMap_(t,e):Hc(t)?da("MapSet").proxySet_(t,e):YK(t,e);return(e?e.scope_:NO()).drafts_.push(r),r}function QK(t){return ca(t)||er(10,t),kO(t)}function kO(t){if(!si(t)||xm(t))return t;let e=t[Ir],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=Ny(t,e.scope_.immer_.useStrictShallowCopy_)}else r=Ny(t,!0);return kc(r,(n,o)=>{LO(r,n,kO(o))}),e&&(e.finalized_=!1),r}function FO(){let e="replace",r="add",n="remove";function o(p,m,g,h){switch(p.type_){case 0:case 2:return a(p,m,g,h);case 1:return i(p,m,g,h);case 3:return s(p,m,g,h)}}function i(p,m,g,h){let{base_:f,assigned_:S}=p,y=p.copy_;y.length<f.length&&([f,y]=[y,f],[g,h]=[h,g]);for(let E=0;E<f.length;E++)if(S[E]&&y[E]!==f[E]){let T=m.concat([E]);g.push({op:e,path:T,value:d(y[E])}),h.push({op:e,path:T,value:d(f[E])})}for(let E=f.length;E<y.length;E++){let T=m.concat([E]);g.push({op:r,path:T,value:d(y[E])})}for(let E=y.length-1;f.length<=E;--E){let T=m.concat([E]);h.push({op:n,path:T})}}function a(p,m,g,h){let{base_:f,copy_:S}=p;kc(p.assigned_,(y,E)=>{let T=Iy(f,y),v=Iy(S,y),w=E?Fc(f,y)?e:r:n;if(T===v&&w===e)return;let C=m.concat(y);g.push(w===n?{op:w,path:C}:{op:w,path:C,value:v}),h.push(w===r?{op:n,path:C}:w===n?{op:r,path:C,value:d(T)}:{op:e,path:C,value:d(T)})})}function s(p,m,g,h){let{base_:f,copy_:S}=p,y=0;f.forEach(E=>{if(!S.has(E)){let T=m.concat([y]);g.push({op:n,path:T,value:E}),h.unshift({op:r,path:T,value:E})}y++}),y=0,S.forEach(E=>{if(!f.has(E)){let T=m.concat([y]);g.push({op:r,path:T,value:E}),h.unshift({op:n,path:T,value:E})}y++})}function c(p,m,g,h){g.push({op:e,path:[],value:m===zy?void 0:m}),h.push({op:e,path:[],value:p})}function l(p,m){return m.forEach(g=>{let{path:h,op:f}=g,S=p;for(let v=0;v<h.length-1;v++){let w=ua(S),C=h[v];typeof C!="string"&&typeof C!="number"&&(C=""+C),(w===0||w===1)&&(C==="__proto__"||C==="constructor")&&er(19),typeof S=="function"&&C==="prototype"&&er(19),S=Iy(S,C),typeof S!="object"&&er(18,h.join("/"))}let y=ua(S),E=u(g.value),T=h[h.length-1];switch(f){case e:switch(y){case 2:return S.set(T,E);case 3:er(16);default:return S[T]=E}case r:switch(y){case 1:return T==="-"?S.push(E):S.splice(T,0,E);case 2:return S.set(T,E);case 3:return S.add(E);default:return S[T]=E}case n:switch(y){case 1:return S.splice(T,1);case 2:return S.delete(T);case 3:return S.delete(g.value);default:return delete S[T]}default:er(17,f)}}),p}function u(p){if(!si(p))return p;if(Array.isArray(p))return p.map(u);if(zc(p))return new Map(Array.from(p.entries()).map(([g,h])=>[g,u(h)]));if(Hc(p))return new Set(Array.from(p).map(u));let m=Object.create(la(p));for(let g in p)m[g]=u(p[g]);return Fc(p,Dc)&&(m[Dc]=p[Dc]),m}function d(p){return ca(p)?u(p):p}WK("Patches",{applyPatches_:l,generatePatches_:o,generateReplacementPatches_:c})}var Or=new JK,kKe=Or.produce,UO=Or.produceWithPatches.bind(Or),FKe=Or.setAutoFreeze.bind(Or),UKe=Or.setUseStrictShallowCopy.bind(Or),BKe=Or.applyPatches.bind(Or),zKe=Or.createDraft.bind(Or),HKe=Or.finishDraft.bind(Or);import{v4 as ZK}from"uuid";FO();function Ds({logger:t,socket:e,baseState:r,recipe:n,description:o}){let[i,a,s]=UO(r,n),c={id:ZK(),patches:a,inversePatches:s,description:o,timestamp:Date.now()};return e?.emit("copilotPatch",c),t.info({description:o},"Emitting copilot patch"),{patch:c,newState:i}}import e2 from"fs";import ks from"path";function BO(t){let e=t.subDir?ks.join(t.project.rootDir,t.subDir):t.project.rootDir,r=`${ze(t.name)}.module.yaml`,n=ks.join(e,r),o=ks.relative(t.project.rootDir,n),i=e2.statSync(n);return{type:Se.MODULE,name:t.name,id:t.moduleId,description:t.description??void 0,relativePath:o,fullFilePath:n,platformSep:ks.sep,fullPathSegments:n.split(ks.sep),relativePathSegments:o.split(ks.sep),fileName:r,lastModified:i.mtime,createdAt:i.birthtime}}import{randomUUID as jy}from"crypto";import{z as zO}from"zod";function Gc(t){let e=t.config.ai?.aiAction??!1,r=e?"The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use. The AI_ACTION_DYNAMIC is an AI action that will dynamically generate up to 15 steps to achieve a goal.":"The step types that can be ingested for a test change. The PRESET_ACTION's action can be seen as a single step command. The MODULE is a module step to use.";return e?zO.discriminatedUnion("type",[Dh,kh,nT]).describe(r):zO.discriminatedUnion("type",[Dh,kh]).describe(r)}async function Fs(t,e,r){switch(t.type){case"PRESET_ACTION":{let n=vu(t.action),o=t.envKey&&Nh.includes(n.type)?t.envKey:void 0;return{type:"PRESET_ACTION",command:n,id:jy(),envKey:o}}case"MODULE":{let{selector:n,inputs:o}=t.module,{entity:i,momenticFiles:a}=await Vn(e,n,"module"),s=await dn(i,a,r);oT(o,s);let l=Object.keys(o??{}).length>0?o??{}:(s.parameters?.length??0)>0?{}:void 0,u={id:jy(),inputs:l};return{...s,...u,type:"RESOLVED_MODULE"}}case"AI_ACTION_DYNAMIC":{if(!(e.config.ai?.aiAction??!1))throw new Error("AI actions are disabled. Enable AI actions in your momentic.config.yaml by setting 'ai.aiAction: true' to use this feature.");return{type:"AI_ACTION_DYNAMIC",text:t.text,id:jy()}}default:return(o=>{throw new Error("You missed a case in the switch above")})(t)}}async function GO({moduleMetadata:t,steps:e,momenticFiles:r,project:n}){let{stepsToSave:o}=await it({stepLists:{steps:e}});_r({content:{...t,steps:o.steps},schemaVersion:_e,momenticFiles:r,project:n})}var jO=t=>({name:"module_create",tool:HO({description:"Create a module. If startIndex is provided, the steps will be extracted from the current test, a module will be created with those steps, and the test will be updated to reference the new module. If no startIndex is provided, an unreferenced module will be created. Automatically splices and repairs the test to reference the new module.",inputSchema:Ve.object({name:Ve.string(),description:Ve.string(),enabled:Ve.boolean().default(!0),parameters:Ve.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:Ve.record(Ve.string(),Ve.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Ve.record(Ve.string(),Ve.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:Ve.record(Ve.string(),Ve.string()).optional().describe("Input parameters to pass to the new module when it's inserted into the test. Keys must match the module's defined parameters. Only relevant if startIndex is provided."),subDir:Ve.string().optional().describe("sub directory to create the module in. If not provided, the module will be created in the project's root directory."),startIndex:Ve.number().optional().describe("Start index of steps to extract from the current test (0-based)."),endIndex:Ve.number().optional().describe("End index of steps to extract from the current test (exclusive). If not provided, extracts just the startIndex.")}),execute:async r=>{let{project:n,logger:o,testPath:i,socket:a,saveChangesToDisk:s}=t,c=r.startIndex??0,l=r.endIndex??c+1,u=await te(n);if(Object.values(u.modules).find(f=>f.name===r.name))return we(oe({text:`Error: A module with the name "${r.name}" already exists. Please use a different name.`,xmlTag:"Error"}));if(r.parameters!==void 0){let f=r.defaultParameters?Object.keys(r.defaultParameters):[],S=r.parameterEnums?Object.keys(r.parameterEnums):[],y=new Set([...f,...S]);for(let E of y)if(!r.parameters.includes(E))return we(oe({text:`Error: Default parameter "${E}" is not defined in parameters array. Available parameters: ${r.parameters.join(", ")}`,xmlTag:"Error"}))}let p=[];if(r.startIndex!==void 0){if(!i)return we(oe({text:"Error: testPath is required when extracting steps from the current test.",xmlTag:"Error"}));let f=await pt(_m.join(n.rootDir,i),o,u);if(c<0||c>=f.steps.length)return we(oe({text:`Error: startIndex ${c} is out of bounds. Test has ${f.steps.length} steps.`,xmlTag:"Error"}));if(l<=c||l>f.steps.length)return we(oe({text:`Error: endIndex ${l} is out of bounds. Must be between ${c+1} and ${f.steps.length}.`,xmlTag:"Error"}));p=f.steps.slice(c,l);for(let S of p)if(S.type==="RESOLVED_MODULE")return we(oe({text:"Error: Modules cannot be nested. Please select steps that do not include module references.",xmlTag:"Error"}))}let m=r.subDir?_m.join(n.rootDir,r.subDir):n.rootDir;r.subDir&&t2.mkdirSync(m,{recursive:!0});let g=await Hd({name:r.name,description:r.description??"",enabled:r.enabled??!0,steps:p,folder:m,project:n}),h=BO({project:n,name:r.name,moduleId:g.moduleId,subDir:r.subDir,description:g.description??void 0});if(u.modules[g.moduleId]=h,r.parameters!==void 0||r.defaultParameters!==void 0||r.parameterEnums!==void 0){let f={moduleId:g.moduleId,name:r.name,description:r.description??g.description,enabled:r.enabled??g.enabled,parameters:r.parameters??[],defaultParameters:r.defaultParameters,parameterEnums:r.parameterEnums};await GO({moduleMetadata:f,steps:p,momenticFiles:u,project:n}),g={...g,name:r.name,description:r.description??g.description,enabled:r.enabled??g.enabled,parameters:r.parameters??[],defaultParameters:r.defaultParameters,parameterEnums:r.parameterEnums}}if(r.startIndex!==void 0){let f=await pt(_m.join(n.rootDir,i),o,u),S={steps:f.steps??[],beforeSteps:f.beforeSteps??[],afterSteps:f.afterSteps??[]},y={type:"MODULE",module:{selector:{id:g.moduleId},inputs:r.moduleInputs??{}}},E;try{E=await Fs(y,n,o)}catch(w){return we(oe({text:`Module "${r.name}" was created successfully, but could not be added to the test. ${String(w)}`,xmlTag:"Error"}))}let T=w=>{w.steps.splice(c,l-c,E)},{newState:v}=Ds({logger:o,socket:a,baseState:S,recipe:T,description:`Create module "${r.name}" from steps ${c}-${l-1}`});if(s){let{stepsToSave:w,moduleUpdates:C}=await it({stepLists:v});C.forEach(_=>{_r({content:_,schemaVersion:_e,momenticFiles:u,project:n})}),Er({relativeTestPath:i,steps:w,schemaVersion:_e,project:n})}}return we(oe({text:JSON.stringify(g,null,2),xmlTag:"ModuleResult"}))}})});function r2(t,e,r,n,o){if(t===void 0&&e!==void 0)throw new ot("Validation Error: startIndex is required when endIndex is provided.");if(t!==void 0&&e===void 0&&r===0)throw new ot("Validation Error: steps are required when startIndex is provided without an endIndex.");if(t!==void 0&&(t>n||t<0))throw new ot(`Validation Error: startIndex is out of bounds for module with ${n} steps.`);if(e!==void 0&&t===void 0)throw new ot("Validation Error: startIndex is required when endIndex is provided.");if(e!==void 0&&t!==void 0&&e<t)throw new ot("Validation Error: endIndex must be greater than or equal to startIndex.");if(e!==void 0&&(e>n||e<0))throw new ot(`Validation Error: endIndex ${e} is out of bounds for module with ${n} steps.`);let i=t??n;if((e??i)===i&&r===0&&!o)throw new ot("Validation Error: Nothing to change. Provide steps, a valid delete range, or metadata updates.")}var VO=t=>{let e=Gc(t.project);return{name:"module_update",tool:HO({description:"Edit a module's steps and/or metadata. Provide startIndex (and optional endIndex) to replace or remove that range; omit endIndex to insert at startIndex; omit both indices to append new steps. Use an empty steps array with both indices to delete the range. Optionally update metadata like parameters. Omit both indices and steps to only update metadata.",inputSchema:Ve.object({selector:Po,steps:e.array(),startIndex:Ve.number().optional(),endIndex:Ve.number().optional(),description:Ve.string().optional().describe("New description for the module."),enabled:Ve.boolean().optional().describe("New enabled state for the module."),parameters:Ve.string().array().optional().describe("New array of parameter names, e.g., ['apiKey', 'userId']. Replaces all existing parameters, resets default parameters and parameter enums if set."),defaultParameters:Ve.record(Ve.string(),Ve.string()).optional().describe("New default values, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:Ve.record(Ve.string(),Ve.string().array()).optional().describe("New enum options, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters.")}),execute:async n=>{let{project:o,logger:i,socket:a,testPath:s,saveChangesToDisk:c}=t,l=await Promise.all(n.steps.map(E=>Fs(E,o,i))),{entity:u,momenticFiles:d}=await Vn(o,n.selector,"module"),p=await dn(u,d,i),m=l.find(E=>!Mh(E));if(m)return we(oe({text:`Error: step type ${m.type} cannot be added to a module.`,xmlTag:"Error"}));let g=n.description!==void 0||n.enabled!==void 0||n.parameters!==void 0||n.defaultParameters!==void 0||n.parameterEnums!==void 0;try{r2(n.startIndex,n.endIndex,n.steps.length,p.steps.length,g)}catch(E){return we(oe({text:String(E),xmlTag:"Error"}))}let h=p.steps;if(n.steps.length>0||n.startIndex!==void 0||n.endIndex!==void 0){h=[...p.steps];let E=n.startIndex!==void 0?n.startIndex:h.length,T=n.endIndex!==void 0?n.endIndex:E;h.splice(E,T-E,...l)}let f={moduleId:p.moduleId,name:p.name,description:n.description??p.description,enabled:n.enabled??p.enabled,parameters:n.parameters??p.parameters,defaultParameters:n.defaultParameters??p.defaultParameters,parameterEnums:n.parameterEnums??p.parameterEnums};n.parameters!==void 0&&(f.defaultParameters=n.defaultParameters??{},f.parameterEnums=n.parameterEnums??{});let S=null;if(s){let E=await pt(_m.join(o.rootDir,s),i,d);S={steps:E.steps??[],beforeSteps:E.beforeSteps??[],afterSteps:E.afterSteps??[]}}c&&await GO({moduleMetadata:f,steps:h,momenticFiles:d,project:o}),s&&S&&Ds({logger:i,socket:a,baseState:S,recipe:T=>{let v=w=>{for(let C of w)C.type==="RESOLVED_MODULE"&&C.moduleId===p.moduleId&&(C.steps=h)};v(T.steps),v(T.beforeSteps),v(T.afterSteps)},description:`Update module "${p.name}"`});let y={...f,stepCount:h.length};return we(oe({text:JSON.stringify(y,null,2),xmlTag:"ModuleResult"}))}})}};import{tool as Pm}from"ai";import{randomUUID as Mm}from"crypto";import{z as li}from"zod";var n2=t=>({name:"preview_preflight",tool:Pm({description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:li.object({description:li.string().describe("Description of the element to preview.")}),toModelOutput:r=>r,execute:async({description:r})=>{let{controller:n,logger:o,testContext:i}=t;try{let a=await n.locateElement({description:r,disableCache:!0,skipWait:!0,logger:o,testContext:i});a.resolution.locator&&await Promise.all([n.browser.scrollIntoViewIfNeeded(a.resolution.locator),n.browser.highlight(a.resolution.locator)]);let s=[...oe({text:`Found element matching description: ${a.target.id}`,xmlTag:"Result"})];return a.target.nodeOnlySerializedHtml&&s.push(...oe({text:`HTML: ${a.target.nodeOnlySerializedHtml}`})),s.push(...await $n(n.browser)),we(s)}catch(a){let s=[...oe({text:`Failed to find any element matching description: ${a}`,xmlTag:"Error"}),...await $n(n.browser)];return we(s)}}})}),o2=t=>({name:"preview_ensure",tool:Pm({description:"Confirm page state.",inputSchema:li.object({assertion:li.string().describe("Assertion to confirm page state.")}),toModelOutput:r=>r,execute:async({assertion:r})=>{let{logger:n,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:c,testContext:l}=t,u={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:r,id:Mm()},id:Mm()},d=await ym({step:u,controller:i,storage:o,codeEvalTools:a,logger:n,socket:s,orgId:c,testContext:l}),p=[];return d?d.status==="SUCCESS"?p.push(...oe({text:`Assertion is true: ${d.message}`,xmlTag:"SuccessfulResult"})):p.push(...oe({text:`Assertion is false: ${d.message}`,xmlTag:"Error"})):p.push(...oe({text:"Assertion executed with unknown result.",xmlTag:"Error"})),p.push(...await $n(i.browser)),we(p)}})}),i2=t=>({name:"preview_step",tool:Pm({description:"Execute a step without adding it to the test.",inputSchema:li.object({command:Oa}),toModelOutput:r=>r,execute:async({command:r})=>{let{logger:n,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:c,testContext:l}=t,u=vu(r),d={type:"PRESET_ACTION",command:u,id:Mm()},p=await ym({step:d,controller:i,storage:o,codeEvalTools:a,logger:n,socket:s,orgId:c,testContext:l}),m=[];return p?p.status==="SUCCESS"?m.push(...oe({text:`Step Execution successful: ${p.message}`,xmlTag:"SuccessfulResult"})):m.push(...oe({text:`Step Execution failed: ${p.message}`,xmlTag:"Error"})):m.push(...oe({text:"Step Execution errored for an unknown reason.",xmlTag:"Error"})),m.push(...await $n(i.browser)),m.push(...aa(l)),we(m)}})}),a2=t=>{let{project:e}=t;return e.config.ai?.aiAction??!1?{name:"preview_ai_action",tool:Pm({description:"Execute an AI action without adding it to the test. This will dynamically generate and run steps to achieve the goal. Note this tool will update and move your test state forward, so if it fails you must rerun the test up to this step before trying again.",inputSchema:li.object({text:li.string().describe("The goal description for the AI action. Supports handlebars templates (ex: {{env.PASSWORD}})"),retries:li.number().optional()}),toModelOutput:o=>o,execute:async({text:o,retries:i})=>{let{logger:a,storage:s,controller:c,codeEvalTools:l,socket:u,orgId:d,testContext:p}=t,m={type:"AI_ACTION_DYNAMIC",text:o,id:Mm(),retries:i},g=await ym({step:m,controller:c,storage:s,codeEvalTools:l,logger:a,socket:u,orgId:d,testContext:p}),h=[];return g?g.status==="SUCCESS"?h.push(...oe({text:`AI action completed successfully: ${g.message??"Goal achieved"}`,xmlTag:"SuccessfulResult"})):h.push(...oe({text:`AI action failed: ${g.message??"Unknown error while previewing AI action"}`,xmlTag:"Error"})):h.push(...oe({text:"AI action executed with unknown result.",xmlTag:"Error"})),h.push(...await $n(c.browser)),h.push(...aa(p)),we(h)}})}:void 0},$O=[n2,o2,i2,a2];import{tool as Wy}from"ai";import JO from"path";import{z as jc}from"zod";import{tool as Vy}from"ai";import WO from"path";import{z as ci}from"zod";var $y=t=>{throw new Error(`Unknown test section: ${t}`)},Im=ci.enum(["setup","teardown","main"]).describe("Test section to modify: 'setup' corresponds to beforeSteps (steps that run before the test), 'teardown' corresponds to afterSteps (steps that run after the test), 'main' is synonymous with steps (the main test steps)");function qO(t,e){switch(e){case"setup":return t.beforeSteps;case"teardown":return t.afterSteps;case"main":return t.steps;default:return $y(e)}}var KO=t=>{let e=Gc(t.project);return{name:"test_insert_step",tool:Vy({description:"Insert a step or module into the test.",inputSchema:ci.object({index:ci.number(),step:e,targetSection:Im.default("main")}),execute:async n=>{let{project:o,logger:i,testPath:a,socket:s,saveChangesToDisk:c}=t,l=await te(o),u=await pt(WO.join(o.rootDir,a),i,l),d={steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]},p=qO(d,n.targetSection);if(n.index<0||n.index>p.length)return we(oe({text:`Error: Invalid index ${n.index} for inserting into ${n.targetSection} section with ${p.length} steps (must be 0-${p.length})`,xmlTag:"Error"}));let m=await Fs(n.step,o,i),g=f=>{switch(n.targetSection){case"setup":f.beforeSteps.splice(n.index,0,m);break;case"teardown":f.afterSteps.splice(n.index,0,m);break;case"main":f.steps.splice(n.index,0,m);break;default:$y(n.targetSection)}},{newState:h}=Ds({logger:i,socket:s,baseState:d,recipe:g,description:`Insert ${m.type} step at index ${n.index} in ${n.targetSection}`});if(c){let{stepsToSave:f,moduleUpdates:S}=await it({stepLists:h});S.forEach(y=>{_r({content:y,schemaVersion:_e,momenticFiles:l,project:o})}),Er({relativeTestPath:a,steps:f,schemaVersion:_e,project:o})}return we(oe({text:`Successfully inserted step at index ${n.index} in the ${n.targetSection} section.`,xmlTag:"Result"}))}})}},YO=t=>{let e=Gc(t.project);return{name:"test_splice_steps",tool:Vy({description:"Splice steps in the test. This is the primary tool for replacing, removing, or bulk inserting steps. Never use this as a means to bypass a failure. Examples: Replace step at index 5: splice(startIndex=5, deleteCount=1, steps=[newStep]). Delete step at index 5: splice(startIndex=5, deleteCount=1, steps=[]). Insert multiple steps at index 5: splice(startIndex=5, deleteCount=0, steps=[step1, step2]).",inputSchema:ci.object({startIndex:ci.number(),deleteCount:ci.number().describe("Number of steps to remove. Use 0 to insert without deleting, 1 to replace a single step, or N to delete N steps."),steps:e.array(),targetSection:Im.default("main"),returnTest:ci.boolean().default(!1).describe("Whether or not you want to see the full test after the splice is complete")}),execute:async n=>{let{project:o,logger:i,testPath:a,socket:s,saveChangesToDisk:c}=t,l=await te(o),u=await pt(WO.join(o.rootDir,a),i,l),d={steps:u.steps??[],beforeSteps:u.beforeSteps??[],afterSteps:u.afterSteps??[]},p=qO(d,n.targetSection);if(n.startIndex<0||n.startIndex>p.length)return we(oe({text:`Error: Invalid startIndex ${n.startIndex} for splicing ${n.targetSection} section with ${p.length} steps (must be 0-${p.length})`,xmlTag:"Error"}));let m=await Promise.all(n.steps.map(E=>Fs(E,o,i))),g=E=>{switch(n.targetSection){case"setup":E.beforeSteps.splice(n.startIndex,n.deleteCount,...m);break;case"teardown":E.afterSteps.splice(n.startIndex,n.deleteCount,...m);break;case"main":E.steps.splice(n.startIndex,n.deleteCount,...m);break;default:$y(n.targetSection)}},h=n.steps.length,f=n.deleteCount,{newState:S}=Ds({logger:i,socket:s,baseState:d,recipe:g,description:`Splice ${h} step(s) at index ${n.startIndex} in ${n.targetSection}, removing ${f}`});if(c){let{stepsToSave:E,moduleUpdates:T}=await it({stepLists:S});T.forEach(v=>{_r({content:v,schemaVersion:_e,momenticFiles:l,project:o})}),Er({relativeTestPath:a,steps:E,schemaVersion:_e,project:o})}let y=[...oe({text:`Successfully spliced ${h} step(s) at index ${n.startIndex} in the ${n.targetSection} section, removing ${f} step(s).`,xmlTag:"Result"})];return n.returnTest&&y.push(...oe({text:JSON.stringify(await Py(o,a,i),null,2),xmlTag:"TestContent"})),we(y)}})}},XO=t=>({name:"test_get",tool:Vy({description:"Retrieve the full test contents, including simplified cache data on some steps enabling you to inspect resolved locators and debug targeting issues. For context, the caches are just simplified targeting information",inputSchema:ci.object({}),execute:async()=>Py(t.project,t.testPath,t.logger)})});var QO=3,ZO=t=>({name:"get_environment_variables",tool:Wy({description:"Get the current environment variables.",inputSchema:jc.object({}),toModelOutput:r=>r,execute:async()=>{let r=t.conversationTokenTarget/QO;return CO(t.testContext,{tokenLimit:r})}})}),eL=t=>({name:"reset_session",tool:Wy({description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:jc.object({}),toModelOutput:r=>r,execute:async()=>{let{project:r,logger:n,testPath:o,orgId:i,codeEvalTools:a}=t,s=await te(r),c=await pt(JO.join(r.rootDir,o),n,s),l=c.baseUrl,u,d={};if(!l&&c.envs){let m=c.envs.find(g=>g.default);if(m)try{let g=Gi(m.name,r,n);u=g.name,d=g.variables;let h=g.variables[Rt];typeof h=="string"&&(l=h)}catch(g){n.warn({err:g,envName:m.name},"Failed to resolve environment for reset")}}l||(l="about:blank"),d=await hm({orgId:i,testName:c.name,envName:u,baseEnvVariables:d,parameters:c.parameters,logger:n,localTools:a}),await t.controller.browser.reset({newUrl:l}),t.testContext.reset({baseUrl:l,testName:c.name,currentUrl:t.controller.browser.url(),variablesFromEnvironment:d,envName:u});let p=[...oe({text:`Session reset to ${l}.`,xmlTag:"Result"}),...await $n(t.controller.browser),...aa(t.testContext)];return we(p)}})}),tL=t=>({name:"run_step",tool:Wy({description:"Run the step in the test at the given startIndex. If there is no endIndex, the step at the startIndex will be executed. EndIndex is the last step that is run (end index is inclusive).",inputSchema:jc.object({fromIndex:jc.number(),toIndex:jc.number().optional(),targetSection:Im.default("main")}),toModelOutput:r=>r,execute:async({fromIndex:r,toIndex:n,targetSection:o})=>{let{project:i,logger:a,testPath:s,storage:c,controller:l,codeEvalTools:u,socket:d,orgId:p,testContext:m,conversationTokenTarget:g}=t,h=r,f=n??h,S=await te(i),y=await pt(JO.join(i.rootDir,s),a,S),E;switch(o){case"setup":E=y.beforeSteps??[];break;case"teardown":E=y.afterSteps??[];break;case"main":E=y.steps;break;default:return(W=>{throw new Error(`Unknown test section: ${W}`)})(o)}if(h<0||h>=E.length)return we(oe({text:`Error: startIndex is out of bounds for ${o} section with ${E.length} steps.`,xmlTag:"Error"}));if(f<h)return we(oe({text:"Error: toIndex must be greater than or equal to fromIndex.",xmlTag:"Error"}));if(f>=E.length)return we(oe({text:`Error: toIndex is out of bounds for ${o} section with ${E.length} steps.`,xmlTag:"Error"}));let T=E.slice(h,f+1);if(T.length===0)return we(oe({text:"Error: No steps were executed.",xmlTag:"Error"}));l.setOpen();let{results:v}=await _y({steps:T,controller:l,storage:c,codeEvalTools:u,logger:a,socket:d,orgId:p,testContext:m});if(!v||v.length===0)return we(oe({text:"Error: No steps were executed.",xmlTag:"Error"}));let w=v.at(-1);if(!w)return we(oe({text:"Error: No steps were executed.",xmlTag:"Error"}));if(w.status!=="SUCCESS"){let B=h+v.length-1;return we(oe({text:`Error: Step at index ${B} failed: ${w.message}`,xmlTag:"Error"}))}let C=o==="main"?"":` in ${o}`,_=h===f?`Step at index ${f}${C}`:`Steps ${h}-${f}${C}`,N=[];if(w.status==="SUCCESS"){let B=`${_} executed successfully. Last step result: ${w.message}`;N.push(...oe({text:B,xmlTag:"Result"})),w.data&&N.push(...oe({text:`Data: ${JSON.stringify(w.data,null,2)}`,xmlTag:"ResultData"}))}let U=g/QO,[j,O]=await Promise.all([$n(l.browser,U),aa(m,{tokenLimit:U})]);return we([...N,...j,...O])}})});var rL=[xO,ZO,tL,XO,eL,KO,YO,jO,VO,...$O];var u2=1e5,nL=8e4,qy=2,oL="[trimmed: omitted due to context budget]",Ky=50,d2=1600;function p2(t,e){return typeof t=="object"&&t!==null&&t.type===e}function m2(t,e,r){let n=0,o=[];for(let i of t){let a=i.content;if(!Array.isArray(a)){o.push(i);continue}let s=[];for(let c of a){if(n>=e){s.push(c);continue}if(!p2(c,r)){s.push(c);continue}if(r==="image"){n>=e?s.push(c):n+=d2;continue}let l=r==="tool-result"?"output":"input",u=r==="tool-result"?c.output:c.input;if(u===void 0||u===oL){s.push(c);continue}let d=Pe(u);n+=d,s.push({...c,[l]:oL})}s.length!==0&&o.push({...i,content:s})}return{messages:o,trimmedTokens:n}}function h2(t){let e=t[0];return e?"parts"in e&&Array.isArray(e.parts):!1}function g2(t){return l2({messages:t,reasoning:"before-last-message",toolCalls:[{type:"before-last-10-messages",tools:["momentic_module_get","momentic_module_recommend","get_environment_variables"]},{type:"before-last-5-messages",tools:["run_step","preview_ai_action"]},{type:"before-last-3-messages",tools:["test_get","reset_session","test_insert_step","test_splice_steps","preview_ensure","momentic_module_create"]},{type:"before-last-2-messages",tools:["observe_page","momentic_module_list","momentic_module_change"]},{type:"before-last-1-messages",tools:["preview_preflight","preview_step"]}],emptyMessages:"remove"})}var f2=["tool-result","image","tool-call"],S2=.3;function Vc(t,e,r){let n=[...t];for(let o of f2){let i=Pe(n);if(i<=e)break;let a=i-e,s=m2(n,a,o);n=s.messages,s.trimmedTokens>0&&r.debug({contentType:o,trimmedTokens:s.trimmedTokens,newTokenCount:Pe(n)},"Trimmed content")}return n}function y2(t,e,r){let n=Pe(t);if(n<=e||t.length<=1)return t;let o=t[0],i=[],a=[];if(t.length>qy+1?(i=t.slice(1,t.length-qy),a=t.slice(t.length-qy)):a=t.slice(1),i.length>0){i=Vc(i,e,r);let u=[o,...i,...a];if(n=Pe(u),n<=e)return u}let s=Pe(i),c=s/e;if(c<S2){if(a.length>1){let u=a[a.length-1],d=[...i,...a.slice(0,-1)],p=Vc(d,e,r),m=[o,...p,u];if(n=Pe(m),n<=e)return m;let g=Vc([...p,u],e,r),h=[o,...g];if(n=Pe(h),n<=e)return h}else if(a.length===1){let u=[...i,...a],d=Vc(u,e,r),p=[o,...d];if(n=Pe(p),n<=e)return p}}else for(r.debug({headBudgetRatio:c,middleMsgTokens:s,targetTokens:e},"Middle exceeds 30% budget, removing messages");i.length>0;){i.shift();let u=[o,...i,...a];if(n=Pe(u),n<=e)return u}a=Vc(a,e,r);let l=[o,...i,...a];if(n=Pe(l),n<=e)return l;for(;a.length>0;)if(a.shift(),l=[o,...i,...a],n=Pe(l),n<=e)return l;return n>e&&r.warn({targetTokens:e,finalTokenCount:n,remainingMessages:l.length},"Unable to meet token target after all pruning phases"),l}function E2(t,e,r,n){let o=g2(t),i=Pe(o);return i>e&&(n.debug({projected:i,threshold:e,target:r},"Context exceeds threshold, pruning messages"),o=y2(o,r,n)),o}function Om(t){let{testPath:e,messages:r,logger:n,session:o,sessionId:i,hooks:a={},saveChangesToDisk:s=!1}=t,{onStepFinish:c,onPrepareStep:l,onChunk:u,onError:d,onFinish:p}=a,m=xr(),g=xt(),h=Cr(),f=me(),S=new et({apiKey:m,baseUrl:h,logger:n}),y=new ai(S,g),E=new On({httpClient:new zt({baseUrl:S.baseUrl,apiKey:S.apiKey,logger:n,mode:"interactive"}),fakerSeed:f.config.advanced?.fakerConstantSeed?qa:void 0}),T={project:f,apiKey:m,orgId:g,baseUrl:h,sessionId:i,logger:n,storage:y,codeEvalTools:E,saveChangesToDisk:s,testPath:e,testContext:o.context,controller:o.controller,socket:o.socket,conversationTokenTarget:nL},v=Tm.reduce((O,{name:B,builder:W})=>(O[B]=W(T),O),{}),w={};for(let O of rL){let B=O(T);B&&(w[B.name]=B.tool)}let C={...v,...w},_=Sm(i),N=async O=>{let{messages:B}=O;l&&await l(B);let W=E2(B,u2,nL,n),q=Pe(B);return q>rR&&n.debug({originalCount:B.length,prunedCount:W.length,originalTokens:q,prunedTokens:Pe(W)},"Prepared messages for copilot step"),{...O,messages:W}},U={model:_("claude-sonnet-4-5-20250929"),stopWhen:c2(Ky),maxRetries:4,system:RO(f),tools:C,prepareStep:N,onStepFinish:c,onChunk:u,onError:d,onFinish:async({finishReason:O,usage:B,text:W,response:q})=>{n.info({finishReason:O,usage:B,sessionId:i},"Full copilot turn finished"),p&&await p({finishReason:O,usage:B,text:W,response:q})}},j=h2(r)?s2(r,{tools:U.tools}):r;return{...U,messages:j}}var WYe=new Error("timeout while waiting for mutex to become available"),qYe=new Error("mutex already locked"),b2=new Error("request for lock canceled"),T2=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},Yy=class{constructor(e,r=b2){this._value=e,this._cancelError=r,this._queue=[],this._weightedWaiters=[]}acquire(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,o)=>{let i={resolve:n,reject:o,weight:e,priority:r},a=iL(this._queue,s=>r<=s.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return T2(this,arguments,void 0,function*(r,n=1,o=0){let[i,a]=yield this.acquire(n,o);try{return yield r(i)}finally{a()}})}waitForUnlock(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,r)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),v2(this._weightedWaiters[e-1],{resolve:n,priority:r})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let r=this._value;this._value-=e.weight,e.resolve([r,this._newReleaser(e.weight)])}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let r=this._weightedWaiters[e-1];r&&(r.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let r=this._value;r>0;r--){let n=this._weightedWaiters[r-1];if(!n)continue;let o=n.findIndex(i=>i.priority<=e);(o===-1?n:n.splice(0,o)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,r){return(this._queue.length===0||this._queue[0].priority<r)&&e<=this._value}};function v2(t,e){let r=iL(t,n=>e.priority<=n.priority);t.splice(r+1,0,e)}function iL(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1}var R2=function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(t,e||[])).next())})},Lm=class{constructor(e){this._semaphore=new Yy(1,e)}acquire(){return R2(this,arguments,void 0,function*(e=0){let[,r]=yield this._semaphore.acquire(1,e);return r})}runExclusive(e,r=0){return this._semaphore.runExclusive(()=>e(),1,r)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};var Xy=class{mutexes=new Map;activeControllers=new Map;async startOrReplace(e,r){r.throwIfAborted(),this.mutexes.has(e)||this.mutexes.set(e,new Lm);let o=await this.mutexes.get(e).acquire();try{let i=this.activeControllers.get(e);i&&!i.signal.aborted&&i.abort(new Error("Superseded by newer momentic_test_edit invocation. Stop executing edit_test requests to this test and ask the user what to do next."));let a=new AbortController;return this.activeControllers.set(e,a),{signal:AbortSignal.any([r,a.signal]),release:()=>{this.activeControllers.get(e)===a&&this.activeControllers.delete(e),this.activeControllers.has(e)||this.mutexes.delete(e)}}}finally{o()}}},aL=new Xy;import Us from"dedent";function A2(){let t=Object.entries(vh).map(([e,r])=>`- **${e}**: ${r}`).join(`
4742
4742
  `);return Us`
4743
4743
  ### Available Step Types
4744
4744
 
@@ -4810,11 +4810,11 @@ ${n}`}import{tool as zK}from"ai";import{z as HK}from"zod";import NK from"path";f
4810
4810
  ${x2}
4811
4811
  `}function lL(t){return t?._meta?.progressToken!==void 0}function O2(t,e,r,n){let o=new AbortController,i=[],a=[],s=lL(t),c=s?t:void 0,l=d=>{c&&Jy(c,r,d,e,o,n)};return{hooks:{onStepFinish:s?()=>{r.completed+=1,l()}:void 0,onPrepareStep:s?d=>{let p=d[d.length-1];if(p?.role==="tool"){let m=p.content.map(g=>g.toolName).join(", ");l(`Tool ${m} finished, thinking...`)}}:void 0,onChunk:({chunk:d})=>{d.type==="text-delta"?(i.push(d.text),a.push(d.text),l(i.join(""))):d.type==="tool-call"&&(a.push(`
4812
4812
  Running tool ${d.toolName} with input ${JSON.stringify(d.input)}
4813
- `),l(`Running tool ${d.toolName}...`))},onError:({error:d})=>{e.error({error:d},"Error during copilot stream"),n.addError(`Stream error: ${String(d)}`)}},notificationAbortController:o,getAccumulatedText:()=>a.join("")}}async function Jy(t,e,r,n,o,i){try{await t.sendNotification({method:"notifications/progress",params:{progressToken:t._meta.progressToken,progress:e.completed,total:e.total,...r?{message:r}:{}}})}catch(a){n.error({err:a},"Failed to send progress notification"),o.abort(a),i.addError(`Failed to send progress notification: ${String(a)}`)}}var L2=yn({schema:{name:"momentic_test_create",description:"Create a test. You must provide a name and either a baseUrl or environment or the tool will fail.",inputSchema:Rg},handle:async(t,e,r,n)=>{let{project:o}=t;try{let i=await Rm({project:o,input:e});r.addResult(JSON.stringify(i,null,2))}catch(i){r.addError(String(i));return}}}),N2=yn({schema:{name:"momentic_test_list",description:"List tests.",inputSchema:{}},handle:async(t,e,r,n)=>{let{project:o}=t,i=await ee(o),s=Object.values(i.tests).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type,labels:c.labels||[]}));r.addResult(JSON.stringify({tests:s},null,2))}}),D2=yn({schema:{name:"momentic_test_get",description:"Get a single fully loaded test by id, exact name, or file path. Exactly one selector must be provided.",inputSchema:{selector:Po}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t;try{let a=await Vn(o,e.selector,"test"),s=await pt(a.entity.fullFilePath,i,a.momenticFiles);r.addResult(JSON.stringify({test:s},null,2))}catch(a){r.addError(String(a));return}}}),k2=4e5,F2=2e5;async function U2(t,e,r){let n=Pe(t);if(n<=k2)return e.getMcpCopilotConversationEvaluation({messagesAndToolCalls:t},{logger:r});let o=Math.ceil(n/F2),i=Math.ceil(t.length/o),a=[];for(let l=0;l<o;l++){let u=l*i,d=Math.min(u+i,t.length);a.push(t.slice(u,d))}let s=await Promise.all(a.map(async(l,u)=>{try{let d=await e.getMcpCopilotChatSummary({messagesAndToolCalls:l},{logger:r}),p={summary:d.summary.trim(),errorsRanInto:d.errorsRanInto,untestedSteps:d.untestedSteps};return JSON.stringify(p,null,2).trim()}catch(d){r.warn({err:d,windowIndex:u},"Copilot chat summary failed for window. Warned the user via error message. Return explanation to tool.")}return"Chat compression failed for an entire window, warn the user they must rerun the test to know its true status."})),c=["The conversation was too large. Here are the summaries from subsections, please use them to process the full conversation into an evaluable form:",...s.map((l,u)=>`--- Summary ${u+1} of ${s.length} ---
4814
- ${l}`)];return e.getMcpCopilotConversationEvaluation({messagesAndToolCalls:c},{logger:r})}async function B2(t,e,r){let n=xr(),o=xt(),i=Cr(),a=new ia,s=new et({apiKey:n,baseUrl:i,logger:t}),c=new ai(s,o),l=(await pt(r.fullFilePath,t,await ee(e))).advanced?.viewport??Kt,u=new no(e.config.ai?.agentConfig,{baseUrl:i,apiKey:n,logger:t,mode:"interactive"}),d=new Ho({baseUrl:i,apiKey:n,logger:t,mode:"interactive"},u),p=await qr.init({baseUrl:"about:blank",userBrowserSettings:{},enricher:d,storage:c,logger:t,contextArgs:{viewport:l,locale:Io,timezoneId:Oo,geolocation:Lo},iconKnowledgeBase:null,callbacks:{}}),m=new oi({browser:p,generator:u,logger:t,orgId:o,options:{scratchPadId:void 0,slowMoMs:void 0,autoFollowNewTabs:!0,useMemory:e.config.ai?.useMemory,aiPageFiltering:!0},storage:c,localCodeEvalTools:new On({httpClient:new zt({baseUrl:i,apiKey:n,logger:t,mode:"interactive"}),fakerSeed:e.config.advanced?.fakerConstantSeed?qa:void 0}),visualDiffScreenshotStorage:a}),g=new lr({baseUrl:"about:blank",testName:P2.basename(r.relativePath),currentUrl:p.url(),variablesFromEnvironment:{},envName:void 0});return{controller:m,context:g,socket:void 0}}var z2=yn({schema:{name:"momentic_test_edit",description:sL(),inputSchema:{selector:Po,message:I2.string().describe("A single block of natural-language instructions describing the desired edits to the test. The test can also be edited to add modules, edit modules, or create new modules inside of the test. Can only be used to modify steps (including module steps) inside of the passed in test.")}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t,a=n?.signal;if(!a){r.addError("No response handler available: client abort signal is required for momentic_test_edit");return}let s=xr(),c=Cr(),l=new no(o.config.ai?.agentConfig,{baseUrl:c,apiKey:s,logger:i,mode:"interactive"}),u={completed:0,total:Ky},{hooks:d,notificationAbortController:p,getAccumulatedText:m}=O2(n,i,u,r),g=lL(n);g&&await Jy(n,u,"Validating if your edits requests are valid...",i,p,r);let h=await l.getLintMcpCopilotMessageResult({message:e.message},{logger:i});if(h.category!=="NONE"){r.addError(`${h.thoughts}
4813
+ `),l(`Running tool ${d.toolName}...`))},onError:({error:d})=>{e.error({error:d},"Error during copilot stream"),n.addError(`Stream error: ${String(d)}`)}},notificationAbortController:o,getAccumulatedText:()=>a.join("")}}async function Jy(t,e,r,n,o,i){try{await t.sendNotification({method:"notifications/progress",params:{progressToken:t._meta.progressToken,progress:e.completed,total:e.total,...r?{message:r}:{}}})}catch(a){n.error({err:a},"Failed to send progress notification"),o.abort(a),i.addError(`Failed to send progress notification: ${String(a)}`)}}var L2=yn({schema:{name:"momentic_test_create",description:"Create a test. You must provide a name and either a baseUrl or environment or the tool will fail.",inputSchema:Rg},handle:async(t,e,r,n)=>{let{project:o}=t;try{let i=await Rm({project:o,input:e});r.addResult(JSON.stringify(i,null,2))}catch(i){r.addError(String(i));return}}}),N2=yn({schema:{name:"momentic_test_list",description:"List tests.",inputSchema:{}},handle:async(t,e,r,n)=>{let{project:o}=t,i=await te(o),s=Object.values(i.tests).map(c=>({id:c.id,name:c.name,description:c.description,relativePath:c.relativePath,fullFilePath:c.fullFilePath,platformSep:c.platformSep,fullPathSegments:c.fullPathSegments,relativePathSegments:c.relativePathSegments,fileName:c.fileName,lastModified:c.lastModified,createdAt:c.createdAt,type:c.type,labels:c.labels||[]}));r.addResult(JSON.stringify({tests:s},null,2))}}),D2=yn({schema:{name:"momentic_test_get",description:"Get a single fully loaded test by id, exact name, or file path. Exactly one selector must be provided.",inputSchema:{selector:Po}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t;try{let a=await Vn(o,e.selector,"test"),s=await pt(a.entity.fullFilePath,i,a.momenticFiles);r.addResult(JSON.stringify({test:s},null,2))}catch(a){r.addError(String(a));return}}}),k2=4e5,F2=2e5;async function U2(t,e,r){let n=Pe(t);if(n<=k2)return e.getMcpCopilotConversationEvaluation({messagesAndToolCalls:t},{logger:r});let o=Math.ceil(n/F2),i=Math.ceil(t.length/o),a=[];for(let l=0;l<o;l++){let u=l*i,d=Math.min(u+i,t.length);a.push(t.slice(u,d))}let s=await Promise.all(a.map(async(l,u)=>{try{let d=await e.getMcpCopilotChatSummary({messagesAndToolCalls:l},{logger:r}),p={summary:d.summary.trim(),errorsRanInto:d.errorsRanInto,untestedSteps:d.untestedSteps};return JSON.stringify(p,null,2).trim()}catch(d){r.warn({err:d,windowIndex:u},"Copilot chat summary failed for window. Warned the user via error message. Return explanation to tool.")}return"Chat compression failed for an entire window, warn the user they must rerun the test to know its true status."})),c=["The conversation was too large. Here are the summaries from subsections, please use them to process the full conversation into an evaluable form:",...s.map((l,u)=>`--- Summary ${u+1} of ${s.length} ---
4814
+ ${l}`)];return e.getMcpCopilotConversationEvaluation({messagesAndToolCalls:c},{logger:r})}async function B2(t,e,r){let n=xr(),o=xt(),i=Cr(),a=new ia,s=new et({apiKey:n,baseUrl:i,logger:t}),c=new ai(s,o),l=(await pt(r.fullFilePath,t,await te(e))).advanced?.viewport??Kt,u=new no(e.config.ai?.agentConfig,{baseUrl:i,apiKey:n,logger:t,mode:"interactive"}),d=new Ho({baseUrl:i,apiKey:n,logger:t,mode:"interactive"},u),p=await qr.init({baseUrl:"about:blank",userBrowserSettings:{},enricher:d,storage:c,logger:t,contextArgs:{viewport:l,locale:Io,timezoneId:Oo,geolocation:Lo},iconKnowledgeBase:null,callbacks:{}}),m=new oi({browser:p,generator:u,logger:t,orgId:o,options:{scratchPadId:void 0,slowMoMs:void 0,autoFollowNewTabs:!0,useMemory:e.config.ai?.useMemory,aiPageFiltering:!0},storage:c,localCodeEvalTools:new On({httpClient:new zt({baseUrl:i,apiKey:n,logger:t,mode:"interactive"}),fakerSeed:e.config.advanced?.fakerConstantSeed?qa:void 0}),visualDiffScreenshotStorage:a}),g=new lr({baseUrl:"about:blank",testName:P2.basename(r.relativePath),currentUrl:p.url(),variablesFromEnvironment:{},envName:void 0});return{controller:m,context:g,socket:void 0}}var z2=yn({schema:{name:"momentic_test_edit",description:sL(),inputSchema:{selector:Po,message:I2.string().describe("A single block of natural-language instructions describing the desired edits to the test. The test can also be edited to add modules, edit modules, or create new modules inside of the test. Can only be used to modify steps (including module steps) inside of the passed in test.")}},handle:async(t,e,r,n)=>{let{project:o,logger:i}=t,a=n?.signal;if(!a){r.addError("No response handler available: client abort signal is required for momentic_test_edit");return}let s=xr(),c=Cr(),l=new no(o.config.ai?.agentConfig,{baseUrl:c,apiKey:s,logger:i,mode:"interactive"}),u={completed:0,total:Ky},{hooks:d,notificationAbortController:p,getAccumulatedText:m}=O2(n,i,u,r),g=lL(n);g&&await Jy(n,u,"Validating if your edits requests are valid...",i,p,r);let h=await l.getLintMcpCopilotMessageResult({message:e.message},{logger:i});if(h.category!=="NONE"){r.addError(`${h.thoughts}
4815
4815
 
4816
4816
  Category: ${h.category}`);return}let f,S;try{({entity:f,momenticFiles:S}=await Vn(o,e.selector,"test"))}catch(O){r.addError(String(O));return}let y=await pt(f.fullFilePath,i,S),E=i.child({applicationName:"momentic-mcp-copilot",testId:f.id}),T=Om({testPath:f.relativePath,messages:[{role:"user",content:e.message}],logger:E,session:await B2(E,o,f),sessionId:n?.sessionId,hooks:d,saveChangesToDisk:!0}),{signal:v,release:w}=await aL.startOrReplace(f.id,a),C=M2(T);try{await C.text}catch(O){if(v.aborted)i.debug("AI stream was cancelled, returning partial output"),r.addResult(JSON.stringify({aborted:String(O),partialOutput:m()},null,2));else throw O}finally{w()}let _=await pt(f.fullFilePath,i,S),N=await Mw(y,_),U=m().split(`
4817
- `).map(O=>O.trim()).filter(O=>O.length>0);g&&await Jy(n,{completed:u.total,total:u.total},"Evaluating edits and generating edit status...",i,p,r);let j=await U2(U,l,i);r.addResult(JSON.stringify({additions:N.additions,deletions:N.deletions,summarization:j},null,2))}}),cL=[N2,L2,D2,z2];var uL=[...bO,...cL,...Tm];function Qy(t,e){let r=new H2({name:e.applicationName,version:e.cliVersion},{capabilities:{logging:{},tools:{}}});for(let n of uL)n.addToolToMcpServer(t,r);return r}async function dL(t,e,r,n){let o=new G2(r,e,n);return await t.connect(o),{close:async()=>{try{await t.close()}catch{}},transport:o}}var Zy="mcp-session-id",q2="sessionId",Bs=W2(),$c=new Map;function pL(){let t={applicationName:"momentic-mcp-desktop-server",cliVersion:Ic??"0.0.0"},e=me(),r=nt.child({orgId:xt(),userId:jo(),...t});return{context:{project:e,logger:r,saveChangesToDisk:!0},info:t}}Bs.get("/sse",async(t,e)=>{let{context:r,info:n}=pL(),o=Qy(r,n),{transport:i}=await dL(o,e,"/api/mcp/sse",{enableDnsRebindingProtection:!1}),a=i.sessionId,s={transport:i,close:async()=>{$c.delete(a);try{await o.close()}catch(c){r.logger.warn({err:c},"Failed to close MCP server on SSE session cleanup")}}};$c.set(a,s),i.onclose=()=>{let c=$c.get(a);c&&c.close()}});Bs.post("/sse",async(t,e)=>{let r=String(t.query[q2]??"");if(!r||!$c.has(r)){e.status(400).send("Invalid or missing sessionId");return}await $c.get(r).transport.handlePostMessage(t,e,t.body)});var mL=Bs,So={};Bs.post("/",async(t,e)=>{let r=String(t.headers[Zy]??"");try{if(r&&So[r]){await So[r].handleRequest(t,e,t.body);return}if(!r&&V2(t.body)){let{context:n,info:o}=pL(),i=Qy(n,o),a=new j2({sessionIdGenerator:()=>$2(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{So[s]=a}});a.onclose=()=>{let s=a.sessionId;s&&So[s]&&delete So[s],i.close().catch(()=>{})},await i.connect(a),await a.handleRequest(t,e,t.body);return}e.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null})}catch{e.headersSent||e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}});Bs.get("/",async(t,e)=>{let r=String(t.headers[Zy]??"");if(!r||!So[r]){e.status(400).send("Invalid or missing session ID");return}await So[r].handleRequest(t,e)});Bs.delete("/",async(t,e)=>{let r=String(t.headers[Zy]??"");if(!r||!So[r]){e.status(400).send("Invalid or missing session ID");return}let n=So[r];try{await n.handleRequest(t,e)}catch{e.headersSent||e.status(500).send("Error processing session termination")}});import{Router as K2}from"express";var Nm=K2();Nm.get("/",Oe(async(t,e)=>{let r=(await Af()).map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(r)}));Nm.get("/current",Oe((t,e)=>{let r=me();if(!r){e.status(404).json({error:"No project found."});return}let n={name:r.config.name,configFilePath:r.configFilePath};e.status(200).json(n)}));Nm.post("/set",Oe(async(t,e)=>{let r;try{r=Xv.parse(t.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}nt.info("Setting local project");try{let n=await _t({configFilePath:r.configFilePath});zd(n,o=>_t({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var hL=Nm;import{Router as Y2}from"express";var gL=Y2();gL.get("/",Oe((t,e)=>{let r=me(),n={ai:r.config.ai,browser:r.config.browser,displayRoot:r.config.displayRoot};e.status(200).json(n)}));var fL=gL;import{streamText as X2}from"ai";import{Router as J2}from"express";import Dm from"fs";import zs from"path";import{v4 as Q2}from"uuid";import Z2 from"yaml";var Wc=new dp({platform:"local_app"},{flushAt:1,flushInterval:0});var yo=J2();yo.post("/",Oe(async(t,e)=>{let r;try{r=Vv.parse(t.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=me(),o=await Rm({project:n,input:r});Wc.track({type:"test_editor:test_create"}),e.status(201).json(o)}catch(n){if(n instanceof ot){e.status(400).json({error:n.message});return}throw n}}));yo.get("/:testPath",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n=me(),o=await ee(n),i;try{i=await pt(zs.join(n.rootDir,r),nt,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:s}=await it({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});s.forEach(c=>{_r({content:c,schemaVersion:_e,momenticFiles:o,project:n})}),Er({relativeTestPath:r,steps:a,schemaVersion:_e,project:n})}catch(a){nt.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));yo.get("/:testPath/metadata",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n=me(),o=zs.join(n.rootDir,r);if(!Dm.existsSync(o)){e.status(404).json({error:"Test file not found."});return}let i=Dm.statSync(o),a=await po(nt),s={gitBranch:a.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:a.gitCommitSha??"unknown"};e.status(200).json(s)}));yo.patch("/:testPath/metadata",Oe(async(t,e)=>{if(!t.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=jv.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Ef(t.params.testPath,r,me()).newRelativeTestPath};e.status(200).json(o)}));yo.patch("/:testPath",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Gv.parse(t.body)}catch(m){nt.warn({err:m},"Invalid save request"),e.status(400).json({error:`Invalid request body: ${m}`});return}nt.info({testPath:r},"Save received");let o=me(),i=await ee(o),a;try{a=Ql(r,o)}catch(m){e.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let{stepsToSave:s,moduleUpdates:c,cachesToSave:l}=await it({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:xt()}}),u=new et({apiKey:xr(),baseUrl:Cr(),logger:nt}),d=await Vr(nt,u,o);await Go({orgId:xt(),client:u,gitMetadata:d,regenerateCache:!1,alwaysSaveCache:!1,noCache:!1,bustOldestCachePercentage:void 0}).saveStepCacheEntries({logger:nt,testId:a.id,entries:l}),c.forEach(m=>{_r({content:m,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),Er({relativeTestPath:r,steps:s,schemaVersion:n.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));yo.patch("/:testPath/environments",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Yv.parse(t.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Ef(r,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},me()),e.status(201).json({message:"ok"})}));yo.post("/:testPath/duplicate",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=$v.parse(t.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Mo(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=me(),i=zs.join(o.rootDir,r);if(!Dm.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=await ee(o),s;try{s=await pt(i,nt,a)}catch(f){e.status(400).send({error:f.message});return}let c=Q2(),l=Gr.parse({...s,name:n.name,id:c}),{stepsToSave:u}=await it({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:xt()}}),d=Ln({fileType:Se.TEST,...l,beforeSteps:u.beforeSteps??void 0,steps:u.steps,afterSteps:u.afterSteps??void 0}),p=zs.dirname(i),m=zs.join(p,`${n.name}.test.yaml`),g=Z2.stringify(d);Dm.writeFileSync(m,g,"utf-8");let h={relativeFilePath:zs.relative(o.rootDir,m)};Wc.track({type:"test_editor:test_create"}),e.status(201).json(h)}));yo.post("/:testPath/chat",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let{messages:n}=t.body;if(!n){e.status(400).json({error:"Missing messages in request body."});return}let{sessionId:o}=t.body;if(!o){e.status(401).json({error:"Missing sessionId in request body."});return}let i=vm.getSession(o);if(!i){e.status(400).json({error:"No active browser session. Start a session first."});return}let a=me(),s=Ql(r,a),c=nt.child({orgId:xt(),userId:jo(),applicationName:"momentic-desktop-server-copilot",testId:s.id,sessionId:o});c.debug({sessionId:o},"Initializing copilot with sessionId");let l=Om({testPath:r,messages:n,logger:c,session:i,sessionId:o,saveChangesToDisk:!1});X2(l).pipeUIMessageStreamToResponse(e,{onError:d=>{let p=d instanceof Error?d.message:String(d);return c.error({err:d,sessionId:o},"streamText session failed"),p}})}));var SL=yo;async function TL(t){let{momenticServerUrl:e,apiKey:r,serverPort:n,staticDir:o,devicePixelRatio:i,regenerateCache:a,alwaysSaveCache:s,noCache:c,initialProject:l}=t;e&&zw(e),await Gw(r);let u=xt(),d=jo();Wc.identify({user_id:d,org_id:u});let p=t.logger??nt;p=p.child({orgId:u,userId:d}),p.debug({params:t},"Desktop server init and api key check done");let m=aY(o,n,p),g=`http://localhost:${n}`;zd(l,v=>_t({configFilePath:v})),await new Promise(v=>{try{m.listen(n,()=>{p.info(`Desktop server is running at ${g}`),v()})}catch(w){w.message.includes("EADDRINUSE")?vL(n):b.error(`An unexpected error occurred while starting the server: ${w.message}`),process.exit(1)}}),b.info(`Desktop server is running at ${g}`);let f={type:"API_KEY",baseUrl:Cr(),apiKey:r,logger:p,mode:"interactive"},S=async()=>{let v=me();return new no(v.config.ai?.agentConfig,f)},y=async()=>new Ho(f,await S()),E=new et(f),T=new ia;pO({baseServer:m,getOrgId:async()=>xt(),generatorFactory:S,enricherFactory:y,cacheStorageFactory:async v=>{let w=me(),C=await Vr(p,E,w);return Go({orgId:v,client:E,gitMetadata:C,regenerateCache:a??!1,alwaysSaveCache:s??!1,noCache:c??!1,bustOldestCachePercentage:void 0})},branchGetter:async()=>{try{return(await po(p))?.gitBranchName}catch(v){p.error({err:v},"Failed to get environment git metadata");return}},settingsFactory:async()=>{let v=me();return{ai:{},browser:{},...v.config}},storageFactory:async v=>new ai(E,v),logger:p,devicePixelRatio:i,authorization:f,visualDiffScreenshotStorage:T,globalE2eStateManager:vm})}var bL="25mb";function aY(t,e,r){let n=EL();n.use(eY()),n.use(yL.json({limit:bL})),n.use(yL.urlencoded({extended:!1,limit:bL}));let o=nY();if(o.use("/tests",SL),o.use("/modules",mO),o.use("/environments",fO),o.use("/projects",hL),o.use("/folders",yf),o.use("/settings",fL),o.use("/identify",yO),o.use("/entities",gO),o.use("/mcp",mL),o.use("/git",Pf),n.use("/api",o),n.use((a,s,c)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&r.debug({url:a.url,path:a.path,query:a.query,method:a.method,body:a.body,headers:a.rawHeaders,client:a.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&r.error({url:a.url,method:a.method,statusCode:s.statusCode},"Request completed in error")}),c()}),n.use((a,s,c,l)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}r.error({stack:a.stack,msg:a.message,err:a,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),b.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
4817
+ `).map(O=>O.trim()).filter(O=>O.length>0);g&&await Jy(n,{completed:u.total,total:u.total},"Evaluating edits and generating edit status...",i,p,r);let j=await U2(U,l,i);r.addResult(JSON.stringify({additions:N.additions,deletions:N.deletions,summarization:j},null,2))}}),cL=[N2,L2,D2,z2];var uL=[...bO,...cL,...Tm];function Qy(t,e){let r=new H2({name:e.applicationName,version:e.cliVersion},{capabilities:{logging:{},tools:{}}});for(let n of uL)n.addToolToMcpServer(t,r);return r}async function dL(t,e,r,n){let o=new G2(r,e,n);return await t.connect(o),{close:async()=>{try{await t.close()}catch{}},transport:o}}var Zy="mcp-session-id",q2="sessionId",Bs=W2(),$c=new Map;function pL(){let t={applicationName:"momentic-mcp-desktop-server",cliVersion:Ic??"0.0.0"},e=me(),r=nt.child({orgId:xt(),userId:jo(),...t});return{context:{project:e,logger:r,saveChangesToDisk:!0},info:t}}Bs.get("/sse",async(t,e)=>{let{context:r,info:n}=pL(),o=Qy(r,n),{transport:i}=await dL(o,e,"/api/mcp/sse",{enableDnsRebindingProtection:!1}),a=i.sessionId,s={transport:i,close:async()=>{$c.delete(a);try{await o.close()}catch(c){r.logger.warn({err:c},"Failed to close MCP server on SSE session cleanup")}}};$c.set(a,s),i.onclose=()=>{let c=$c.get(a);c&&c.close()}});Bs.post("/sse",async(t,e)=>{let r=String(t.query[q2]??"");if(!r||!$c.has(r)){e.status(400).send("Invalid or missing sessionId");return}await $c.get(r).transport.handlePostMessage(t,e,t.body)});var mL=Bs,So={};Bs.post("/",async(t,e)=>{let r=String(t.headers[Zy]??"");try{if(r&&So[r]){await So[r].handleRequest(t,e,t.body);return}if(!r&&V2(t.body)){let{context:n,info:o}=pL(),i=Qy(n,o),a=new j2({sessionIdGenerator:()=>$2(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{So[s]=a}});a.onclose=()=>{let s=a.sessionId;s&&So[s]&&delete So[s],i.close().catch(()=>{})},await i.connect(a),await a.handleRequest(t,e,t.body);return}e.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null})}catch{e.headersSent||e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}});Bs.get("/",async(t,e)=>{let r=String(t.headers[Zy]??"");if(!r||!So[r]){e.status(400).send("Invalid or missing session ID");return}await So[r].handleRequest(t,e)});Bs.delete("/",async(t,e)=>{let r=String(t.headers[Zy]??"");if(!r||!So[r]){e.status(400).send("Invalid or missing session ID");return}let n=So[r];try{await n.handleRequest(t,e)}catch{e.headersSent||e.status(500).send("Error processing session termination")}});import{Router as K2}from"express";var Nm=K2();Nm.get("/",Oe(async(t,e)=>{let r=(await Af()).map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(r)}));Nm.get("/current",Oe((t,e)=>{let r=me();if(!r){e.status(404).json({error:"No project found."});return}let n={name:r.config.name,configFilePath:r.configFilePath};e.status(200).json(n)}));Nm.post("/set",Oe(async(t,e)=>{let r;try{r=Xv.parse(t.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}nt.info("Setting local project");try{let n=await _t({configFilePath:r.configFilePath});zd(n,o=>_t({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var hL=Nm;import{Router as Y2}from"express";var gL=Y2();gL.get("/",Oe((t,e)=>{let r=me(),n={ai:r.config.ai,browser:r.config.browser,displayRoot:r.config.displayRoot};e.status(200).json(n)}));var fL=gL;import{streamText as X2}from"ai";import{Router as J2}from"express";import Dm from"fs";import zs from"path";import{v4 as Q2}from"uuid";import Z2 from"yaml";var Wc=new dp({platform:"local_app"},{flushAt:1,flushInterval:0});var yo=J2();yo.post("/",Oe(async(t,e)=>{let r;try{r=Vv.parse(t.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=me(),o=await Rm({project:n,input:r});Wc.track({type:"test_editor:test_create"}),e.status(201).json(o)}catch(n){if(n instanceof ot){e.status(400).json({error:n.message});return}throw n}}));yo.get("/:testPath",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n=me(),o=await te(n),i;try{i=await pt(zs.join(n.rootDir,r),nt,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:s}=await it({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});s.forEach(c=>{_r({content:c,schemaVersion:_e,momenticFiles:o,project:n})}),Er({relativeTestPath:r,steps:a,schemaVersion:_e,project:n})}catch(a){nt.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));yo.get("/:testPath/metadata",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n=me(),o=zs.join(n.rootDir,r);if(!Dm.existsSync(o)){e.status(404).json({error:"Test file not found."});return}let i=Dm.statSync(o),a=await po(nt),s={gitBranch:a.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:a.gitCommitSha??"unknown"};e.status(200).json(s)}));yo.patch("/:testPath/metadata",Oe(async(t,e)=>{if(!t.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=jv.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Ef(t.params.testPath,r,me()).newRelativeTestPath};e.status(200).json(o)}));yo.patch("/:testPath",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Gv.parse(t.body)}catch(m){nt.warn({err:m},"Invalid save request"),e.status(400).json({error:`Invalid request body: ${m}`});return}nt.info({testPath:r},"Save received");let o=me(),i=await te(o),a;try{a=Ql(r,o)}catch(m){e.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let{stepsToSave:s,moduleUpdates:c,cachesToSave:l}=await it({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:xt()}}),u=new et({apiKey:xr(),baseUrl:Cr(),logger:nt}),d=await Vr(nt,u,o);await Go({orgId:xt(),client:u,gitMetadata:d,regenerateCache:!1,alwaysSaveCache:!1,noCache:!1,bustOldestCachePercentage:void 0}).saveStepCacheEntries({logger:nt,testId:a.id,entries:l}),c.forEach(m=>{_r({content:m,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),Er({relativeTestPath:r,steps:s,schemaVersion:n.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));yo.patch("/:testPath/environments",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Yv.parse(t.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Ef(r,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},me()),e.status(201).json({message:"ok"})}));yo.post("/:testPath/duplicate",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=$v.parse(t.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Mo(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=me(),i=zs.join(o.rootDir,r);if(!Dm.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=await te(o),s;try{s=await pt(i,nt,a)}catch(f){e.status(400).send({error:f.message});return}let c=Q2(),l=Gr.parse({...s,name:n.name,id:c}),{stepsToSave:u}=await it({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:xt()}}),d=Ln({fileType:Se.TEST,...l,beforeSteps:u.beforeSteps??void 0,steps:u.steps,afterSteps:u.afterSteps??void 0}),p=zs.dirname(i),m=zs.join(p,`${n.name}.test.yaml`),g=Z2.stringify(d);Dm.writeFileSync(m,g,"utf-8");let h={relativeFilePath:zs.relative(o.rootDir,m)};Wc.track({type:"test_editor:test_create"}),e.status(201).json(h)}));yo.post("/:testPath/chat",Oe(async(t,e)=>{let{testPath:r}=t.params;if(!r){e.status(400).json({error:"Missing testPath in url path."});return}let{messages:n}=t.body;if(!n){e.status(400).json({error:"Missing messages in request body."});return}let{sessionId:o}=t.body;if(!o){e.status(401).json({error:"Missing sessionId in request body."});return}let i=vm.getSession(o);if(!i){e.status(400).json({error:"No active browser session. Start a session first."});return}let a=me(),s=Ql(r,a),c=nt.child({orgId:xt(),userId:jo(),applicationName:"momentic-desktop-server-copilot",testId:s.id,sessionId:o});c.debug({sessionId:o},"Initializing copilot with sessionId");let l=Om({testPath:r,messages:n,logger:c,session:i,sessionId:o,saveChangesToDisk:!1});X2(l).pipeUIMessageStreamToResponse(e,{onError:d=>{let p=d instanceof Error?d.message:String(d);return c.error({err:d,sessionId:o},"streamText session failed"),p}})}));var SL=yo;async function TL(t){let{momenticServerUrl:e,apiKey:r,serverPort:n,staticDir:o,devicePixelRatio:i,regenerateCache:a,alwaysSaveCache:s,noCache:c,initialProject:l}=t;e&&zw(e),await Gw(r);let u=xt(),d=jo();Wc.identify({user_id:d,org_id:u});let p=t.logger??nt;p=p.child({orgId:u,userId:d}),p.debug({params:t},"Desktop server init and api key check done");let m=aY(o,n,p),g=`http://localhost:${n}`;zd(l,v=>_t({configFilePath:v})),await new Promise(v=>{try{m.listen(n,()=>{p.info(`Desktop server is running at ${g}`),v()})}catch(w){w.message.includes("EADDRINUSE")?vL(n):b.error(`An unexpected error occurred while starting the server: ${w.message}`),process.exit(1)}}),b.info(`Desktop server is running at ${g}`);let f={type:"API_KEY",baseUrl:Cr(),apiKey:r,logger:p,mode:"interactive"},S=async()=>{let v=me();return new no(v.config.ai?.agentConfig,f)},y=async()=>new Ho(f,await S()),E=new et(f),T=new ia;pO({baseServer:m,getOrgId:async()=>xt(),generatorFactory:S,enricherFactory:y,cacheStorageFactory:async v=>{let w=me(),C=await Vr(p,E,w);return Go({orgId:v,client:E,gitMetadata:C,regenerateCache:a??!1,alwaysSaveCache:s??!1,noCache:c??!1,bustOldestCachePercentage:void 0})},branchGetter:async()=>{try{return(await po(p))?.gitBranchName}catch(v){p.error({err:v},"Failed to get environment git metadata");return}},settingsFactory:async()=>{let v=me();return{ai:{},browser:{},...v.config}},storageFactory:async v=>new ai(E,v),logger:p,devicePixelRatio:i,authorization:f,visualDiffScreenshotStorage:T,globalE2eStateManager:vm})}var bL="25mb";function aY(t,e,r){let n=EL();n.use(eY()),n.use(yL.json({limit:bL})),n.use(yL.urlencoded({extended:!1,limit:bL}));let o=nY();if(o.use("/tests",SL),o.use("/modules",mO),o.use("/environments",fO),o.use("/projects",hL),o.use("/folders",yf),o.use("/settings",fL),o.use("/identify",yO),o.use("/entities",gO),o.use("/mcp",mL),o.use("/git",Pf),n.use("/api",o),n.use((a,s,c)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&r.debug({url:a.url,path:a.path,query:a.query,method:a.method,body:a.body,headers:a.rawHeaders,client:a.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&r.error({url:a.url,method:a.method,statusCode:s.statusCode},"Request completed in error")}),c()}),n.use((a,s,c,l)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}r.error({stack:a.stack,msg:a.message,err:a,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),b.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
4818
4818
  ${a.stack}`),c.status(500).send(`Internal Server Error: ${a.message}`)}),t){let a=EL.static(t,{setHeaders:s=>{s.setHeader("Cache-Control","no-cache")},redirect:!1});n.use(a),n.use("*",(s,c)=>{c.sendFile(iY.join(t,"index.html"))})}let i=oY.createServer(n);return i.once("error",a=>{"code"in a&&a.code==="EADDRINUSE"?(vL(e),process.exit(1)):console.error("An unexpected server error occurred:",a.message)}),i}rY.setMaxListeners(25);process.on("warning",t=>{nt.warn({err:t},`Node warning received on desktop-server: ${t.message}`)});process.on("uncaughtException",t=>{nt.error({err:t},"Uncaught exception on desktop-server"),b.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${t.message}`)});process.on("unhandledRejection",(t,e)=>{nt.error({reason:`${t}`,stack:t?.stack},"Uncaught exception on desktop-server (promise rejection)"),b.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${t}`)});function vL(t){b.error(tY`Port ${t} is already in use by another process. Please close the other process and try again.
4819
4819
  Using Bash on MacOS or Linux:
4820
4820
  lsof -t -i :58888 | xargs kill -9
@@ -4828,25 +4828,25 @@ ${[...r].map(o=>`${dt}- ${o}`).join(`
4828
4828
  `)}`),n.size>0&&b.error(`Failed module files:
4829
4829
  ${[...n].map(o=>`${dt}- ${o}`).join(`
4830
4830
  `)}`)),b.warn(`
4831
- These schema/validation errors must be fixed manually before running the app.`)}function Kc(t){return AL.string().uuid().safeParse(t).success}async function km({fix:t,project:e}){let r=await ee(e),n=Object.values(r.tests),o=0,i=new Set,a=new Set,s={},c={},l=new Set,u={},d=new Set,p=0,m=[];for(let h of n)try{let f=Hi(h.fullFilePath,X,r),S=!1,y=!1;Kc(h.id)||(b.error(`Test '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${h.id}'`),p++,y=!0,t&&(h.id=Lr(),S=!0)),r.duplicateEntities[h.id]&&(b.error(`Test '${h.name}' (${h.relativePath}) has a duplicate ID: '${h.id}'`),p++,y=!0,t&&(h.id=Lr(),S=!0));let E=f.steps;if(!E||E.length===0||!Array.isArray(E)){b.debug(`Test ${h.name} (${h.relativePath}) has no steps, skipping...`);continue}let T=Xt.parse(f),v=await Ui(T,E,b);v.steps=v.steps.map((w,C)=>{w.id||(b.error(`Step ${C} in test '${h.name}' (${h.relativePath}) does not have an ID`),y=!0,t&&(S=!0,w.id=Lr())),Kc(w.id)||(b.error(`Step ${C} in test '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${w.id}'`),p++,y=!0,t&&(S=!0,w.id=Lr()));let _=s[w.id]?.testId,N=s[w.id]?.testRelativePath;if(_?(p++,y=!0,_===h.id?b.error(`Multiple steps in the test '${h.name}' (${h.relativePath}) have the same ID '${w.id}'`):b.error(`Step ${C} in test '${h.name}' (${h.relativePath}) has the ID ${w.id} which is duplicated in ${N}`),t&&(S=!0,w.id=Lr())):s[w.id]={testId:h.id,testRelativePath:h.relativePath},w.type==="PRESET_ACTION"){let U=w.command.id;Kc(U)||(b.error(`Command ${C} in test '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${U}'`),p++,y=!0,t&&(S=!0,w.command.id=Lr()));let j=c[U]?.testId,O=c[U]?.testRelativePath;j?(p++,y=!0,j===h.id?b.error(`Multiple commands in the test '${h.name}' (${h.relativePath}) have the same ID '${U}'`):b.error(`Command ${C} in test '${h.name}' (${h.relativePath}) has the ID ${U} which is duplicated in test ${O}`),t&&(S=!0,w.command.id=Lr())):c[U]={testId:h.id,testRelativePath:h.relativePath}}return Qe.parse(w)}),y&&b.dimmed("=".repeat(80)),S&&t&&(Er({relativeTestPath:h.relativePath,steps:{beforeSteps:f.beforeSteps,steps:v.steps,afterSteps:f.afterSteps},schemaVersion:_e,project:e}),l.add(h.fullFilePath))}catch(f){b.error({err:f},`Failed to parse test ${h.name} (${h.relativePath})`),f instanceof Co&&f.zodIssues&&f.zodIssues.forEach(S=>{m.push({file:h.relativePath,stepIndex:typeof S.path[0]=="number"?S.path[0]:void 0,field:S.path.slice(1).join(".")||S.path.join("."),issue:S.message})}),o++,i.add(h.relativePath);continue}let g=Object.values(r.modules);for(let h of g)try{let f=!1,S=!1;Kc(h.id)||(b.error(`Module '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${h.id}'`),p++,S=!0,t&&(h.id=Lr(),f=!0)),r.duplicateEntities[h.id]&&(b.error(`Module '${h.name}' (${h.relativePath}) has a duplicate ID: '${h.id}'`),p++,S=!0,t&&(h.id=Lr(),f=!0));let y=uo(h.fullFilePath,b),E=y.steps;if(!E||E.length===0||!Array.isArray(E)){b.debug(`Module ${h.name} (${h.relativePath}) has no steps, skipping...`);continue}let T,v;try{let C=await Ui({id:y.moduleId,schemaVersion:y.schemaVersion},y.steps,b);T=C.steps,v=C.newVersion}catch(C){b.error({err:C},`Failed to migrate module ${h.name} (${h.relativePath})`);continue}let w=T.map((C,_)=>{if(AL.string().uuid().safeParse(C.id)||(b.error(`Step ${_} in module '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${C.id}'`),p++,S=!0,t&&(f=!0,C.id=Lr())),s[C.id]?.testId){let U=s[C.id]?.testRelativePath;p++,S=!0,b.error(`Step ${_} in module '${h.name}' (${h.relativePath}) has the ID ${C.id} which is duplicated in test ${U}`),t&&(f=!0,C.id=Lr())}if(C.type==="PRESET_ACTION"){let U=C.command.id;Kc(U)||(b.error(`Command ${_} in module '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${U}'`),p++,S=!0,t&&(f=!0,C.command.id=Lr()));let j=c[U],O=u[U];j||O?(p++,S=!0,O?.moduleId===h.id?b.error(`Multiple commands in module '${h.name}' (${h.relativePath}) have the same ID '${U}'`):j?b.error(`Command in module '${h.name}' (${h.relativePath}) has the ID ${U} which is duplicated in test ${j.testRelativePath}`):b.error(`Command ${_} in module '${h.name}' (${h.relativePath}) has the ID ${U} which is duplicated in module ${O.moduleRelativePath}`),t&&(f=!0,C.command.id=Lr())):u[U]={moduleId:h.id,moduleRelativePath:h.relativePath}}return Qe.parse(C)});S&&b.dimmed("=".repeat(80)),f&&t&&(_r({content:{...y,steps:w},schemaVersion:v,momenticFiles:r,project:e,forceSaveOnNoDiffs:!0}),d.add(h.fullFilePath))}catch(f){b.error({err:f},`Failed to parse module ${h.name} (${h.relativePath})`),f instanceof Co&&f.zodIssues&&f.zodIssues.forEach(S=>{m.push({file:h.relativePath,stepIndex:typeof S.path[0]=="number"?S.path[0]:void 0,field:S.path.slice(1).join(".")||S.path.join("."),issue:S.message})}),a.add(h.relativePath),o++;continue}return{errors:p,parsingErrors:o,modifiedTestFilePaths:l,modifiedModuleFilePaths:d,failedTestFilePaths:i,failedModuleFilePaths:a,parsingErrorDetails:m}}async function wL({fix:t,project:e}){let{errors:r,parsingErrors:n,modifiedTestFilePaths:o,modifiedModuleFilePaths:i,failedTestFilePaths:a,failedModuleFilePaths:s,parsingErrorDetails:c}=await km({fix:t,project:e});n>0&&(qc({parsingErrors:n,parsingErrorDetails:c,failedTestFilePaths:a,failedModuleFilePaths:s}),process.exit(1)),r>0?(b.error(`Found errors in ${r} steps`),t?(b.warn(`Modified the following test files:
4831
+ These schema/validation errors must be fixed manually before running the app.`)}function Kc(t){return AL.string().uuid().safeParse(t).success}async function km({fix:t,project:e}){let r=await te(e),n=Object.values(r.tests),o=0,i=new Set,a=new Set,s={},c={},l=new Set,u={},d=new Set,p=0,m=[];for(let h of n)try{let f=Hi(h.fullFilePath,X,r),S=!1,y=!1;Kc(h.id)||(b.error(`Test '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${h.id}'`),p++,y=!0,t&&(h.id=Lr(),S=!0)),r.duplicateEntities[h.id]&&(b.error(`Test '${h.name}' (${h.relativePath}) has a duplicate ID: '${h.id}'`),p++,y=!0,t&&(h.id=Lr(),S=!0));let E=f.steps;if(!E||E.length===0||!Array.isArray(E)){b.debug(`Test ${h.name} (${h.relativePath}) has no steps, skipping...`);continue}let T=Xt.parse(f),v=await Ui(T,E,b);v.steps=v.steps.map((w,C)=>{w.id||(b.error(`Step ${C} in test '${h.name}' (${h.relativePath}) does not have an ID`),y=!0,t&&(S=!0,w.id=Lr())),Kc(w.id)||(b.error(`Step ${C} in test '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${w.id}'`),p++,y=!0,t&&(S=!0,w.id=Lr()));let _=s[w.id]?.testId,N=s[w.id]?.testRelativePath;if(_?(p++,y=!0,_===h.id?b.error(`Multiple steps in the test '${h.name}' (${h.relativePath}) have the same ID '${w.id}'`):b.error(`Step ${C} in test '${h.name}' (${h.relativePath}) has the ID ${w.id} which is duplicated in ${N}`),t&&(S=!0,w.id=Lr())):s[w.id]={testId:h.id,testRelativePath:h.relativePath},w.type==="PRESET_ACTION"){let U=w.command.id;Kc(U)||(b.error(`Command ${C} in test '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${U}'`),p++,y=!0,t&&(S=!0,w.command.id=Lr()));let j=c[U]?.testId,O=c[U]?.testRelativePath;j?(p++,y=!0,j===h.id?b.error(`Multiple commands in the test '${h.name}' (${h.relativePath}) have the same ID '${U}'`):b.error(`Command ${C} in test '${h.name}' (${h.relativePath}) has the ID ${U} which is duplicated in test ${O}`),t&&(S=!0,w.command.id=Lr())):c[U]={testId:h.id,testRelativePath:h.relativePath}}return Ze.parse(w)}),y&&b.dimmed("=".repeat(80)),S&&t&&(Er({relativeTestPath:h.relativePath,steps:{beforeSteps:f.beforeSteps,steps:v.steps,afterSteps:f.afterSteps},schemaVersion:_e,project:e}),l.add(h.fullFilePath))}catch(f){b.error({err:f},`Failed to parse test ${h.name} (${h.relativePath})`),f instanceof Co&&f.zodIssues&&f.zodIssues.forEach(S=>{m.push({file:h.relativePath,stepIndex:typeof S.path[0]=="number"?S.path[0]:void 0,field:S.path.slice(1).join(".")||S.path.join("."),issue:S.message})}),o++,i.add(h.relativePath);continue}let g=Object.values(r.modules);for(let h of g)try{let f=!1,S=!1;Kc(h.id)||(b.error(`Module '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${h.id}'`),p++,S=!0,t&&(h.id=Lr(),f=!0)),r.duplicateEntities[h.id]&&(b.error(`Module '${h.name}' (${h.relativePath}) has a duplicate ID: '${h.id}'`),p++,S=!0,t&&(h.id=Lr(),f=!0));let y=uo(h.fullFilePath,b),E=y.steps;if(!E||E.length===0||!Array.isArray(E)){b.debug(`Module ${h.name} (${h.relativePath}) has no steps, skipping...`);continue}let T,v;try{let C=await Ui({id:y.moduleId,schemaVersion:y.schemaVersion},y.steps,b);T=C.steps,v=C.newVersion}catch(C){b.error({err:C},`Failed to migrate module ${h.name} (${h.relativePath})`);continue}let w=T.map((C,_)=>{if(AL.string().uuid().safeParse(C.id)||(b.error(`Step ${_} in module '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${C.id}'`),p++,S=!0,t&&(f=!0,C.id=Lr())),s[C.id]?.testId){let U=s[C.id]?.testRelativePath;p++,S=!0,b.error(`Step ${_} in module '${h.name}' (${h.relativePath}) has the ID ${C.id} which is duplicated in test ${U}`),t&&(f=!0,C.id=Lr())}if(C.type==="PRESET_ACTION"){let U=C.command.id;Kc(U)||(b.error(`Command ${_} in module '${h.name}' (${h.relativePath}) has an ID that does not parse as a UUID: '${U}'`),p++,S=!0,t&&(f=!0,C.command.id=Lr()));let j=c[U],O=u[U];j||O?(p++,S=!0,O?.moduleId===h.id?b.error(`Multiple commands in module '${h.name}' (${h.relativePath}) have the same ID '${U}'`):j?b.error(`Command in module '${h.name}' (${h.relativePath}) has the ID ${U} which is duplicated in test ${j.testRelativePath}`):b.error(`Command ${_} in module '${h.name}' (${h.relativePath}) has the ID ${U} which is duplicated in module ${O.moduleRelativePath}`),t&&(f=!0,C.command.id=Lr())):u[U]={moduleId:h.id,moduleRelativePath:h.relativePath}}return Ze.parse(C)});S&&b.dimmed("=".repeat(80)),f&&t&&(_r({content:{...y,steps:w},schemaVersion:v,momenticFiles:r,project:e,forceSaveOnNoDiffs:!0}),d.add(h.fullFilePath))}catch(f){b.error({err:f},`Failed to parse module ${h.name} (${h.relativePath})`),f instanceof Co&&f.zodIssues&&f.zodIssues.forEach(S=>{m.push({file:h.relativePath,stepIndex:typeof S.path[0]=="number"?S.path[0]:void 0,field:S.path.slice(1).join(".")||S.path.join("."),issue:S.message})}),a.add(h.relativePath),o++;continue}return{errors:p,parsingErrors:o,modifiedTestFilePaths:l,modifiedModuleFilePaths:d,failedTestFilePaths:i,failedModuleFilePaths:a,parsingErrorDetails:m}}async function wL({fix:t,project:e}){let{errors:r,parsingErrors:n,modifiedTestFilePaths:o,modifiedModuleFilePaths:i,failedTestFilePaths:a,failedModuleFilePaths:s,parsingErrorDetails:c}=await km({fix:t,project:e});n>0&&(qc({parsingErrors:n,parsingErrorDetails:c,failedTestFilePaths:a,failedModuleFilePaths:s}),process.exit(1)),r>0?(b.error(`Found errors in ${r} steps`),t?(b.warn(`Modified the following test files:
4832
4832
  ${[...o].map(l=>`${dt}- ${l}`).join(`
4833
4833
  `)}`),i.size>0&&b.warn(`Modified the following module files:
4834
4834
  ${[...i].map(l=>`${dt}- ${l}`).join(`
4835
- `)}`)):b.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(b.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function CL({project:t}){let e=await ee(t),r=Object.values(e.tests),n=await Gd(e,X),o={},i={},a=new Set,s=new Set;for(let l of r)o[l.name]?i[l.name]?i[l.name].push(l.fullFilePath):i[l.name]=[o[l.name],l.fullFilePath]:o[l.name]=l.fullFilePath;for(let l of n)s.has(l.name)&&a.add(l.name),s.add(l.name);if(Object.entries(i).length>0||a.size>0){for(let[l,u]of Object.entries(i))for(let d of u)b.error(`Test Name ${l} is duplicated in ${d}`);for(let l of a)b.error(`Module name ${l} is duplicated in your project`);process.exit(1)}b.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as cY}from"lodash-es";async function xL({client:t,skipPrompts:e,project:r}){let n=await t.getAllEnvironments(),o=cY(r.config);o.environments||(o.environments=[]);for(let i of n){let a=o.environments?.find(s=>s.name===i.name);if(a)!e&&!await Bt(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[Rt],delete i.variables[Rt],a.envVariables=i.variables;else{let s=i.variables[Rt];delete i.variables[Rt],o.environments.push({name:i.name,baseUrl:s,envVariables:i.variables})}}$o(o,r.configFilePath),b.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as _L}from"crypto";import ML from"fs";async function eE({testsToFetch:t,client:e,all:r,yes:n}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:t,all:r}),a=0;for(let[c,l]of Object.entries(o)){let u=PL(c,Se.TEST);!n&&!await Gg(u)||(a+=1,ML.writeFileSync(u,l,"utf-8"),X.info({checksum:_L("md5").update(l).digest("hex")},`Wrote '${u}'`))}let s=0;for(let[c,l]of Object.entries(i)){let u=PL(c,Se.MODULE);!n&&!await Gg(u)||(s+=1,ML.writeFileSync(u,l,"utf-8"),X.info({checksum:_L("md5").update(l).digest("hex")},`Wrote '${u}'`))}a===0?b.success("Pulled 0 tests."):b.success(`Pulled ${a} test${a>1?"s":""}${s?` and ${s} module${s>1?"s":""}`:""}!`)}function PL(t,e){switch(e){case Se.TEST:return`${ze(t)}.test.yaml`;case Se.MODULE:return`${ze(t)}.module.yaml`;default:throw new Error(`Unknown entity type ${e}`)}}async function IL(t){let{project:e,client:r,skipPrompts:n}=t;b.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),b.info("Importing environments from Momentic Cloud."),b.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await Bt("Are you sure you want to proceed?")||(b.info("Aborting..."),process.exit(1)),await xL({client:r,project:e,skipPrompts:n}),b.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),b.info("Importing tests and modules from Momentic Cloud."),await eE({testsToFetch:[],client:r,all:!0,yes:n}),b.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}async function OL(t){let{client:e,skipPrompts:r,paths:n}=t;await eE({testsToFetch:n,client:e,all:void 0,yes:r}),b.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import{Argument as pa,InvalidArgumentError as Yc,Option as Be}from"@commander-js/extra-typings";import{validateHeaderValue as uY}from"http";import{z as LL}from"zod";var Fm=58888;function Wn(t){let e=parseInt(t,10);if(isNaN(e))throw new Yc("Not a number.");return e}function Um(t){if(t===void 0)return;let e={};for(let r of t){let n=r.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${r}`);let o=r.slice(0,n),i=r.slice(n+1);uY(o,i),e[o]=i}return e}var Zr=new Be("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(t=>{if(!t)throw new Yc("API key is required.");return t}).makeOptionMandatory(),en=new Be("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(t=>{try{return LL.string().url().parse(t),t}catch{throw new Yc("Not a valid URL.")}}),ui=new Be("-y, --yes","Skip all confirmation prompts.").env("CI"),tE=new Be("-w, --wait","Wait for tests to finish running before exiting."),rE=new Be("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${18e5/1e3} seconds.`).default(18e5/1e3).implies({wait:!0}).argParser(Wn),Bm=new Be("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),NL=new Be("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(Bu)),DL=new Be("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),nE=new Be("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),kL=new Be("--upload-results","Upload test results to Momentic Cloud.").default(!1),oE=new Be("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),iE=new Be("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),aE=new Be("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(Wn),sE=new Be("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),zm=new Be("--env <env>","Name of the environment to use when running tests."),Hm=new Be("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(t=>{try{return LL.string().url().parse(t),t}catch{throw new Yc("Not a valid URL.")}}),FL=new Be("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(t=>{let e=Wn(t);if(e<1)throw new Yc("Shard index must be greater than 0.");return e}),UL=new Be("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Wn),mr=new Be("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),di=new Be("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),BL=new Be("--fix","Attempt to fix any issues found."),lE=new Be("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.").implies({disableCache:!1,saveCache:!0}),cE=new Be("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI").implies({disableCache:!1}),uE=new Be("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1,regenerateCache:!1}),zL=new Be("--bust-oldest-cache-percentage <n>","Bust the oldest n% of step caches when running tests. This option can be used to incrementally regenerate caches after a config change. When enabled, there will always be at least one cache busted, even if n% is less than 1. This option is only used when running on not protected branches.").implies({disableCache:!1,regenerateCache:!1}).argParser(Wn),HL=new Be("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),GL=new Be("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),jL=new Be("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),VL=new Be("--record-video","Record video of test runs. By default, video is never recorded. It is recommended to only enable this when debugging test failures, as it causes larger test outputs. FFMpeg must be installed to use this flag."),$L=new pa("<tests...>","One or more test paths to queue on Momentic Cloud."),WL=new pa("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),dE=new pa("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),qL=new pa("<suites...>","One or more suite paths that exist on Momentic Cloud."),KL=new pa("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),YL=new pa("<results>","Path to the results archive.").argRequired(),pE=new Be("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),mE=new pa("<test>","Name of the test to quarantine.").argOptional(),XL=new Be("--timeout-minutes <timeoutMinutes>","Maximum number of minutes to run tests before stopping. When the timeout is reached, tests will stop and current results will be printed.").argParser(Wn);async function JL(t){let e=await ee(t),r=Object.values(e.tests);for(let n of r)try{let o=Hi(n.fullFilePath,b,e),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){b.debug(`Test ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=Xt.parse(o),s=await Ui(a,i,b);b.dimmed(`Updating ${n.relativePath}`),Er({relativeTestPath:n.relativePath,steps:{beforeSteps:o.beforeSteps,steps:s.steps,afterSteps:o.afterSteps},schemaVersion:_e,project:t,forceSaveOnNoDiffs:!0})}catch(o){b.error({err:o},`Failed to read or migrate test ${n.name} (${n.relativePath}), continuing...`)}for(let n of Object.values(e.modules)){b.dimmed(`Updating ${n.relativePath}`);try{let o=uo(n.fullFilePath,b),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){b.debug(`Module ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=await Ui({id:o.moduleId,schemaVersion:o.schemaVersion},i,b);_r({content:{...o,steps:a.steps},schemaVersion:_e,momenticFiles:e,project:t,forceSaveOnNoDiffs:!0})}catch(o){b.error({err:o},`Failed to read or migrate module ${n.name} (${n.relativePath}), continuing...`)}}}import{spawnSync as pY}from"child_process";function mY(){try{let e=pY("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();b.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(t){let e=t instanceof Error?t.message:String(t);b.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
4836
- ${e}`)}}async function QL({project:t,orgId:e,apiClient:r}){b.info("Pulling browser and AI configuration options from Cloud");let n=await up.init(e);t.config.browser={autoExpandIframes:n.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:n.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:n.isBooleanFlagEnabled("global_locator_redirect"),visualActions:n.isBooleanFlagEnabled("visual_actions"),showZeroOpacityElements:n.isBooleanFlagEnabled("show_zero_opacity_elements"),...t.config.browser},t.config.advanced={fakerConstantSeed:n.isBooleanFlagEnabled("faker_constant_seed"),...t.config.advanced},t.config.ai={aiPageFiltering:n.isBooleanFlagEnabled("rag_v2"),agentConfig:await r.getAgentConfig(),...t.config.ai},b.info(`Updated ${t.configFilePath} to include V2 browser and AI configuration options`),b.info("Determining main Git branch"),t.config.gitMainBranch=mY(),$o(t.config,t.configFilePath),b.success("Migration complete!")}import{input as hY,search as gY}from"@inquirer/prompts";import fY from"fuse.js";async function Gm({prompt:t,inputtedTest:e,testOptions:r}){if(e){let s=r.find(c=>c.name===e||c.relativePath===e);if(!s)b.error(`${e} is not a valid test option.`);else return{name:s.name,id:s.id}}let n=r.map(s=>({value:s.id,name:s.name})),o=new fY(n,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),i=await gY({message:t,source:async s=>!s||s.length===0?n:o.search({name:s}).map(l=>l.item)}),a=n.find(s=>s.value===i);return{name:a.name,id:a.value}}async function jm({prompt:t,inputtedReason:e}){return e||hY({message:t})}async function ZL({test:t,reason:e,apiClient:r,project:n,logger:o,identity:i}){let a=(await ee(n)).tests,s=await Gm({prompt:"Select a test to quarantine.",inputtedTest:t,testOptions:Object.values(a)}),c=await jm({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await r.quarantineTest(s,c,i),b.success(`Test ${s.name} has been successfully quarantined. Navigate to ${r.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${s.name}'.`)}import hE from"fs";import{compact as SY,partition as Vm}from"lodash-es";import gE from"path";import{cwd as yY}from"process";import EY from"semver";async function Hs({tests:t,momenticFiles:e,project:r,yes:n,include:o,exclude:i,labels:a,logger:s}){let c=new Set;if(t&&t.length>0){let u=t.some(p=>hE.existsSync(p)),d=yY();u?(d!==r.rootDir&&s.warn(`The current working directory ('${d}') is different from the project root directory ('${r.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),s.info(`Reading tests from the following local file paths:
4835
+ `)}`)):b.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(b.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function CL({project:t}){let e=await te(t),r=Object.values(e.tests),n=await Gd(e,X),o={},i={},a=new Set,s=new Set;for(let l of r)o[l.name]?i[l.name]?i[l.name].push(l.fullFilePath):i[l.name]=[o[l.name],l.fullFilePath]:o[l.name]=l.fullFilePath;for(let l of n)s.has(l.name)&&a.add(l.name),s.add(l.name);if(Object.entries(i).length>0||a.size>0){for(let[l,u]of Object.entries(i))for(let d of u)b.error(`Test Name ${l} is duplicated in ${d}`);for(let l of a)b.error(`Module name ${l} is duplicated in your project`);process.exit(1)}b.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as cY}from"lodash-es";async function xL({client:t,skipPrompts:e,project:r}){let n=await t.getAllEnvironments(),o=cY(r.config);o.environments||(o.environments=[]);for(let i of n){let a=o.environments?.find(s=>s.name===i.name);if(a)!e&&!await Bt(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[Rt],delete i.variables[Rt],a.envVariables=i.variables;else{let s=i.variables[Rt];delete i.variables[Rt],o.environments.push({name:i.name,baseUrl:s,envVariables:i.variables})}}$o(o,r.configFilePath),b.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as _L}from"crypto";import ML from"fs";async function eE({testsToFetch:t,client:e,all:r,yes:n}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:t,all:r}),a=0;for(let[c,l]of Object.entries(o)){let u=PL(c,Se.TEST);!n&&!await Gg(u)||(a+=1,ML.writeFileSync(u,l,"utf-8"),X.info({checksum:_L("md5").update(l).digest("hex")},`Wrote '${u}'`))}let s=0;for(let[c,l]of Object.entries(i)){let u=PL(c,Se.MODULE);!n&&!await Gg(u)||(s+=1,ML.writeFileSync(u,l,"utf-8"),X.info({checksum:_L("md5").update(l).digest("hex")},`Wrote '${u}'`))}a===0?b.success("Pulled 0 tests."):b.success(`Pulled ${a} test${a>1?"s":""}${s?` and ${s} module${s>1?"s":""}`:""}!`)}function PL(t,e){switch(e){case Se.TEST:return`${ze(t)}.test.yaml`;case Se.MODULE:return`${ze(t)}.module.yaml`;default:throw new Error(`Unknown entity type ${e}`)}}async function IL(t){let{project:e,client:r,skipPrompts:n}=t;b.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),b.info("Importing environments from Momentic Cloud."),b.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await Bt("Are you sure you want to proceed?")||(b.info("Aborting..."),process.exit(1)),await xL({client:r,project:e,skipPrompts:n}),b.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),b.info("Importing tests and modules from Momentic Cloud."),await eE({testsToFetch:[],client:r,all:!0,yes:n}),b.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}async function OL(t){let{client:e,skipPrompts:r,paths:n}=t;await eE({testsToFetch:n,client:e,all:void 0,yes:r}),b.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import{Argument as pa,InvalidArgumentError as Yc,Option as Be}from"@commander-js/extra-typings";import{validateHeaderValue as uY}from"http";import{z as LL}from"zod";var Fm=58888;function Wn(t){let e=parseInt(t,10);if(isNaN(e))throw new Yc("Not a number.");return e}function Um(t){if(t===void 0)return;let e={};for(let r of t){let n=r.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${r}`);let o=r.slice(0,n),i=r.slice(n+1);uY(o,i),e[o]=i}return e}var Zr=new Be("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(t=>{if(!t)throw new Yc("API key is required.");return t}).makeOptionMandatory(),en=new Be("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(t=>{try{return LL.string().url().parse(t),t}catch{throw new Yc("Not a valid URL.")}}),ui=new Be("-y, --yes","Skip all confirmation prompts.").env("CI"),tE=new Be("-w, --wait","Wait for tests to finish running before exiting."),rE=new Be("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${18e5/1e3} seconds.`).default(18e5/1e3).implies({wait:!0}).argParser(Wn),Bm=new Be("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),NL=new Be("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(Bu)),DL=new Be("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),nE=new Be("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),kL=new Be("--upload-results","Upload test results to Momentic Cloud.").default(!1),oE=new Be("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),iE=new Be("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),aE=new Be("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(Wn),sE=new Be("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),zm=new Be("--env <env>","Name of the environment to use when running tests."),Hm=new Be("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(t=>{try{return LL.string().url().parse(t),t}catch{throw new Yc("Not a valid URL.")}}),FL=new Be("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(t=>{let e=Wn(t);if(e<1)throw new Yc("Shard index must be greater than 0.");return e}),UL=new Be("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Wn),mr=new Be("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),di=new Be("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),BL=new Be("--fix","Attempt to fix any issues found."),lE=new Be("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.").implies({disableCache:!1,saveCache:!0}),cE=new Be("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI").implies({disableCache:!1}),uE=new Be("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1,regenerateCache:!1}),zL=new Be("--bust-oldest-cache-percentage <n>","Bust the oldest n% of step caches when running tests. This option can be used to incrementally regenerate caches after a config change. When enabled, there will always be at least one cache busted, even if n% is less than 1. This option is only used when running on not protected branches.").implies({disableCache:!1,regenerateCache:!1}).argParser(Wn),HL=new Be("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),GL=new Be("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),jL=new Be("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),VL=new Be("--record-video","Record video of test runs. By default, video is never recorded. It is recommended to only enable this when debugging test failures, as it causes larger test outputs. FFMpeg must be installed to use this flag."),$L=new pa("<tests...>","One or more test paths to queue on Momentic Cloud."),WL=new pa("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),dE=new pa("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),qL=new pa("<suites...>","One or more suite paths that exist on Momentic Cloud."),KL=new pa("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),YL=new pa("<results>","Path to the results archive.").argRequired(),pE=new Be("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),mE=new pa("<test>","Name of the test to quarantine.").argOptional(),XL=new Be("--timeout-minutes <timeoutMinutes>","Maximum number of minutes to run tests before stopping. When the timeout is reached, tests will stop and current results will be printed.").argParser(Wn);async function JL(t){let e=await te(t),r=Object.values(e.tests);for(let n of r)try{let o=Hi(n.fullFilePath,b,e),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){b.debug(`Test ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=Xt.parse(o),s=await Ui(a,i,b);b.dimmed(`Updating ${n.relativePath}`),Er({relativeTestPath:n.relativePath,steps:{beforeSteps:o.beforeSteps,steps:s.steps,afterSteps:o.afterSteps},schemaVersion:_e,project:t,forceSaveOnNoDiffs:!0})}catch(o){b.error({err:o},`Failed to read or migrate test ${n.name} (${n.relativePath}), continuing...`)}for(let n of Object.values(e.modules)){b.dimmed(`Updating ${n.relativePath}`);try{let o=uo(n.fullFilePath,b),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){b.debug(`Module ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=await Ui({id:o.moduleId,schemaVersion:o.schemaVersion},i,b);_r({content:{...o,steps:a.steps},schemaVersion:_e,momenticFiles:e,project:t,forceSaveOnNoDiffs:!0})}catch(o){b.error({err:o},`Failed to read or migrate module ${n.name} (${n.relativePath}), continuing...`)}}}import{spawnSync as pY}from"child_process";function mY(){try{let e=pY("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();b.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(t){let e=t instanceof Error?t.message:String(t);b.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
4836
+ ${e}`)}}async function QL({project:t,orgId:e,apiClient:r}){b.info("Pulling browser and AI configuration options from Cloud");let n=await up.init(e);t.config.browser={autoExpandIframes:n.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:n.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:n.isBooleanFlagEnabled("global_locator_redirect"),visualActions:n.isBooleanFlagEnabled("visual_actions"),showZeroOpacityElements:n.isBooleanFlagEnabled("show_zero_opacity_elements"),...t.config.browser},t.config.advanced={fakerConstantSeed:n.isBooleanFlagEnabled("faker_constant_seed"),...t.config.advanced},t.config.ai={aiPageFiltering:n.isBooleanFlagEnabled("rag_v2"),agentConfig:await r.getAgentConfig(),...t.config.ai},b.info(`Updated ${t.configFilePath} to include V2 browser and AI configuration options`),b.info("Determining main Git branch"),t.config.gitMainBranch=mY(),$o(t.config,t.configFilePath),b.success("Migration complete!")}import{input as hY,search as gY}from"@inquirer/prompts";import fY from"fuse.js";async function Gm({prompt:t,inputtedTest:e,testOptions:r}){if(e){let s=r.find(c=>c.name===e||c.relativePath===e);if(!s)b.error(`${e} is not a valid test option.`);else return{name:s.name,id:s.id}}let n=r.map(s=>({value:s.id,name:s.name})),o=new fY(n,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),i=await gY({message:t,source:async s=>!s||s.length===0?n:o.search({name:s}).map(l=>l.item)}),a=n.find(s=>s.value===i);return{name:a.name,id:a.value}}async function jm({prompt:t,inputtedReason:e}){return e||hY({message:t})}async function ZL({test:t,reason:e,apiClient:r,project:n,logger:o,identity:i}){let a=(await te(n)).tests,s=await Gm({prompt:"Select a test to quarantine.",inputtedTest:t,testOptions:Object.values(a)}),c=await jm({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await r.quarantineTest(s,c,i),b.success(`Test ${s.name} has been successfully quarantined. Navigate to ${r.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${s.name}'.`)}import hE from"fs";import{compact as SY,partition as Vm}from"lodash-es";import gE from"path";import{cwd as yY}from"process";import EY from"semver";async function Hs({tests:t,momenticFiles:e,project:r,yes:n,include:o,exclude:i,labels:a,logger:s}){let c=new Set;if(t&&t.length>0){let u=t.some(p=>hE.existsSync(p)),d=yY();u?(d!==r.rootDir&&s.warn(`The current working directory ('${d}') is different from the project root directory ('${r.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),s.info(`Reading tests from the following local file paths:
4837
4837
  ${t.map(p=>`${dt}- ${p}`).join(`
4838
4838
  `)}
4839
4839
  `),t.forEach(p=>{if(!hE.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=hE.statSync(p),g=m.isDirectory()}catch(f){s.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=gE.resolve(p);Object.values(e.tests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(s.info(`Reading all tests from the project and running those matching the following substring filters:
4840
4840
  ${t.map(p=>`${dt}- ${p}`).join(`
4841
- `)}`),Object.values(e.tests).forEach(p=>{t.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Bt("No test paths or substrings were provided. Do you want to run all tests?")&&(s.error("Cancelled by user."),process.exit(1));let u=Object.values(e.tests);s.info(`Reading all ${u.length} tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of c){let d=gE.relative(r.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}let l=Array.from(c).map(async u=>{try{let d=await pt(u,X,e);if(EY.gt(d.schemaVersion,_e)&&s.warn(`Test ${u} has schema version ${d.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),a&&a.length>0){let p=d.labels||[];if(!a.some(g=>p.includes(g)))return null}return{...d,fullFilePath:u,relativeFilePath:gE.relative(r.rootDir,u)}}catch(d){s.error(`Failed to read and resolve test at '${u}': ${d}`),process.exit(1)}});return Promise.all(l).then(SY)}function eN({testDefinitions:t,quarantinedTestReasons:e,onlyQuarantined:r=!1,skipQuarantined:n=!1}){if(r){let[u,d]=Vm(t,g=>g.id in e),[p,m]=Vm(u,g=>g.disabled||n);return{testsToSkip:p,quarantinedTestsToSkip:[],testsToRun:m,quarantinedTestsToRun:[]}}let[o,i]=Vm(t,u=>u.disabled),[a,s]=Vm(i,u=>u.id in e);return{testsToSkip:o,testsToRun:s,quarantinedTestsToRun:n?[]:a,quarantinedTestsToSkip:n?a:[]}}function tN({testsToRun:t,quarantinedTestsToRun:e,quarantinedTestReasons:r,testInputMatrix:n}){let o=[],i=(a,s,c)=>{n?n.forEach((l,u)=>{o.push({inputs:l,inputIndex:u,testDefinition:a,quarantined:s,quarantinedReason:c})}):o.push({inputs:void 0,testDefinition:a,quarantined:s,quarantinedReason:c})};return t.forEach(a=>i(a,!1)),e.forEach(a=>i(a,!0,r[a.id])),o}async function rN({project:t,apiClient:e}){let r=await ee(t),n=await Hs({tests:[],momenticFiles:r,yes:!0,project:t,logger:new Li(40,{})}),o=(await e.getQuarantinedTests()).quarantined,i=new Set(o.map(s=>s.testId)),a=n.filter(s=>i.has(s.id));b.info(a.map(s=>s.relativeFilePath).join(`
4842
- `))}async function nN({test:t,reason:e,apiClient:r,project:n,identity:o}){let i=(await ee(n)).tests,a=Object.values(i),s=(await r.getQuarantinedTests()).quarantined,c=new Set(s.map(p=>p.testId)),l=a.filter(p=>c.has(p.id)),u=await Gm({prompt:"Select a test to unquarantine.",inputtedTest:t,testOptions:l}),d=await jm({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await r.unquarantineTest(u,d,o),b.success(`Test ${u.name} has been successfully removed from quarantine.`)}function oN(t){return t?ze(t):"Unknown suite"}async function iN({client:t,orgId:e,suitePaths:r,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:s}=await t.queueSuiteRuns({paths:r,...i});X.info({orgId:e,suiteRunIds:a,runGroupIds:s,suitePaths:r},"Queued suites remotely"),b.dimmed(`Queued ${r.length} suites.`),n||process.exit(0);let c=Date.now();b.dimmed(`Waiting for ${r.length} suites to finish. You can view results upon completion at:`);for(let f of s)b.dimmed(`${dt}- ${t.getAppUrl()}/run-groups/${f}`);let l=new Set,u=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(y=>y.status==="FAILED"&&(y.failureReason||y.finishedAt&&Date.now()-y.finishedAt.getTime()>30*1e3)||y.status==="PASSED"||y.status==="CANCELLED"),p=await dd({name:"suites",getResults:async()=>{let f=s.filter(E=>!u.some(T=>T.id===E)),S=await t.bulkGetRunGroupStatus(f),y=[];for(let E of S)d(E)?u.push(E):y.push(E);return[...u,...y]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(l.has(S.id)||(l.add(S.id),b.log(`${l.size}/${s.length} ${oN(S.suite?.name)}`)))}),f.every(d))}),m=t.getAppUrl(),h=Ja({results:p,startTime:c,onFailed:f=>{let S=oN(f.suite?.name),y=f.runs.filter(T=>T.status==="FAILED").length,E=f.runs.length;b.error(`${S} (${y}/${E} tests failed):`);for(let T of f.runs)if(T.status==="FAILED"){let v=T.testName||T.test?.name;b.error(` ${v?ze(v):"Unknown test"} (${m}/runs/${T.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?ze(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function aN({tests:t,client:e,orgId:r,...n}){!n.yes&&!await Bt(`This command will queue ${t.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:t,...n});if(X.info({queuedTests:o,runIds:i,orgId:r},"Queued tests remotely"),b.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),n.wait||process.exit(0),!i.length)return;b.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,s=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",l=e.getAppUrl(),u=Date.now(),d=await dd({name:"runs",getResults:async()=>{let m=i.filter(f=>!s.some(S=>S.id===f)),g=await e.bulkGetRunStatus(m),h=[];for(let f of g)c(f)?s.push(f):h.push(f);return[...s,...h]},timeoutMs:n.waitTimeout?n.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(g=>{if(g.status==="RUNNING"&&!a.has(g.id)){a.add(g.id);let h=g.testName||g.test?.name;h&&b.log(`${a.size}/${o.length} ${ze(h)}`)}}),m.every(c))}),p=Ja({results:d,startTime:u,onFailed:m=>{let g=m.testName||m.test?.name;pd(m,g?ze(g):"Unknown test")},getDisplayLine:m=>{let g=m.testName||m.test?.name,h=` ${g?ze(g):"Unknown test"}`;return m.id&&(h+=` (${l}/runs/${m.id})`),h},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as o5}from"crypto";import i5 from"fs";import{existsSync as LY,mkdirSync as NY,statSync as DY}from"fs";import{randomUUID as ma}from"crypto";import Gs,{writeFileSync as sN}from"fs";import{hostname as bY}from"os";import qn from"path";import{z as $m}from"zod";async function qm(t,e,r,n){if(n){let o=await e.getScreenshot(t,n);if(o){let i=`screenshot-${n}.jpeg`,a=qn.join(r,i);return Gs.writeFileSync(a,o),i}}}async function TY(t,e,r,n){let o=r.folder,i={uuid:n.runAttemptId??ma(),historyId:n.runId??ma(),testCaseId:n.test.id,fullName:n.test.name,name:ze(n.test.name),status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"skipped":"failed",start:n.lastAttemptStartedAt.getTime(),stop:n.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:r.suiteName},{name:"host",value:bY()},{name:"platform",value:"momentic"},{name:"attempts",value:n.attempts.toString()}],steps:[]};n.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${n.runId}`});for(let[c,l]of Object.entries(n.parameters))l!=null&&i.parameters.push({name:c,value:JSON.stringify(l)});n.results&&await fE(t,e,r.folder,i.steps,n.results);let a=vY(e,o,i.uuid);a.length>0&&(i.attachments=a);let s=`${n.runAttemptId}-result.json`;Gs.writeFileSync(qn.join(o,s),JSON.stringify(i,void 0,2))}async function Wm(t,e,r,n){let o={name:fw(n),start:n.startedAt.getTime(),stop:n.finishedAt.getTime(),status:n.status==="SUCCESS"?"passed":n.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};n.beforeUrl&&o.labels?.push({name:"URL before step",value:n.beforeUrl}),n.afterUrl&&o.labels?.push({name:"URL after step",value:n.afterUrl});let i=await qm(t,e,r,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await qm(t,e,r,n.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),n.message&&(o.statusDetails={message:n.message}),n.data)if(al.safeParse(n.data).success){let s=al.parse(n.data),c=s.request,l={...s,request:void 0},u=`output-attachment-api-request-${ma()}.json`,d=`output-attachment-api-response-${ma()}.json`,p=qn.join(r,u),m=qn.join(r,d);Gs.writeFileSync(p,JSON.stringify(c,null,2)),Gs.writeFileSync(m,JSON.stringify(l,null,2)),o.attachments.push({name:"API request details",source:u,type:"application/json"}),o.attachments.push({name:"API response details",source:d,type:"application/json"})}else{let s=$m.union([$m.object({}).passthrough(),$m.array($m.any())]).safeParse(n.data).success,c=`output-attachment-${ma()}.json`,l=qn.join(r,c);Gs.writeFileSync(l,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:c,type:s?"application/json":"text/plain"})}return o}async function fE(t,e,r,n,o){for(let i of o){let a;switch(i.type){case"PRESET_ACTION":{a=await Wm(t,e,r,i);break}case"CONDITIONAL":{a=await Wm(t,e,r,i),a.steps=[],i.assertionResult&&a.steps.push(await Wm(t,e,r,i.assertionResult)),await fE(t,e,r,a.steps,i.results);break}case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"SECTION":case"MODULE":{if(a=await Wm(t,e,r,i),await fE(t,e,r,a.steps,i.results),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[s,c]of Object.entries(i.inputs))a.parameters.push({name:s,value:c})}break}default:{let s=i}}if(!a){t.warn({result:i},"Failed to convert Momentic result to Allure step");continue}if(a.attachments||(a.attachments=[]),i.beforeTestContext){let s=`before-context-${ma()}.json`,c=qn.join(r,s);sN(c,lN(i.beforeTestContext.env)),a.attachments.push({name:"Test context before step",source:s,type:"application/json"})}if(i.afterTestContext){let s=`after-context-${ma()}.json`,c=qn.join(r,s);sN(c,lN(i.afterTestContext.env)),a.attachments.push({name:"Test context after step",source:s,type:"application/json"})}n.push(a)}}async function cN(t,e,r,n){for(let o of n.runs){if(!o.runId||!o.runAttemptId)throw new Error(`Missing runId/runAttemptId for Allure report generation for test '${o.test.name}'`);let i=e.createDebugDataReaderForRunAttempt(o.runId,o.runAttemptId);try{await TY(t,i,{folder:r,suiteName:n.suiteName},o)}finally{i.close()}}}function lN(t){try{return JSON.stringify(t,void 0,2)??JSON.stringify({value:null},void 0,2)}catch(e){let r=e instanceof Error?e.message:"unknown error";return JSON.stringify({error:r},void 0,2)}}function vY(t,e,r){let n=t.listVideoAssetPaths();if(n.length===0)return[];let o=[];for(let i of n){let a=qn.basename(i),s=a,c=qn.join(e,s);try{Gs.copyFileSync(i,c)}catch{continue}let l,u=qn.extname(i).toLowerCase();u===".webm"?l="video/webm":u===".mp4"?l="video/mp4":l="application/octet-stream",o.push({name:a,source:s,type:l})}return o}import RY from"junit-report-builder";import Km from"path";function AY(t,e){if(e.name(t.test.name).className(t.test.name).file(Km.relative(".",t.filePath)).property("id",t.test.id).property("dd_tags[id]",t.test.id),t.test.labels&&(e.property("labels",t.test.labels.join(",")),t.test.labels.forEach(r=>{e.property("dd_tags[label]",r)})),t.baseUrl&&(e.property("base_url",t.baseUrl),e.property("dd_tags[base_url]",t.baseUrl)),t.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${t.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${t.runId}`)),t.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),t.quarantinedReason&&(e.property("quarantined_reason",t.quarantinedReason),e.property("dd_tags[quarantined_reason]",t.quarantinedReason))),t.beforeResults?.some(r=>r.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),t.results?.some(r=>r.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),t.afterResults?.some(r=>r.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),t.status==="FAILED"){if(t.failureReason){let r=Su[t.failureDetails?.classification?.reason||t.failureReason],n=t.failureDetails?.classification?.summary||Pa[t.failureReason];t.runId&&(n+=` Visit https://app.momentic.ai/runs/${t.runId} for more details.`),e.failure(n,r)}t.failureDetails?.errorStack&&e.stacktrace(t.failureDetails.errorStack)}else t.status==="CANCELLED"&&e.skipped();return e.time((t.finishedAt.getTime()-t.lastAttemptStartedAt.getTime())/1e3).property("started_at",t.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",t.lastAttemptStartedAt.toISOString()).property("finished_at",t.finishedAt.toISOString()).property("dd_tags[finished_at]",t.finishedAt.toISOString()),e.property("attempts",t.attempts.toString()).property("dd_tags[attempts]",t.attempts.toString()),t.parameters.envName&&(e.property("environment",t.parameters.envName),e.property("dd_tags[environment]",t.parameters.envName)),t.parameters.urlOverride&&e.property("url_override",t.parameters.urlOverride),e}function wY(t,{suiteId:e,suiteName:r,startedAt:n,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:s,quarantinedTestReasons:c}){let l=t.testSuite().name(r);e&&l.property("id",e),l.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let u of i){let d=l.testCase();AY(u,d)}for(let u of a){let d=l.testCase();d.name(u.name).className(u.name).file(Km.relative(".",u.relativeFilePath)).property("id",u.id),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(p=>{d.property("dd_tags[label]",p)})),d.skipped()}for(let u of s){let d=l.testCase();d.name(u.name).className(u.name).file(Km.relative(".",u.relativeFilePath)).property("id",u.id).property("quarantined","true");let p=c[u.id];p&&d.property("quarantinedReason",p),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(m=>{d.property("dd_tags[label]",m)})),d.skipped()}return l}function uN(t,e){let r=RY.newBuilder();wY(r,e),r.writeTo(Km.join(t,`${e.suiteName}.xml`))}import CY from"fs";import xY from"path";function dN(t){return{title:lo(t),duration:t.finishedAt.getTime()-t.startedAt.getTime(),error:t.status==="FAILED"?{value:t.failureReason}:void 0,steps:t.results&&t.type!=="PRESET_ACTION"?t.results.map(dN):[]}}async function _Y(t,e,r,n){if(n.results?.length){let o=await qm(t,e,r,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function MY(t,e,r,n){return{status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:n.status==="FAILED"&&n.failureReason?{value:n.failureDetails?.classification?.reason||n.failureReason,message:n.failureDetails?.classification?.summary||Pa[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(dN)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await _Y(t,e,r,n)}}async function PY(t,e,r,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await MY(t,e,r,n)]}}async function IY(t,e,r,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await PY(t,e,r,n)],id:n.runId,file:n.filePath}}function SE(t,e){return t.reduce((r,n)=>e(n)?r+1:r,0)}async function OY(t,e,r,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(async o=>{let i=o.runId&&o.runAttemptId?e.createDebugDataReaderForRunAttempt(o.runId,o.runAttemptId):new Il;try{return await IY(t,i,r,o)}finally{i.close()}}))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:SE(n.runs,o=>o.status==="PASSED"),unexpected:SE(n.runs,o=>o.status!=="PASSED"),flaky:SE(n.runs,o=>!!o.isFlake),skipped:0}}}async function pN(t,e,r,n){let o=await OY(t,e,r,n);CY.writeFileSync(xY.join(r,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function mN({logger:t,callbacks:e,format:r,params:n,folder:o}){switch(LY(o)?DY(o).isDirectory()||(b.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(b.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),NY(o,{recursive:!0})),r){case"junit":uN(o,n);return;case"allure":case"allure-json":await cN(t,e,o,n);return;case"playwright-json":await pN(t,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${r}'`)}}import a5 from"wait-on";import{execSync as kY}from"child_process";import{platform as FY}from"os";function yE(){return hN()?(b.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),b.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
4841
+ `)}`),Object.values(e.tests).forEach(p=>{t.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Bt("No test paths or substrings were provided. Do you want to run all tests?")&&(s.error("Cancelled by user."),process.exit(1));let u=Object.values(e.tests);s.info(`Reading all ${u.length} tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of c){let d=gE.relative(r.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}let l=Array.from(c).map(async u=>{try{let d=await pt(u,X,e);if(EY.gt(d.schemaVersion,_e)&&s.warn(`Test ${u} has schema version ${d.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),a&&a.length>0){let p=d.labels||[];if(!a.some(g=>p.includes(g)))return null}return{...d,fullFilePath:u,relativeFilePath:gE.relative(r.rootDir,u)}}catch(d){s.error(`Failed to read and resolve test at '${u}': ${d}`),process.exit(1)}});return Promise.all(l).then(SY)}function eN({testDefinitions:t,quarantinedTestReasons:e,onlyQuarantined:r=!1,skipQuarantined:n=!1}){if(r){let[u,d]=Vm(t,g=>g.id in e),[p,m]=Vm(u,g=>g.disabled||n);return{testsToSkip:p,quarantinedTestsToSkip:[],testsToRun:m,quarantinedTestsToRun:[]}}let[o,i]=Vm(t,u=>u.disabled),[a,s]=Vm(i,u=>u.id in e);return{testsToSkip:o,testsToRun:s,quarantinedTestsToRun:n?[]:a,quarantinedTestsToSkip:n?a:[]}}function tN({testsToRun:t,quarantinedTestsToRun:e,quarantinedTestReasons:r,testInputMatrix:n}){let o=[],i=(a,s,c)=>{n?n.forEach((l,u)=>{o.push({inputs:l,inputIndex:u,testDefinition:a,quarantined:s,quarantinedReason:c})}):o.push({inputs:void 0,testDefinition:a,quarantined:s,quarantinedReason:c})};return t.forEach(a=>i(a,!1)),e.forEach(a=>i(a,!0,r[a.id])),o}async function rN({project:t,apiClient:e}){let r=await te(t),n=await Hs({tests:[],momenticFiles:r,yes:!0,project:t,logger:new Li(40,{})}),o=(await e.getQuarantinedTests()).quarantined,i=new Set(o.map(s=>s.testId)),a=n.filter(s=>i.has(s.id));b.info(a.map(s=>s.relativeFilePath).join(`
4842
+ `))}async function nN({test:t,reason:e,apiClient:r,project:n,identity:o}){let i=(await te(n)).tests,a=Object.values(i),s=(await r.getQuarantinedTests()).quarantined,c=new Set(s.map(p=>p.testId)),l=a.filter(p=>c.has(p.id)),u=await Gm({prompt:"Select a test to unquarantine.",inputtedTest:t,testOptions:l}),d=await jm({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await r.unquarantineTest(u,d,o),b.success(`Test ${u.name} has been successfully removed from quarantine.`)}function oN(t){return t?ze(t):"Unknown suite"}async function iN({client:t,orgId:e,suitePaths:r,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:s}=await t.queueSuiteRuns({paths:r,...i});X.info({orgId:e,suiteRunIds:a,runGroupIds:s,suitePaths:r},"Queued suites remotely"),b.dimmed(`Queued ${r.length} suites.`),n||process.exit(0);let c=Date.now();b.dimmed(`Waiting for ${r.length} suites to finish. You can view results upon completion at:`);for(let f of s)b.dimmed(`${dt}- ${t.getAppUrl()}/run-groups/${f}`);let l=new Set,u=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(y=>y.status==="FAILED"&&(y.failureReason||y.finishedAt&&Date.now()-y.finishedAt.getTime()>30*1e3)||y.status==="PASSED"||y.status==="CANCELLED"),p=await dd({name:"suites",getResults:async()=>{let f=s.filter(E=>!u.some(T=>T.id===E)),S=await t.bulkGetRunGroupStatus(f),y=[];for(let E of S)d(E)?u.push(E):y.push(E);return[...u,...y]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(l.has(S.id)||(l.add(S.id),b.log(`${l.size}/${s.length} ${oN(S.suite?.name)}`)))}),f.every(d))}),m=t.getAppUrl(),h=Ja({results:p,startTime:c,onFailed:f=>{let S=oN(f.suite?.name),y=f.runs.filter(T=>T.status==="FAILED").length,E=f.runs.length;b.error(`${S} (${y}/${E} tests failed):`);for(let T of f.runs)if(T.status==="FAILED"){let v=T.testName||T.test?.name;b.error(` ${v?ze(v):"Unknown test"} (${m}/runs/${T.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?ze(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function aN({tests:t,client:e,orgId:r,...n}){!n.yes&&!await Bt(`This command will queue ${t.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:t,...n});if(X.info({queuedTests:o,runIds:i,orgId:r},"Queued tests remotely"),b.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),n.wait||process.exit(0),!i.length)return;b.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,s=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",l=e.getAppUrl(),u=Date.now(),d=await dd({name:"runs",getResults:async()=>{let m=i.filter(f=>!s.some(S=>S.id===f)),g=await e.bulkGetRunStatus(m),h=[];for(let f of g)c(f)?s.push(f):h.push(f);return[...s,...h]},timeoutMs:n.waitTimeout?n.waitTimeout*1e3:void 0,checkDone:m=>(m.forEach(g=>{if(g.status==="RUNNING"&&!a.has(g.id)){a.add(g.id);let h=g.testName||g.test?.name;h&&b.log(`${a.size}/${o.length} ${ze(h)}`)}}),m.every(c))}),p=Ja({results:d,startTime:u,onFailed:m=>{let g=m.testName||m.test?.name;pd(m,g?ze(g):"Unknown test")},getDisplayLine:m=>{let g=m.testName||m.test?.name,h=` ${g?ze(g):"Unknown test"}`;return m.id&&(h+=` (${l}/runs/${m.id})`),h},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as o5}from"crypto";import i5 from"fs";import{existsSync as LY,mkdirSync as NY,statSync as DY}from"fs";import{randomUUID as ma}from"crypto";import Gs,{writeFileSync as sN}from"fs";import{hostname as bY}from"os";import qn from"path";import{z as $m}from"zod";async function qm(t,e,r,n){if(n){let o=await e.getScreenshot(t,n);if(o){let i=`screenshot-${n}.jpeg`,a=qn.join(r,i);return Gs.writeFileSync(a,o),i}}}async function TY(t,e,r,n){let o=r.folder,i={uuid:n.runAttemptId??ma(),historyId:n.runId??ma(),testCaseId:n.test.id,fullName:n.test.name,name:ze(n.test.name),status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"skipped":"failed",start:n.lastAttemptStartedAt.getTime(),stop:n.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:r.suiteName},{name:"host",value:bY()},{name:"platform",value:"momentic"},{name:"attempts",value:n.attempts.toString()}],steps:[]};n.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${n.runId}`});for(let[c,l]of Object.entries(n.parameters))l!=null&&i.parameters.push({name:c,value:JSON.stringify(l)});n.results&&await fE(t,e,r.folder,i.steps,n.results);let a=vY(e,o,i.uuid);a.length>0&&(i.attachments=a);let s=`${n.runAttemptId}-result.json`;Gs.writeFileSync(qn.join(o,s),JSON.stringify(i,void 0,2))}async function Wm(t,e,r,n){let o={name:fw(n),start:n.startedAt.getTime(),stop:n.finishedAt.getTime(),status:n.status==="SUCCESS"?"passed":n.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};n.beforeUrl&&o.labels?.push({name:"URL before step",value:n.beforeUrl}),n.afterUrl&&o.labels?.push({name:"URL after step",value:n.afterUrl});let i=await qm(t,e,r,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await qm(t,e,r,n.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),n.message&&(o.statusDetails={message:n.message}),n.data)if(al.safeParse(n.data).success){let s=al.parse(n.data),c=s.request,l={...s,request:void 0},u=`output-attachment-api-request-${ma()}.json`,d=`output-attachment-api-response-${ma()}.json`,p=qn.join(r,u),m=qn.join(r,d);Gs.writeFileSync(p,JSON.stringify(c,null,2)),Gs.writeFileSync(m,JSON.stringify(l,null,2)),o.attachments.push({name:"API request details",source:u,type:"application/json"}),o.attachments.push({name:"API response details",source:d,type:"application/json"})}else{let s=$m.union([$m.object({}).passthrough(),$m.array($m.any())]).safeParse(n.data).success,c=`output-attachment-${ma()}.json`,l=qn.join(r,c);Gs.writeFileSync(l,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:c,type:s?"application/json":"text/plain"})}return o}async function fE(t,e,r,n,o){for(let i of o){let a;switch(i.type){case"PRESET_ACTION":{a=await Wm(t,e,r,i);break}case"CONDITIONAL":{a=await Wm(t,e,r,i),a.steps=[],i.assertionResult&&a.steps.push(await Wm(t,e,r,i.assertionResult)),await fE(t,e,r,a.steps,i.results);break}case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"SECTION":case"MODULE":{if(a=await Wm(t,e,r,i),await fE(t,e,r,a.steps,i.results),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[s,c]of Object.entries(i.inputs))a.parameters.push({name:s,value:c})}break}default:{let s=i}}if(!a){t.warn({result:i},"Failed to convert Momentic result to Allure step");continue}if(a.attachments||(a.attachments=[]),i.beforeTestContext){let s=`before-context-${ma()}.json`,c=qn.join(r,s);sN(c,lN(i.beforeTestContext.env)),a.attachments.push({name:"Test context before step",source:s,type:"application/json"})}if(i.afterTestContext){let s=`after-context-${ma()}.json`,c=qn.join(r,s);sN(c,lN(i.afterTestContext.env)),a.attachments.push({name:"Test context after step",source:s,type:"application/json"})}n.push(a)}}async function cN(t,e,r,n){for(let o of n.runs){if(!o.runId||!o.runAttemptId)throw new Error(`Missing runId/runAttemptId for Allure report generation for test '${o.test.name}'`);let i=e.createDebugDataReaderForRunAttempt(o.runId,o.runAttemptId);try{await TY(t,i,{folder:r,suiteName:n.suiteName},o)}finally{i.close()}}}function lN(t){try{return JSON.stringify(t,void 0,2)??JSON.stringify({value:null},void 0,2)}catch(e){let r=e instanceof Error?e.message:"unknown error";return JSON.stringify({error:r},void 0,2)}}function vY(t,e,r){let n=t.listVideoAssetPaths();if(n.length===0)return[];let o=[];for(let i of n){let a=qn.basename(i),s=a,c=qn.join(e,s);try{Gs.copyFileSync(i,c)}catch{continue}let l,u=qn.extname(i).toLowerCase();u===".webm"?l="video/webm":u===".mp4"?l="video/mp4":l="application/octet-stream",o.push({name:a,source:s,type:l})}return o}import RY from"junit-report-builder";import Km from"path";function AY(t,e){if(e.name(t.test.name).className(t.test.name).file(Km.relative(".",t.filePath)).property("id",t.test.id).property("dd_tags[id]",t.test.id),t.test.labels&&(e.property("labels",t.test.labels.join(",")),t.test.labels.forEach(r=>{e.property("dd_tags[label]",r)})),t.baseUrl&&(e.property("base_url",t.baseUrl),e.property("dd_tags[base_url]",t.baseUrl)),t.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${t.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${t.runId}`)),t.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),t.quarantinedReason&&(e.property("quarantined_reason",t.quarantinedReason),e.property("dd_tags[quarantined_reason]",t.quarantinedReason))),t.beforeResults?.some(r=>r.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),t.results?.some(r=>r.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),t.afterResults?.some(r=>r.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),t.status==="FAILED"){if(t.failureReason){let r=Su[t.failureDetails?.classification?.reason||t.failureReason],n=t.failureDetails?.classification?.summary||Pa[t.failureReason];t.runId&&(n+=` Visit https://app.momentic.ai/runs/${t.runId} for more details.`),e.failure(n,r)}t.failureDetails?.errorStack&&e.stacktrace(t.failureDetails.errorStack)}else t.status==="CANCELLED"&&e.skipped();return e.time((t.finishedAt.getTime()-t.lastAttemptStartedAt.getTime())/1e3).property("started_at",t.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",t.lastAttemptStartedAt.toISOString()).property("finished_at",t.finishedAt.toISOString()).property("dd_tags[finished_at]",t.finishedAt.toISOString()),e.property("attempts",t.attempts.toString()).property("dd_tags[attempts]",t.attempts.toString()),t.parameters.envName&&(e.property("environment",t.parameters.envName),e.property("dd_tags[environment]",t.parameters.envName)),t.parameters.urlOverride&&e.property("url_override",t.parameters.urlOverride),e}function wY(t,{suiteId:e,suiteName:r,startedAt:n,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:s,quarantinedTestReasons:c}){let l=t.testSuite().name(r);e&&l.property("id",e),l.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let u of i){let d=l.testCase();AY(u,d)}for(let u of a){let d=l.testCase();d.name(u.name).className(u.name).file(Km.relative(".",u.relativeFilePath)).property("id",u.id),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(p=>{d.property("dd_tags[label]",p)})),d.skipped()}for(let u of s){let d=l.testCase();d.name(u.name).className(u.name).file(Km.relative(".",u.relativeFilePath)).property("id",u.id).property("quarantined","true");let p=c[u.id];p&&d.property("quarantinedReason",p),u.baseUrl&&d.property("baseUrl",u.baseUrl),u.labels&&(d.property("labels",u.labels.join(",")),u.labels.forEach(m=>{d.property("dd_tags[label]",m)})),d.skipped()}return l}function uN(t,e){let r=RY.newBuilder();wY(r,e),r.writeTo(Km.join(t,`${e.suiteName}.xml`))}import CY from"fs";import xY from"path";function dN(t){return{title:lo(t),duration:t.finishedAt.getTime()-t.startedAt.getTime(),error:t.status==="FAILED"?{value:t.failureReason}:void 0,steps:t.results&&t.type!=="PRESET_ACTION"?t.results.map(dN):[]}}async function _Y(t,e,r,n){if(n.results?.length){let o=await qm(t,e,r,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function MY(t,e,r,n){return{status:n.status==="PASSED"?"passed":n.status==="CANCELLED"?"interrupted":"failed",duration:n.finishedAt.getTime()-n.lastAttemptStartedAt.getTime(),error:n.status==="FAILED"&&n.failureReason?{value:n.failureDetails?.classification?.reason||n.failureReason,message:n.failureDetails?.classification?.summary||Pa[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(dN)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await _Y(t,e,r,n)}}async function PY(t,e,r,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await MY(t,e,r,n)]}}async function IY(t,e,r,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await PY(t,e,r,n)],id:n.runId,file:n.filePath}}function SE(t,e){return t.reduce((r,n)=>e(n)?r+1:r,0)}async function OY(t,e,r,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(async o=>{let i=o.runId&&o.runAttemptId?e.createDebugDataReaderForRunAttempt(o.runId,o.runAttemptId):new Il;try{return await IY(t,i,r,o)}finally{i.close()}}))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:SE(n.runs,o=>o.status==="PASSED"),unexpected:SE(n.runs,o=>o.status!=="PASSED"),flaky:SE(n.runs,o=>!!o.isFlake),skipped:0}}}async function pN(t,e,r,n){let o=await OY(t,e,r,n);CY.writeFileSync(xY.join(r,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function mN({logger:t,callbacks:e,format:r,params:n,folder:o}){switch(LY(o)?DY(o).isDirectory()||(b.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(b.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),NY(o,{recursive:!0})),r){case"junit":uN(o,n);return;case"allure":case"allure-json":await cN(t,e,o,n);return;case"playwright-json":await pN(t,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${r}'`)}}import a5 from"wait-on";import{execSync as kY}from"child_process";import{platform as FY}from"os";function yE(){return hN()?(b.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),b.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
4843
4843
  `),2):(b.dimmed("Setting device pixel ratio to 1."),b.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
4844
- `),1)}function hN(){return FY()==="darwin"&&kY("system_profiler SPDisplaysDataType").toString().includes("Retina")}function EE(t){hN()&&t===1&&(b.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),b.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import UY from"@actions/exec";import BY from"@actions/io";import zY from"quote";import HY from"string-argv";async function gN(t,e=!0){let r=HY(t),n=await BY.which(r[0],!0),o=r.slice(1),i=UY.exec(zY(n),o,{delay:100});if(e)return i}import GY from"csv-parser";import{createReadStream as jY}from"fs";function bE(t){return new Promise((e,r)=>{let n=[];jY(t).pipe(GY()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>r(o))})}import js from"semver";import{z as Ym}from"zod";var Nr="2.29.4",VY="https://registry.npmjs.org/momentic",$Y=Ym.object({versions:Ym.record(Ym.string(),Ym.unknown()).optional()});async function tr(t){try{await WY(t)}catch(e){b.warn({err:e},"Failed to check CLI version against NPM servers")}}async function TE(){let t=await $(fetch(VY),{milliseconds:5e3});if(!t.ok)throw new Error(`Got error status code ${t.statusText}`);let e=await t.json(),r=$Y.parse(e).versions;if(!r)throw new Error("Failed to fetch npm registry data. Skipping version check.");let n=Nr;for(let o of Object.keys(r))js.valid(o)&&js.major(o)===js.major(Nr)&&js.gt(o,n)&&js.prerelease(o)===null&&(n=o);return n}async function WY(t){let e;for(let r=0;r<2;r++)try{e=await TE()}catch(n){t.warn({err:n},"Failed to fetch latest version from npm registry")}if(!e){t.warn("Failed to fetch npm registry data. Skipping version check.");return}js.eq(Nr,e)||(b.warn(`Update available: v${Nr} -> v${e}`),b.warn("This version may be missing critical fixes, features, and security updates."),b.warn('Run "npx momentic@latest upgrade" to update'))}async function Eo(){try{await $(Promise.all([TA(),kt.flush()]),{milliseconds:5e3})}catch{}}import{partition as qY}from"lodash-es";function Xm(t){return t.length===1?"test":"tests"}function fN(t){return t===1?"1 worker":`${t} workers`}function SN(t){t.length!==0&&(b.info(`Skipping ${t.length} disabled ${Xm(t)}:`),t.forEach(e=>{b.info(`${dt}- ${[e.relativeFilePath]}`)}),b.log(""))}function yN(t,e){t.length!==0&&(b.info(`Skipping ${t.length} quarantined ${Xm(t)}:`),t.forEach(r=>{b.info(`${dt}- ${[r.relativeFilePath]}: ${e[r.id]}`)}),b.log(""))}function KY(t,e){t.length!==0&&(b.info(`Running ${t.length} quarantined ${Xm(t)} with ${fN(e)}:`),t.forEach(r=>{b.info(`${dt}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),b.log(""))}function YY(t,e,r){e.length===0&&t.length>0||(b.info(`Running ${e.length} ${Xm(e)} with ${fN(r)}:`),e.forEach(n=>{b.info(`${dt}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),b.log(""))}function EN({logger:t,localTestsToRunWithInputs:e,parallel:r,shardCount:n,shardIndex:o}){t.info({tests:e.length,shardCount:n,shardIndex:o,parallel:r},"Running local tests");let[i,a]=qY(e,s=>s.quarantined);KY(i,r),YY(i,a,r)}import{randomUUID as XY}from"crypto";import{cloneDeep as Vs}from"lodash-es";async function bN({orgId:t,codeEvalTools:e,logger:r,outputDefinitions:n,testContext:o}){let i={};for(let a of n){let{name:s,value:c}=a;i[s]=await pr({orgId:t,s:c,localTools:e,logger:r,context:o})}return i}async function TN({baseUrl:t,envName:e,testName:r,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:s,generator:c,orgId:l,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f,tracer:S}){let y=await mm({settings:g,customHeaders:p,envVariables:u,envName:e,testName:r,baseUrl:t,logger:d,localTools:s,orgId:l}),E={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:X,mode:"runner"},T=xu({browserType:y.browserType,orgDefaultBrowserType:g.defaultBrowserType});if(!wA(T)){let _=`Browser ${T} is required by the test named ${i.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;b.warn(_),X.warn(_)}let v=await qr.init({baseUrl:t,logger:d,userBrowserSettings:y,storage:a,enricher:new Ho(E,c),contextArgs:{viewport:i.advanced.viewport??Kt,locale:i.advanced.locale??Io,geolocation:i.advanced.geolocation??Lo,timezoneId:i.advanced.timezone??Oo,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},callbacks:{onNetworkPage:_=>S.onNetworkPage(_),onNetworkLogs:_=>S.onNetworkLogs(_)},iconKnowledgeBase:null,videoOptions:S.videoOutputPath?{videoOutputPath:S.videoOutputPath,onVideoPageChange:({videoName:_})=>{S.setActiveVideo(_)}}:void 0}),w=new oi({browser:v,generator:c,logger:d,orgId:l,options:{scratchPadId:void 0,slowMoMs:y.slowMoMs,autoFollowNewTabs:y.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering},storage:a,localCodeEvalTools:s,visualDiffScreenshotStorage:f}),C=new lr({baseUrl:t,currentUrl:w.browser.url(),variablesFromEnvironment:u,envName:e,testName:r});return i.parameters&&await Promise.all(i.parameters.map(async _=>{let{name:N,defaultValue:U,required:j}=_,O=m?.[N];j&&O===void 0&&(b.error(`Required parameter '${N}' is required by test '${i.name}' but not provided`),process.exit(1));let B=await pr({orgId:l,s:O??U,localTools:s,logger:d,context:lr.dummyContext(C.getEnvName())});C.setMomenticSystemVariable(N,B)})),{controller:w,context:C}}async function vN({testAdvancedSettings:t,orgSettings:e,logger:r}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Ni){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return r.warn(n),b.warn(n),!1}return!0}async function RN({attemptInputs:t,attemptFixtures:e,attemptMetadata:r}){let{orgId:n,runId:o}=r,{controller:i,context:a,codeEvalTools:s,storageClient:c,logger:l,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=t;l.info(`Running test '${p.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let g={controller:i,storage:c,usageTracker:u,context:a,logger:l,codeEvalTools:s},h={orgId:n,runId:o,testMetadata:p,steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps,orgSettings:m},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await vN({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:l})};return await pm({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function AN(t){let{testDefinition:e,logger:r}=t,n=new Date;try{return await JY(t)}catch(o){let i="Fatal error running test";return b.error(`${i}: ${o.message}`),r.error({err:o},i),{results:[],parameters:t,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:n,lastAttemptStartedAt:n,finishedAt:new Date,outputs:{}}}}async function JY(t){let{testDefinition:e,project:r,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:s,logger:c,gitMetadata:l,cacheOptions:u,runId:d,testInputs:p,quarantined:m,quarantinedReason:g,usageTracker:h}=t,f=new Qa(n,o),S=Go({orgId:o,client:n,gitMetadata:l,regenerateCache:u.regenerateCache??!1,alwaysSaveCache:u.alwaysSaveCache??!1,noCache:u.noCache??!1,bustOldestCachePercentage:u.bustOldestCachePercentage}),y=await Rd({cacheStorage:S,logger:c,schemaVersion:e.schemaVersion,stepLists:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},testId:e.id}),E=y.steps,T=y.beforeSteps??void 0,v=y.afterSteps??void 0,w=t.envName??ZY(e),C,_={};if(w){try{C=Gi(w,r,c)}catch(O){let B=`Failed to resolve environment ${w} for test ${e.name}: ${O}`;throw new Error(B)}_=C.variables}let N=e.baseUrl;if(i)N=i;else if(!N){let O=_[Rt];typeof O=="string"&&(N=O)}if(!N){let O=`Cannot run test with no base URL and no ${Rt} variable defined in its environment`;throw new Error(O)}let U=await s.startRun({logger:c,runId:d,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:N,environmentName:w,schemaVersion:e.schemaVersion,resolvedInputs:p,quarantined:m,quarantinedReason:g}),j=c.child(U.loggerBindings||{});Object.entries(U.envVarBindings||{}).forEach(([O,B])=>{_[O]=B});try{let O=await QY({...t,variables:_,envName:w,resolvedEnv:C,baseUrl:N,storageClient:f,tracer:U,logger:j,cacheStorage:S,stepsWithCaches:E,beforeStepsWithCaches:T,afterStepsWithCaches:v,usageTracker:h});return await U.finish({logger:c,status:O.status,finishedAt:O.finishedAt,failureDetails:O.failureDetails,failureReason:O.failureReason,isFlake:O.isFlake,failureRecoveryDetails:O.failureRecoveryDetails}),{runId:U.runId,...O}}finally{a?.pop()}}async function QY(t){let{testDefinition:e,stepsWithCaches:r,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:s,generator:c,baseUrl:l,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:g,testInputs:h,variables:f,resolvedEnv:S,retriesOverride:y,devicePixelRatio:E,logUpdate:T,tracer:v,logger:w,cacheStorage:C,gitMetadata:_,quarantined:N,quarantinedReason:U,usageTracker:j}=t,O=i.config.ai?.aiFailureAnalysis??!1,B=new Date,W=new ps(i,a),q={...i.config},ve={envName:p,urlOverride:m,customHeaders:g,testInputs:h},Y,st=Math.abs(y??i.config.retries??e.retries??0),Le=[];w.info({..._,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let gt=0;gt<=st;gt++){let rr=XY(),Ge=await v.startAttempt(rr),se=w.child(Ge.loggerBindings||{}),qe={...e,steps:Vs(r),beforeSteps:Vs(n),afterSteps:Vs(o)};gt!==0&&T("RETRY",`attempt ${gt+1}/${st+1}`);let tn=new Date,ga=q.advanced?.fakerConstantSeed,$s=new On({httpClient:new zt({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:se,mode:"runner"}),fakerSeed:ga?qa:void 0}),Zm=Ge;try{let{controller:nr,context:rn}=await TN({tracer:Ge,baseUrl:l,envName:p,testName:qe.name,apiClient:s,devicePixelRatio:E,logger:se,storageClient:u,codeEvalTools:$s,test:qe,generator:c,orgId:d,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...i.config.browser||{},...S?.browser||{},...qe.advanced},aiSettings:{...i.config.ai||{},...qe.advanced||{}},visualDiffScreenshotStorage:W});Y=await RN({attemptMetadata:{attemptNumber:gt+1,orgId:d,runId:v.runId},attemptFixtures:{logger:se,storageClient:u,usageTracker:j,codeEvalTools:$s,apiClient:s,context:rn,controller:nr,tracer:Ge},attemptInputs:{test:qe,orgSettings:q}});let pi=new Date,En={logger:w,cacheStorage:C,orgId:d,testId:e.id,originalStepsWithCaches:{steps:Vs(r),beforeSteps:Vs(n),afterSteps:Vs(o)},updatedStepsWithCaches:{steps:qe.steps,beforeSteps:qe.beforeSteps,afterSteps:qe.afterSteps}};Y?.status==="PASSED"?await Md(En):Y?.status==="FAILED"&&gt===st&&await Pd(En),await Ge.finish({logger:se,result:Y}),Le.unshift(Y.status);let J=await bN({orgId:d,codeEvalTools:$s,logger:se,outputDefinitions:e.outputs??[],testContext:rn}),bo=LT(Le),fa=gt+1;if(Y.status!=="FAILED")return{...Y,runAttemptId:rr,parameters:ve,test:qe,filePath:qe.relativeFilePath,startedAt:B,lastAttemptStartedAt:tn,finishedAt:pi,attempts:fa,baseUrl:l,outputs:J,isFlake:bo,quarantined:N,quarantinedReason:U};let Ws=Y.failedStepResult,Kn=Ws?.message||"Unknown failure",Yn=Ws?.failureReason??Bb(Kn)??"UnknownError",qs=se.child({failureReason:Yn,errorMessage:Kn,numAttempts:(st+1).toString(),name:qe.name});if(gt<st){qs.warn(`Retrying failed execution attempt for run: ${Kn}`);continue}qs.error(`Test failed after all exhausting attempts: ${Kn}`);let Sa=new Error(Kn),To={errorMessage:Kn,errorStack:Sa.stack},eh;if(O){let Ks;try{if(Y.results&&Y.results.length>0){let{classification:De,aiFailureReason:Tr}=await Fw({logger:se,browserStateStorage:Zm,generator:c,fullResults:Y,failureReason:Yn,error:Sa,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Ks=De,eh=Tr}}catch(De){se.warn({err:De},"Failed to classify test results")}Ks&&(To.classification=Ks,Yn=eh??Yn)}return{...Y,runAttemptId:rr,parameters:ve,failureDetails:To,failureReason:Yn,test:qe,filePath:qe.relativeFilePath,startedAt:B,lastAttemptStartedAt:tn,finishedAt:pi,attempts:gt+1,baseUrl:l,outputs:J,quarantined:N,quarantinedReason:U}}catch(nr){Xs(nr);let rn=`Encountered fatal platform error while running test '${qe.name}': ${nr}`,pi=new Date,En=gt+1;se.error({err:nr},rn),b.error(rn);let J={errorMessage:nr.message,errStack:nr.stack},bo={status:"FAILED",failureDetails:J,failureReason:"InternalPlatformError",finishedAt:pi};return await Ge.finish({logger:se,result:{status:"FAILED",results:[]}}),{...bo,runAttemptId:rr,results:[],parameters:ve,test:qe,filePath:qe.relativeFilePath,startedAt:B,lastAttemptStartedAt:tn,finishedAt:new Date,attempts:En,baseUrl:l,outputs:{},quarantined:N,quarantinedReason:U}}}throw new Error("This code should not be reachable")}function ZY(t){for(let e of t.envs??[])if(e.default)return e.name}import r5 from"adm-zip";import n5 from"path";function e5(t){switch(t){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}var ha=class{constructor(e,r,n,o){this.orgId=e;this.testId=r;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,r){return this.diskStorage.readFile(`${ur}/${r}.jpeg`)}async getHtmlSnapshot(e,r){return this.diskStorage.readFile(`${ur}/${r}.html`)?.toString()}getParentStepIdChain(){return[]}recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,r]of Object.entries(this.stepFrequenciesByType))kt.increment("test_step_execution",r,[`type:${e}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async startStep(e){let{step:r}=e;this.recordStepStat(r);let n={step:r,status:"RUNNING",startedAt:new Date},o=new vE(this.orgId,this.testId,this.testName,n,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(r=>r.finishInternal({status:e5(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}};function t5(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var vE=class{constructor(e,r,n,o,i){this.orgId=e;this.testId=r;this.testName=n;this.metadata=o;this.diskStorage=i}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:r,screenshot:n}=e;this.metadata.beforeSnapshotId=r,this.diskStorage.storeFile({name:`${ur}/${r}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:r,screenshot:n}=e;this.metadata.afterSnapshotId=r,this.diskStorage.storeFile({name:`${ur}/${r}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:r,html:n}=e;this.metadata.beforeSnapshotId=r,this.diskStorage.storeFile({name:`${ur}/${r}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:r,html:n}=e;this.metadata.afterSnapshotId=r,this.diskStorage.storeFile({name:`${ur}/${r}.html`,contents:n})}recordTargetAutoHeal(e){let{healType:r}=e,n=r==="AI"?"ai-target-heal":"cache-heal";kt.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:r,healedAt:new Date}}recordStepDuration(e){let r=e.step.type!=="PRESET_ACTION"?e.step.type:e.step.command.type;kt.distribution("test_step_duration",e.durationMs,[`type:${r}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(r=>r.finish({status:t5(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new ha(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}};var Xc=class{constructor(e,r,n,o,i,a,s){this.orgId=e;this.testId=r;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.recordVideo=s;this.diskStorage.mkdir(ur),this.harPagesStream=this.diskStorage.createFileStream(`${ur}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${ur}/har-entries.log`)}finished=!1;children=[];harPagesStream;inProgressHarEntries;harEntriesStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}get videoOutputPath(){if(this.recordVideo)return n5.resolve(this.diskStorage.cwd(),ur)}setActiveVideo(e){this.recordVideo&&(this.metadata.activeVideos=this.metadata.activeVideos||[],this.metadata.activeVideos.push({videoName:e,timestamp:new Date}))}onNetworkPage(e){this.finished||this.harPagesStream.write(`${JSON.stringify(e)}
4844
+ `),1)}function hN(){return FY()==="darwin"&&kY("system_profiler SPDisplaysDataType").toString().includes("Retina")}function EE(t){hN()&&t===1&&(b.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),b.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import UY from"@actions/exec";import BY from"@actions/io";import zY from"quote";import HY from"string-argv";async function gN(t,e=!0){let r=HY(t),n=await BY.which(r[0],!0),o=r.slice(1),i=UY.exec(zY(n),o,{delay:100});if(e)return i}import GY from"csv-parser";import{createReadStream as jY}from"fs";function bE(t){return new Promise((e,r)=>{let n=[];jY(t).pipe(GY()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>r(o))})}import js from"semver";import{z as Ym}from"zod";var Nr="2.29.5",VY="https://registry.npmjs.org/momentic",$Y=Ym.object({versions:Ym.record(Ym.string(),Ym.unknown()).optional()});async function tr(t){try{await WY(t)}catch(e){b.warn({err:e},"Failed to check CLI version against NPM servers")}}async function TE(){let t=await $(fetch(VY),{milliseconds:5e3});if(!t.ok)throw new Error(`Got error status code ${t.statusText}`);let e=await t.json(),r=$Y.parse(e).versions;if(!r)throw new Error("Failed to fetch npm registry data. Skipping version check.");let n=Nr;for(let o of Object.keys(r))js.valid(o)&&js.major(o)===js.major(Nr)&&js.gt(o,n)&&js.prerelease(o)===null&&(n=o);return n}async function WY(t){let e;for(let r=0;r<2;r++)try{e=await TE()}catch(n){t.warn({err:n},"Failed to fetch latest version from npm registry")}if(!e){t.warn("Failed to fetch npm registry data. Skipping version check.");return}js.eq(Nr,e)||(b.warn(`Update available: v${Nr} -> v${e}`),b.warn("This version may be missing critical fixes, features, and security updates."),b.warn('Run "npx momentic@latest upgrade" to update'))}async function Eo(){try{await $(Promise.all([TA(),kt.flush()]),{milliseconds:5e3})}catch{}}import{partition as qY}from"lodash-es";function Xm(t){return t.length===1?"test":"tests"}function fN(t){return t===1?"1 worker":`${t} workers`}function SN(t){t.length!==0&&(b.info(`Skipping ${t.length} disabled ${Xm(t)}:`),t.forEach(e=>{b.info(`${dt}- ${[e.relativeFilePath]}`)}),b.log(""))}function yN(t,e){t.length!==0&&(b.info(`Skipping ${t.length} quarantined ${Xm(t)}:`),t.forEach(r=>{b.info(`${dt}- ${[r.relativeFilePath]}: ${e[r.id]}`)}),b.log(""))}function KY(t,e){t.length!==0&&(b.info(`Running ${t.length} quarantined ${Xm(t)} with ${fN(e)}:`),t.forEach(r=>{b.info(`${dt}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),b.log(""))}function YY(t,e,r){e.length===0&&t.length>0||(b.info(`Running ${e.length} ${Xm(e)} with ${fN(r)}:`),e.forEach(n=>{b.info(`${dt}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),b.log(""))}function EN({logger:t,localTestsToRunWithInputs:e,parallel:r,shardCount:n,shardIndex:o}){t.info({tests:e.length,shardCount:n,shardIndex:o,parallel:r},"Running local tests");let[i,a]=qY(e,s=>s.quarantined);KY(i,r),YY(i,a,r)}import{randomUUID as XY}from"crypto";import{cloneDeep as Vs}from"lodash-es";async function bN({orgId:t,codeEvalTools:e,logger:r,outputDefinitions:n,testContext:o}){let i={};for(let a of n){let{name:s,value:c}=a;i[s]=await pr({orgId:t,s:c,localTools:e,logger:r,context:o})}return i}async function TN({baseUrl:t,envName:e,testName:r,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:s,generator:c,orgId:l,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f,tracer:S}){let y=await mm({settings:g,customHeaders:p,envVariables:u,envName:e,testName:r,baseUrl:t,logger:d,localTools:s,orgId:l}),E={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:X,mode:"runner"},T=xu({browserType:y.browserType,orgDefaultBrowserType:g.defaultBrowserType});if(!wA(T)){let _=`Browser ${T} is required by the test named ${i.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;b.warn(_),X.warn(_)}let v=await qr.init({baseUrl:t,logger:d,userBrowserSettings:y,storage:a,enricher:new Ho(E,c),contextArgs:{viewport:i.advanced.viewport??Kt,locale:i.advanced.locale??Io,geolocation:i.advanced.geolocation??Lo,timezoneId:i.advanced.timezone??Oo,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},callbacks:{onNetworkPage:_=>S.onNetworkPage(_),onNetworkLogs:_=>S.onNetworkLogs(_)},iconKnowledgeBase:null,videoOptions:S.videoOutputPath?{videoOutputPath:S.videoOutputPath,onVideoPageChange:({videoName:_})=>{S.setActiveVideo(_)}}:void 0}),w=new oi({browser:v,generator:c,logger:d,orgId:l,options:{scratchPadId:void 0,slowMoMs:y.slowMoMs,autoFollowNewTabs:y.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering},storage:a,localCodeEvalTools:s,visualDiffScreenshotStorage:f}),C=new lr({baseUrl:t,currentUrl:w.browser.url(),variablesFromEnvironment:u,envName:e,testName:r});return i.parameters&&await Promise.all(i.parameters.map(async _=>{let{name:N,defaultValue:U,required:j}=_,O=m?.[N];j&&O===void 0&&(b.error(`Required parameter '${N}' is required by test '${i.name}' but not provided`),process.exit(1));let B=await pr({orgId:l,s:O??U,localTools:s,logger:d,context:lr.dummyContext(C.getEnvName())});C.setMomenticSystemVariable(N,B)})),{controller:w,context:C}}async function vN({testAdvancedSettings:t,orgSettings:e,logger:r}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Ni){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return r.warn(n),b.warn(n),!1}return!0}async function RN({attemptInputs:t,attemptFixtures:e,attemptMetadata:r}){let{orgId:n,runId:o}=r,{controller:i,context:a,codeEvalTools:s,storageClient:c,logger:l,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=t;l.info(`Running test '${p.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let g={controller:i,storage:c,usageTracker:u,context:a,logger:l,codeEvalTools:s},h={orgId:n,runId:o,testMetadata:p,steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps,orgSettings:m},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await vN({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:l})};return await pm({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function AN(t){let{testDefinition:e,logger:r}=t,n=new Date;try{return await JY(t)}catch(o){let i="Fatal error running test";return b.error(`${i}: ${o.message}`),r.error({err:o},i),{results:[],parameters:t,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:n,lastAttemptStartedAt:n,finishedAt:new Date,outputs:{}}}}async function JY(t){let{testDefinition:e,project:r,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:s,logger:c,gitMetadata:l,cacheOptions:u,runId:d,testInputs:p,quarantined:m,quarantinedReason:g,usageTracker:h}=t,f=new Qa(n,o),S=Go({orgId:o,client:n,gitMetadata:l,regenerateCache:u.regenerateCache??!1,alwaysSaveCache:u.alwaysSaveCache??!1,noCache:u.noCache??!1,bustOldestCachePercentage:u.bustOldestCachePercentage}),y=await Rd({cacheStorage:S,logger:c,schemaVersion:e.schemaVersion,stepLists:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},testId:e.id}),E=y.steps,T=y.beforeSteps??void 0,v=y.afterSteps??void 0,w=t.envName??ZY(e),C,_={};if(w){try{C=Gi(w,r,c)}catch(O){let B=`Failed to resolve environment ${w} for test ${e.name}: ${O}`;throw new Error(B)}_=C.variables}let N=e.baseUrl;if(i)N=i;else if(!N){let O=_[Rt];typeof O=="string"&&(N=O)}if(!N){let O=`Cannot run test with no base URL and no ${Rt} variable defined in its environment`;throw new Error(O)}let U=await s.startRun({logger:c,runId:d,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:N,environmentName:w,schemaVersion:e.schemaVersion,resolvedInputs:p,quarantined:m,quarantinedReason:g}),j=c.child(U.loggerBindings||{});Object.entries(U.envVarBindings||{}).forEach(([O,B])=>{_[O]=B});try{let O=await QY({...t,variables:_,envName:w,resolvedEnv:C,baseUrl:N,storageClient:f,tracer:U,logger:j,cacheStorage:S,stepsWithCaches:E,beforeStepsWithCaches:T,afterStepsWithCaches:v,usageTracker:h});return await U.finish({logger:c,status:O.status,finishedAt:O.finishedAt,failureDetails:O.failureDetails,failureReason:O.failureReason,isFlake:O.isFlake,failureRecoveryDetails:O.failureRecoveryDetails}),{runId:U.runId,...O}}finally{a?.pop()}}async function QY(t){let{testDefinition:e,stepsWithCaches:r,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:s,generator:c,baseUrl:l,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:g,testInputs:h,variables:f,resolvedEnv:S,retriesOverride:y,devicePixelRatio:E,logUpdate:T,tracer:v,logger:w,cacheStorage:C,gitMetadata:_,quarantined:N,quarantinedReason:U,usageTracker:j}=t,O=i.config.ai?.aiFailureAnalysis??!1,B=new Date,W=new ps(i,a),q={...i.config},ve={envName:p,urlOverride:m,customHeaders:g,testInputs:h},Y,st=Math.abs(y??i.config.retries??e.retries??0),Le=[];w.info({..._,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let gt=0;gt<=st;gt++){let rr=XY(),Ge=await v.startAttempt(rr),se=w.child(Ge.loggerBindings||{}),Ke={...e,steps:Vs(r),beforeSteps:Vs(n),afterSteps:Vs(o)};gt!==0&&T("RETRY",`attempt ${gt+1}/${st+1}`);let tn=new Date,ga=q.advanced?.fakerConstantSeed,$s=new On({httpClient:new zt({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:se,mode:"runner"}),fakerSeed:ga?qa:void 0}),Zm=Ge;try{let{controller:nr,context:rn}=await TN({tracer:Ge,baseUrl:l,envName:p,testName:Ke.name,apiClient:s,devicePixelRatio:E,logger:se,storageClient:u,codeEvalTools:$s,test:Ke,generator:c,orgId:d,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...i.config.browser||{},...S?.browser||{},...Ke.advanced},aiSettings:{...i.config.ai||{},...Ke.advanced||{}},visualDiffScreenshotStorage:W});Y=await RN({attemptMetadata:{attemptNumber:gt+1,orgId:d,runId:v.runId},attemptFixtures:{logger:se,storageClient:u,usageTracker:j,codeEvalTools:$s,apiClient:s,context:rn,controller:nr,tracer:Ge},attemptInputs:{test:Ke,orgSettings:q}});let pi=new Date,En={logger:w,cacheStorage:C,orgId:d,testId:e.id,originalStepsWithCaches:{steps:Vs(r),beforeSteps:Vs(n),afterSteps:Vs(o)},updatedStepsWithCaches:{steps:Ke.steps,beforeSteps:Ke.beforeSteps,afterSteps:Ke.afterSteps}};Y?.status==="PASSED"?await Md(En):Y?.status==="FAILED"&&gt===st&&await Pd(En),await Ge.finish({logger:se,result:Y}),Le.unshift(Y.status);let J=await bN({orgId:d,codeEvalTools:$s,logger:se,outputDefinitions:e.outputs??[],testContext:rn}),bo=LT(Le),fa=gt+1;if(Y.status!=="FAILED")return{...Y,runAttemptId:rr,parameters:ve,test:Ke,filePath:Ke.relativeFilePath,startedAt:B,lastAttemptStartedAt:tn,finishedAt:pi,attempts:fa,baseUrl:l,outputs:J,isFlake:bo,quarantined:N,quarantinedReason:U};let Ws=Y.failedStepResult,Kn=Ws?.message||"Unknown failure",Yn=Ws?.failureReason??Bb(Kn)??"UnknownError",qs=se.child({failureReason:Yn,errorMessage:Kn,numAttempts:(st+1).toString(),name:Ke.name});if(gt<st){qs.warn(`Retrying failed execution attempt for run: ${Kn}`);continue}qs.error(`Test failed after all exhausting attempts: ${Kn}`);let Sa=new Error(Kn),To={errorMessage:Kn,errorStack:Sa.stack},eh;if(O){let Ks;try{if(Y.results&&Y.results.length>0){let{classification:De,aiFailureReason:Tr}=await Fw({logger:se,browserStateStorage:Zm,generator:c,fullResults:Y,failureReason:Yn,error:Sa,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Ks=De,eh=Tr}}catch(De){se.warn({err:De},"Failed to classify test results")}Ks&&(To.classification=Ks,Yn=eh??Yn)}return{...Y,runAttemptId:rr,parameters:ve,failureDetails:To,failureReason:Yn,test:Ke,filePath:Ke.relativeFilePath,startedAt:B,lastAttemptStartedAt:tn,finishedAt:pi,attempts:gt+1,baseUrl:l,outputs:J,quarantined:N,quarantinedReason:U}}catch(nr){Xs(nr);let rn=`Encountered fatal platform error while running test '${Ke.name}': ${nr}`,pi=new Date,En=gt+1;se.error({err:nr},rn),b.error(rn);let J={errorMessage:nr.message,errStack:nr.stack},bo={status:"FAILED",failureDetails:J,failureReason:"InternalPlatformError",finishedAt:pi};return await Ge.finish({logger:se,result:{status:"FAILED",results:[]}}),{...bo,runAttemptId:rr,results:[],parameters:ve,test:Ke,filePath:Ke.relativeFilePath,startedAt:B,lastAttemptStartedAt:tn,finishedAt:new Date,attempts:En,baseUrl:l,outputs:{},quarantined:N,quarantinedReason:U}}}throw new Error("This code should not be reachable")}function ZY(t){for(let e of t.envs??[])if(e.default)return e.name}import r5 from"adm-zip";import n5 from"path";function e5(t){switch(t){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}var ha=class{constructor(e,r,n,o){this.orgId=e;this.testId=r;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,r){return this.diskStorage.readFile(`${ur}/${r}.jpeg`)}async getHtmlSnapshot(e,r){return this.diskStorage.readFile(`${ur}/${r}.html`)?.toString()}getParentStepIdChain(){return[]}recordStepStat(e){e.type!=="PRESET_ACTION"?this.stepFrequenciesByType[e.type]=(this.stepFrequenciesByType[e.type]||0)+1:this.stepFrequenciesByType[e.command.type]=(this.stepFrequenciesByType[e.command.type]||0)+1}sendFinalizedStepStats(){for(let[e,r]of Object.entries(this.stepFrequenciesByType))kt.increment("test_step_execution",r,[`type:${e}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async startStep(e){let{step:r}=e;this.recordStepStat(r);let n={step:r,status:"RUNNING",startedAt:new Date},o=new vE(this.orgId,this.testId,this.testName,n,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(r=>r.finishInternal({status:e5(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}};function t5(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var vE=class{constructor(e,r,n,o,i){this.orgId=e;this.testId=r;this.testName=n;this.metadata=o;this.diskStorage=i}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:r,screenshot:n}=e;this.metadata.beforeSnapshotId=r,this.diskStorage.storeFile({name:`${ur}/${r}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:r,screenshot:n}=e;this.metadata.afterSnapshotId=r,this.diskStorage.storeFile({name:`${ur}/${r}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:r,html:n}=e;this.metadata.beforeSnapshotId=r,this.diskStorage.storeFile({name:`${ur}/${r}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:r,html:n}=e;this.metadata.afterSnapshotId=r,this.diskStorage.storeFile({name:`${ur}/${r}.html`,contents:n})}recordTargetAutoHeal(e){let{healType:r}=e,n=r==="AI"?"ai-target-heal":"cache-heal";kt.increment("test_event",1,[`name:${n}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:r,healedAt:new Date}}recordStepDuration(e){let r=e.step.type!=="PRESET_ACTION"?e.step.type:e.step.command.type;kt.distribution("test_step_duration",e.durationMs,[`type:${r}`,"platform:browser","executor:cli",`orgId:${this.orgId}`])}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(r=>r.finish({status:t5(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new ha(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}};var Xc=class{constructor(e,r,n,o,i,a,s){this.orgId=e;this.testId=r;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.recordVideo=s;this.diskStorage.mkdir(ur),this.harPagesStream=this.diskStorage.createFileStream(`${ur}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${ur}/har-entries.log`)}finished=!1;children=[];harPagesStream;inProgressHarEntries;harEntriesStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}get videoOutputPath(){if(this.recordVideo)return n5.resolve(this.diskStorage.cwd(),ur)}setActiveVideo(e){this.recordVideo&&(this.metadata.activeVideos=this.metadata.activeVideos||[],this.metadata.activeVideos.push({videoName:e,timestamp:new Date}))}onNetworkPage(e){this.finished||this.harPagesStream.write(`${JSON.stringify(e)}
4845
4845
  `)}onNetworkLogs(e){if(!this.finished)for(let[r,n]of Object.entries(e))n.response?(delete this.inProgressHarEntries[r],this.harEntriesStream.write(`${JSON.stringify(n)}
4846
4846
  `)):this.inProgressHarEntries[r]=n}attachConsoleLogs(e){let{logs:r}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(r,null,2)})}attachBrowserCrashDump(e){let{crashReportDirFetcher:r,logger:n}=e,o=r();if(!o)return;let i=new r5;i.addLocalFolder(o,void 0,a=>a!==".DS_Store"),this.diskStorage.storeFile({name:`${ur}/${Ug}`,contents:i.toBuffer()}),n.info({browserCrashZipName:Ug},"Attached browser crash ZIP")}async finish(e){if(this.finished)return;this.finished=!0;let{logger:r,result:n}=e,o={...this.metadata,status:n.status,finishedAt:new Date,results:_d(n.results,r),beforeResults:n.beforeResults?_d(n.beforeResults,r):void 0,afterResults:n.afterResults?_d(n.afterResults,r):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt})));for(let i of Object.values(this.inProgressHarEntries))this.harEntriesStream.write(`${JSON.stringify(i)}
4847
- `);try{this.harEntriesStream.end()}catch{}try{this.harPagesStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new ha(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new ha(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new ha(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,r){return this.diskStorage.readFile(`${ur}/${r}.jpeg`)}async getHtmlSnapshot(e,r){return this.diskStorage.readFile(`${ur}/${r}.html`)?.toString()}};var Jc=class{constructor(e,r,n,o,i,a,s){this.orgId=e;this.testId=r;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a;this.recordVideo=s}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[VI]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let r={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,result:{status:r.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)}),this.diskStorage.close()}async startAttempt(e){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let r=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n={id:e,schemaVersion:_e,runAttemptSchemaVersion:sA,startedAt:new Date,status:"RUNNING"};r.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new Xc(this.orgId,this.testId,this.testName,e,n,r,this.recordVideo);return this.children.push(o),o}};var Qc=class t{constructor(e,r,n,o,i){this.orgId=e;this.runGroupId=r;this.metadata=n;this.diskStorage=o;this.recordVideo=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:r,outputDir:n,gitMetadata:o,labels:i,recordVideo:a}){let s={...o,id:r,trigger:zr.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Nr,labels:i??[]},c=new ec(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)}),new t(e,r,s,c,a??!1)}async finish(e){if(this.finished)return;this.finished=!0;let{status:r}=e,n={...this.metadata,status:r,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let r=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:Nr,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};r.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new Jc(this.orgId,e.testId,e.testName,e.runId,n,r,this.recordVideo);return this.children.push(o),o}};async function wN(t,e,r){if(r)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return t.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function CN(t){let{logger:e,tests:r,yes:n,start:o,waitOn:i,waitOnProxy:a,client:s,project:c,retriesOverride:l,urlOverride:u,envName:d,orgId:p,devicePixelRatio:m,customHeaders:g,testInputMatrix:h,reporter:f,include:S,exclude:y,labels:E,reporterDir:T=rC,outputDir:v=nC,uploadResults:w=!1,waitOnTimeout:C=60,parallel:_,shardIndex:N=1,shardCount:U=1,regenerateGoldenFiles:j,gitMetadata:O,cacheOptions:B,ignoreQuarantine:W,skipQuarantined:q,onlyQuarantined:ve,runGroupId:Y,recordVideo:st,timeoutMinutes:Le}=t;if(o&&(e.info({orgId:p},`Executing start command: ${o}`),await gN(o,!1)),i){e.info({orgId:p},`Waiting for url: ${i} with timeout: ${C} seconds.`);let De=a?new URL(a):void 0,Tr;De&&(Tr={host:De.hostname,port:De.port?parseInt(De.port):De.protocol.startsWith("https")?443:80,auth:De.username||De.password?{username:De.username,password:De.password}:void 0}),await a5({resources:[i],interval:2500,timeout:C*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1,proxy:Tr})}let gt=new no(c.config.ai?.agentConfig,{baseUrl:s.baseUrl,apiKey:s.apiKey,logger:e,mode:"runner"}),rr=await ee(c),Ge=await Hs({tests:r,momenticFiles:rr,yes:n,project:c,include:S,exclude:y,labels:E,logger:b}),se=await wN(e,s,W),{testsToSkip:qe,quarantinedTestsToSkip:tn,testsToRun:ga,quarantinedTestsToRun:$s}=eN({testDefinitions:Ge,quarantinedTestReasons:se,onlyQuarantined:ve,skipQuarantined:q});SN(qe),yN(tn,se);let Zm=tN({testsToRun:ga,quarantinedTestsToRun:$s,quarantinedTestReasons:se,testInputMatrix:h}),nr=MA({items:Zm,shardIndex:N,shardCount:U});EN({logger:e,localTestsToRunWithInputs:nr,parallel:_,shardCount:U,shardIndex:N});let rn=[],pi=new Date,En=new Set,J=async()=>{let De=s.getAppUrl(),Tr=Ja({results:rn,startTime:pi.getTime(),onFailed:vr=>{pd(vr,vr.filePath)},getDisplayLine:vr=>{let mi=`${dt}- ${vr.filePath}${vr.failureRecoveryDetails?" [recovered] ":""}`;return vr.runId&&(mi+=` ( link when uploaded: ${De}/runs/${vr.runId} )`),mi},entity:"test"}),Zc=rn.filter(vr=>!!vr.failureRecoveryDetails?.attempts);return Zc.length>0&&b.warn(`Our AI agent automatically prevented ${Zc.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.
4848
- `),b.log(""),w?(b.success(`Test results have been saved to the folder ${v}. Uploading to Momentic Cloud...`),await Kd({client:s,consoleLogger:b,resultsPath:v})):b.success(`Test results have been saved to the folder ${v}. Upload them to Momentic Cloud by running 'npx momentic results upload ${v}'.`),Tr};i5.existsSync(v)&&b.warn(`Output directory ${v} already exists, removing before test execution...`);let bo=await Qc.start({orgId:p,runGroupId:Y,outputDir:v,gitMetadata:O,labels:E,recordVideo:st}),fa=e.child(bo.loggerBindings||{}),Ws=[],Kn=!1,Yn=async De=>{Kn||(Kn=!0,b.warn(`${De} Stopping tests and printing latest results...`),await bo.finish({logger:fa,status:"CANCELLED"}),await J(),await Promise.allSettled(Ws.map(Tr=>Tr())),await Eo(),process.exit(1))},qs=async()=>{await Yn("SIGINT received.")};process.once("SIGINT",qs);let Sa;if(Le!==void 0&&Le>0){let De=Le*60*1e3;b.info(`Test run timeout set to ${Le} minute(s).`),Sa=setTimeout(()=>{Yn(`Timeout of ${Le} minute(s) reached.`)},De)}let To={};for(let De=0;De<nr.length;De++){let Tr=Object.values(To);Tr.length===_&&await Promise.race(Tr.map(mi=>mi.promise));let Zc=nr[De],vr=`test-${De}`;To[vr]={done:!1,promise:(async({inputs:mi,quarantined:DN,quarantinedReason:kN,testDefinition:hi})=>{En.add({inputs:mi});let eu=hi.relativeFilePath.includes("..")?hi.fullFilePath:hi.relativeFilePath;Bl({status:"START",testLogRef:eu,getRunningTestsCount:()=>En.size,getTotalTestsCount:()=>nr.length});let FN=setInterval(()=>Bl({status:"RUN",testLogRef:eu,getRunningTestsCount:()=>En.size,getTotalTestsCount:()=>nr.length}),5*60*1e3),th=o5(),rh=fa.child({testId:hi.id,runId:th}),wE=new kd({logger:rh,reporter:new hd(s),runType:"test-run",runId:th,testMetadata:hi,suiteMetadata:void 0});try{let Ys=await AN({testDefinition:hi,project:c,testInputs:mi,quarantined:DN,quarantinedReason:kN,orgId:p,runId:th,devicePixelRatio:m,apiClient:s,runGroupTracer:bo,generator:gt,retriesOverride:l,urlOverride:u,envName:d,customHeaders:g,regenerateGoldenFiles:j,logUpdate:(tu,UN)=>Bl({status:tu,testLogRef:eu,getRunningTestsCount:()=>En.size,getTotalTestsCount:()=>nr.length,additionalText:UN}),runSigIntHandlers:Ws,logger:rh,gitMetadata:O,cacheOptions:B,usageTracker:wE});Bl({status:Ys.status,testLogRef:eu,getRunningTestsCount:()=>En.size,getTotalTestsCount:()=>nr.length}),rn.push(Ys)}catch(Ys){let tu=`Encountered unexpected fatal error when running test '${hi.name}': ${Ys.message}`;b.error(tu),rh.error({err:Ys},tu),await Yn("Fatal error occurred.")}finally{clearInterval(FN),To[vr].done=!0,delete To[vr]}await wE.flush(e)})(Zc)}}await Promise.allSettled(Object.values(To).map(De=>De.promise));let Ks=rn.some(De=>!De.quarantined&&De.status==="FAILED")?"FAILED":"PASSED";return process.off("SIGINT",qs),Sa&&clearTimeout(Sa),await bo.finish({logger:fa,status:Ks}),f&&await mN({logger:fa,callbacks:{createDebugDataReaderForRunAttempt:(De,Tr)=>new Yd(v,De,Tr)},format:f,params:{projectConfigPath:c.configFilePath,suiteName:c.config.name,startedAt:pi,finishedAt:new Date,runs:rn,testsToSkip:qe,quarantinedTestsToSkip:tn,quarantinedTestReasons:se},folder:T}),J()}import{installPackage as s5}from"@antfu/install-pkg";import{cloneDeep as l5}from"lodash-es";import c5 from"semver";async function xN(){let t=await TE();c5.lt(Nr,t)&&b.warn(`The current CLI version (${Nr}) is not the latest. It's recommended to run the upgrade command using momentic@latest.`),await s5(`momentic@${t}`,{silent:!1,dev:!0})}function _N(t){let e=l5(t.config),r={...e.ai?.agentConfig,...Gu},n={...e.ai,agentConfig:r};e.ai=n,$o(e,t.configFilePath)}nh||X.warn("Sentry is not enabled in this environment due to unsupported node version");iI({serviceName:"cli"});var PN=process.argv.some(t=>t.includes("--log-level"))&&process.argv.some(t=>t.includes("debug")),IN=t=>{PN&&b.dimmed(t)};PN&&xA(X);var Vt=new u5;Vt.name("momentic").description("Momentic CLI").version(Nr);Vt.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${$g.join(", ")}.`).action(async(t,e)=>{await tr(X),!e.all&&t.length===0&&(b.error("No browsers specified"),process.exit(1)),await CA({rawBrowsers:t,force:e.force,all:e.all})});Vt.addOption(new hr("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",t=>{t==="debug"&&b.info("Enabling debug logging"),b.setMinLevel(t.toLowerCase())});Vt.addOption(new hr("--verbose","enable verbose logging")).on("option:verbose",()=>{X.enableConsoleLogs(),b.setMinLevel(20)});var RE=Vt.command("checks").alias("check").description("Perform various project checks");RE.command("config").addOption(mr).action(async t=>{await tr(X),await _t({configFilePath:t.config})});RE.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(mr).addOption(BL).action(async t=>{await tr(X);let e=await _t({configFilePath:t.config});await wL({project:e,fix:t.fix})});RE.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(mr).action(async t=>{await tr(X);let e=await _t({configFilePath:t.config});await CL({project:e})});var ON=Vt.command("migrate").description("Migrate and upgrade tooling");ON.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(mr).action(async t=>{let e=await _t({configFilePath:t.config});await JL(e)});ON.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(en).addOption(mr).addOption(Zr).addOption(ui).action(async t=>{!t.yes&&!await Bt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?")&&process.exit(1);let e=await _t({configFilePath:t.config}),r=new et({baseUrl:t.server,apiKey:t.apiKey,logger:X}),{orgId:n}=await r.getAuthInfo();await QL({project:e,orgId:n,apiClient:r}),process.exit(0)});Vt.command("import").addOption(Zr).addOption(en).addOption(mr).addOption(ui).addArgument(WL).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n,config:o,yes:i}=e,a=await _t({configFilePath:o}),s=new et({baseUrl:n,apiKey:r,logger:X});!t||t.length===0?await IL({client:s,project:a,skipPrompts:i}):await OL({client:s,project:a,paths:t,skipPrompts:i}),process.exit(0)});Vt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new hr("--name <name>","Name of the project")).action(async t=>{await tr(X),b.info(`Welcome to the Momentic project setup wizard! \u{1F680}
4849
- `),b.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),Qm.existsSync(us)&&(b.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let e=t.name??await hA("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app");await iC()||await Bt("A Git repository was not detected in the current directory. Momentic highly recommends initializing your project within a Git repository for seamless version control. Continue?")||process.exit(1),$o({name:e,include:Vd},us),b.success(`Initialized Momentic project file at ${Jm.resolve(us)}`)});Vt.command("app").addOption(Zr).addOption(en).addOption(ui).addOption(aE).addOption(mr).addOption(lE).addOption(cE).addOption(uE).action(async t=>{await tr(X);let{apiKey:e,yes:r,server:n,pixelRatio:o,disableCache:i,saveCache:a,regenerateCache:s}=t,c=await _t({configFilePath:t.config,nameFilter:void 0}),{errors:l,parsingErrors:u,failedTestFilePaths:d,failedModuleFilePaths:p,parsingErrorDetails:m}=await km({project:c,fix:!1});u>0?(qc({parsingErrors:u,parsingErrorDetails:m,failedTestFilePaths:d,failedModuleFilePaths:p}),process.exit(1)):l>0&&(b.error(`Found ${l} errors`),b.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1)),r_(X);let g=new et({baseUrl:n,apiKey:e,logger:X});await Jg({client:g,skipPrompts:r});let h=g5(import.meta.url),f=Jm.dirname(h),S=Jm.resolve(f,"..","static"),y=Jm.resolve(f,"..","assets"),E=o??yE();EE(E),await TL({momenticServerUrl:n,apiKey:e,serverPort:Fm,appPort:Fm,staticDir:S,assetsDir:y,devicePixelRatio:E,regenerateCache:s,noCache:i,alwaysSaveCache:a,initialProject:c});let T=`http://localhost:${Fm}`;await h5(T)});var LN=Vt.command("queue").description("Queue tests or suites to run on Momentic Cloud");LN.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Zr).addOption(en).addOption(tE).addOption(rE).addOption(ui).addArgument(qL).addOption(Hm).addOption(zm).addOption(Bm).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n,wait:o,waitTimeout:i,env:a,urlOverride:s}=e,c=Um(e.customHeaders),l=new et({baseUrl:n,apiKey:r,logger:X});(!t||!Array.isArray(t)||!t.length)&&(b.error("Must pass at least one suite to run."),process.exit(1));let{orgId:u}=await l.getAuthInfo();await iN({client:l,orgId:u,wait:o,suitePaths:t,waitTimeout:i,env:a,urlOverride:s,customHeaders:c}),await Eo()});LN.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Zr).addOption(en).addOption(ui).addOption(Bm).addOption(sE).addOption(Hm).addOption(zm).addOption(new hr("--all","Run all tests.").default(!1)).addOption(tE).addOption(rE).addArgument($L).action(async(t,e)=>{await tr(X);let{all:r,apiKey:n,env:o,server:i,inputCsv:a,urlOverride:s,wait:c,waitTimeout:l,yes:u}=e,d=Um(e.customHeaders);for(let h of t)(h.endsWith(".yaml")||Qm.existsSync(h))&&b.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let p=new et({baseUrl:i,apiKey:n,logger:X}),{orgId:m}=await p.getAuthInfo(),g;a&&(g=await bE(a)),await aN({client:p,orgId:m,tests:t,all:r,customHeaders:d,env:o,urlOverride:s,wait:c,waitTimeout:l,testInputMatrix:g,yes:u}),await Eo(),process.exit(0)});var f5=Vt.command("list").description("List test paths");f5.addOption(mr).addOption(di).addOption(oE).addOption(iE).addOption(new hr("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(dE).action(async(t,e)=>{let r=await _t({configFilePath:e.config,nameFilter:e.filter}),n=await ee(r),o=await Hs({tests:t,momenticFiles:n,yes:!0,project:r,include:e.include,exclude:e.exclude,labels:e.labels,logger:new Li(40,{})});b.info(o.map(i=>i.relativeFilePath).join(`
4850
- `)),process.exit(0)});var S5=Vt.command("run").alias("test").description("Run tests on the local machine");S5.addOption(Zr).addOption(en).addOption(mr).addOption(di).addOption(ui).addOption(Bm).addOption(sE).addOption(lE).addOption(cE).addOption(uE).addOption(zL).addOption(VL).addOption(HL).addOption(GL).addOption(jL).addOption(zm).addOption(Hm).addOption(aE).addOption(new hr("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new hr("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new hr("--wait-on-proxy <waitOnProxy>","HTTP proxy to use with the --wait-on command. Specify as https://username:pass@domain.com:2345")).addOption(new hr("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(Wn)).addOption(new hr("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(Wn)).addOption(new hr("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Wn)).addOption(new hr("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new hr("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(NL).addOption(DL).addOption(nE).addOption(kL).addOption(UL).addOption(FL).addOption(oE).addOption(iE).addOption(XL).addArgument(dE).action(async(t,e)=>{await tr(X),_A({shardIndex:e.shardIndex,shardCount:e.shardCount});let r=Um(e.customHeaders),n=await _t({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??n.config.parallel??1;MN().length<o*2&&b.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${MN().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),b.debug({projectName:n.config.name},"Identified project config");let{errors:i,parsingErrors:a,parsingErrorDetails:s,failedTestFilePaths:c,failedModuleFilePaths:l}=await km({project:n,fix:!1});a>0?(qc({parsingErrors:a,parsingErrorDetails:s,failedTestFilePaths:c,failedModuleFilePaths:l}),process.exit(1)):i>0&&(b.error(`Found ${i} errors`),b.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let u=new et({baseUrl:e.server,apiKey:e.apiKey,logger:X});b.debug("Checking API key and dependencies");let{orgId:d,userId:p}=await Jg({client:u,skipPrompts:e.yes});b.debug("API key check and browser installation complete");let m=e.outputDir??n.config.outputDir,g=e.reporterDir??n.config.reporterDir,h=p5(),f=X.child({cliVersion:Nr,orgId:d,userId:p,runGroupId:h}),S=await Vr(X,u,n);f.info({gitMetadata:S,config:n.config,nodeVersion:process.versions.node},"Got local metadata");let y;e.inputCsv&&(y=await bE(e.inputCsv));let E=e.pixelRatio??yE();EE(E);try{let T=await CN({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:E,tests:t,project:n,client:u,outputDir:m,uploadResults:e.uploadResults,reporterDir:g,customHeaders:r,envName:e.env,orgId:d,testInputMatrix:y,logger:f,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:S,cacheOptions:{regenerateCache:e.regenerateCache,alwaysSaveCache:e.saveCache,noCache:e.disableCache,bustOldestCachePercentage:e.bustOldestCachePercentage},recordVideo:e.recordVideo??n.config.recordVideo,runGroupId:h,timeoutMinutes:e.timeoutMinutes});await Eo(),T.failed>0?process.exit(1):process.exit(0)}catch(T){b.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),b.error(T),await Eo(),process.exit(1)}});var y5=Vt.command("apply").description("Apply an operation to local resources");y5.command("patch").addOption(Zr).addOption(en).addOption(mr).addOption(di).addOption(ui).addOption(new hr("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new hr("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async t=>{await tr(X);let{apiKey:e,server:r,config:n,yes:o}=t,i=await _t({configFilePath:n}),a=X,s=new et({baseUrl:r,apiKey:e,logger:a}),c=await ee(i),l=c.tests[t.to]??Object.values(c.tests).find(d=>ze(d.name)===t.to.trim());l||(b.error(`No test matching '${t.to}' could be found in the current project.`),process.exit(1));let u=await s.fetchTestFragment(t.from);await RL({client:s,test:l,fragment:u,yes:o,entities:c,logger:X}),process.exit(0)});var NN=Vt.command("results").description("Merge and upload test results.");NN.command("merge").description("Merge test results files.").addOption(nE).addArgument(KL).action(async(t,e)=>{await tr(X);let{outputDir:r}=e;r||(b.error("Output directory is required."),process.exit(1)),Qm.existsSync(t)||(b.warn("Results path does not exist, skipping merge."),process.exit(0)),Qm.existsSync(r)&&b.warn(`Output directory ${r} already exists, removing before merging...`),cC(X,r,t)});NN.command("upload").description("Upload test results to Momentic cloud.").addOption(Zr).addOption(en).addArgument(YL).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n}=e,o=X,i=new et({baseUrl:n,apiKey:r,logger:o});await Kd({consoleLogger:b,resultsPath:t,client:i}),process.exit(0)});var AE=Vt.command("quarantine").description("Manage test quarantines");AE.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(Zr).addOption(en).addOption(mr).addOption(di).addOption(pE).addArgument(mE).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n,config:o,reason:i}=e,a=X,s=await _t({configFilePath:o}),c=new et({baseUrl:n,apiKey:r,logger:a}),l=await Vr(X,c,s);await ZL({test:t,reason:i,apiClient:c,project:s,logger:a,identity:l})});AE.command("list").description("List quarantined tests.").addOption(Zr).addOption(en).addOption(mr).addOption(di).action(async t=>{let{apiKey:e,server:r,config:n}=t,o=X,i=await _t({configFilePath:n}),a=new et({baseUrl:r,apiKey:e,logger:o});await rN({apiClient:a,project:i})});AE.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(Zr).addOption(en).addOption(mr).addOption(di).addOption(pE).addArgument(mE).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n,config:o,reason:i}=e,a=X,s=await _t({configFilePath:o}),c=new et({baseUrl:n,apiKey:r,logger:a}),l=await Vr(X,c,s);await nN({test:t,reason:i,apiClient:c,project:s,identity:l})});Vt.command("upgrade").description("Upgrade your configuration to the latest recommended settings").addOption(mr).addOption(di).action(async t=>{let e=await _t({configFilePath:t.config,nameFilter:t.filter});b.info("Updating Momentic version in package.json..."),await xN(),b.info("Updating project configuration..."),_N(e),b.success("Your project configuration was successfully updated to the latest recommended settings."),b.info("You can optionally run tests with the `--regenerate-cache` flag to entirely rebuild caches with the newer configuration. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.")});async function E5(){IN("Main program started");try{await Vt.parseAsync(process.argv),await Eo()}catch(t){let e={};try{e.playwrightVersion=d5("npx playwright --version").toString()}catch(r){X.error({err:r},"Error fetching debug information")}X.error({err:t,debugInfo:e},"Uncaught error in CLI"),Xs(t,e),b.error(t),await Eo(),process.exit(1)}}m5.setMaxListeners(25);process.on("warning",t=>{X.warn({err:t},`Node warning received on CLI: ${t.message}`)});IN("CLI parsing setup complete");E5();
4847
+ `);try{this.harEntriesStream.end()}catch{}try{this.harPagesStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new ha(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new ha(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new ha(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,r){return this.diskStorage.readFile(`${ur}/${r}.jpeg`)}async getHtmlSnapshot(e,r){return this.diskStorage.readFile(`${ur}/${r}.html`)?.toString()}};var Jc=class{constructor(e,r,n,o,i,a,s){this.orgId=e;this.testId=r;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a;this.recordVideo=s}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[VI]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let r={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(n=>n.finish({logger:e.logger,result:{status:r.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)}),this.diskStorage.close()}async startAttempt(e){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let r=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n={id:e,schemaVersion:_e,runAttemptSchemaVersion:sA,startedAt:new Date,status:"RUNNING"};r.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new Xc(this.orgId,this.testId,this.testName,e,n,r,this.recordVideo);return this.children.push(o),o}};var Qc=class t{constructor(e,r,n,o,i){this.orgId=e;this.runGroupId=r;this.metadata=n;this.diskStorage=o;this.recordVideo=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:r,outputDir:n,gitMetadata:o,labels:i,recordVideo:a}){let s={...o,id:r,trigger:zr.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Nr,labels:i??[]},c=new ec(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)}),new t(e,r,s,c,a??!1)}async finish(e){if(this.finished)return;this.finished=!0;let{status:r}=e,n={...this.metadata,status:r,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:n.status,finishedAt:n.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)})}async startRun(e){let r=this.diskStorage.createRunArchive(e.runId),n={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:Nr,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};r.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new Jc(this.orgId,e.testId,e.testName,e.runId,n,r,this.recordVideo);return this.children.push(o),o}};async function wN(t,e,r){if(r)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return t.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function CN(t){let{logger:e,tests:r,yes:n,start:o,waitOn:i,waitOnProxy:a,client:s,project:c,retriesOverride:l,urlOverride:u,envName:d,orgId:p,devicePixelRatio:m,customHeaders:g,testInputMatrix:h,reporter:f,include:S,exclude:y,labels:E,reporterDir:T=rC,outputDir:v=nC,uploadResults:w=!1,waitOnTimeout:C=60,parallel:_,shardIndex:N=1,shardCount:U=1,regenerateGoldenFiles:j,gitMetadata:O,cacheOptions:B,ignoreQuarantine:W,skipQuarantined:q,onlyQuarantined:ve,runGroupId:Y,recordVideo:st,timeoutMinutes:Le}=t;if(o&&(e.info({orgId:p},`Executing start command: ${o}`),await gN(o,!1)),i){e.info({orgId:p},`Waiting for url: ${i} with timeout: ${C} seconds.`);let De=a?new URL(a):void 0,Tr;De&&(Tr={host:De.hostname,port:De.port?parseInt(De.port):De.protocol.startsWith("https")?443:80,auth:De.username||De.password?{username:De.username,password:De.password}:void 0}),await a5({resources:[i],interval:2500,timeout:C*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1,proxy:Tr})}let gt=new no(c.config.ai?.agentConfig,{baseUrl:s.baseUrl,apiKey:s.apiKey,logger:e,mode:"runner"}),rr=await te(c),Ge=await Hs({tests:r,momenticFiles:rr,yes:n,project:c,include:S,exclude:y,labels:E,logger:b}),se=await wN(e,s,W),{testsToSkip:Ke,quarantinedTestsToSkip:tn,testsToRun:ga,quarantinedTestsToRun:$s}=eN({testDefinitions:Ge,quarantinedTestReasons:se,onlyQuarantined:ve,skipQuarantined:q});SN(Ke),yN(tn,se);let Zm=tN({testsToRun:ga,quarantinedTestsToRun:$s,quarantinedTestReasons:se,testInputMatrix:h}),nr=MA({items:Zm,shardIndex:N,shardCount:U});EN({logger:e,localTestsToRunWithInputs:nr,parallel:_,shardCount:U,shardIndex:N});let rn=[],pi=new Date,En=new Set,J=async()=>{let De=s.getAppUrl(),Tr=Ja({results:rn,startTime:pi.getTime(),onFailed:vr=>{pd(vr,vr.filePath)},getDisplayLine:vr=>{let mi=`${dt}- ${vr.filePath}${vr.failureRecoveryDetails?" [recovered] ":""}`;return vr.runId&&(mi+=` ( link when uploaded: ${De}/runs/${vr.runId} )`),mi},entity:"test"}),Zc=rn.filter(vr=>!!vr.failureRecoveryDetails?.attempts);return Zc.length>0&&b.warn(`Our AI agent automatically prevented ${Zc.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.
4848
+ `),b.log(""),w?(b.success(`Test results have been saved to the folder ${v}. Uploading to Momentic Cloud...`),await Kd({client:s,consoleLogger:b,resultsPath:v})):b.success(`Test results have been saved to the folder ${v}. Upload them to Momentic Cloud by running 'npx momentic results upload ${v}'.`),Tr};i5.existsSync(v)&&b.warn(`Output directory ${v} already exists, removing before test execution...`);let bo=await Qc.start({orgId:p,runGroupId:Y,outputDir:v,gitMetadata:O,labels:E,recordVideo:st}),fa=e.child(bo.loggerBindings||{}),Ws=[],Kn=!1,Yn=async De=>{Kn||(Kn=!0,b.warn(`${De} Stopping tests and printing latest results...`),await bo.finish({logger:fa,status:"CANCELLED"}),await J(),await Promise.allSettled(Ws.map(Tr=>Tr())),await Eo(),process.exit(1))},qs=async()=>{await Yn("SIGINT received.")};process.once("SIGINT",qs);let Sa;if(Le!==void 0&&Le>0){let De=Le*60*1e3;b.info(`Test run timeout set to ${Le} minute(s).`),Sa=setTimeout(()=>{Yn(`Timeout of ${Le} minute(s) reached.`)},De)}let To={};for(let De=0;De<nr.length;De++){let Tr=Object.values(To);Tr.length===_&&await Promise.race(Tr.map(mi=>mi.promise));let Zc=nr[De],vr=`test-${De}`;To[vr]={done:!1,promise:(async({inputs:mi,quarantined:DN,quarantinedReason:kN,testDefinition:hi})=>{En.add({inputs:mi});let eu=hi.relativeFilePath.includes("..")?hi.fullFilePath:hi.relativeFilePath;Bl({status:"START",testLogRef:eu,getRunningTestsCount:()=>En.size,getTotalTestsCount:()=>nr.length});let FN=setInterval(()=>Bl({status:"RUN",testLogRef:eu,getRunningTestsCount:()=>En.size,getTotalTestsCount:()=>nr.length}),5*60*1e3),th=o5(),rh=fa.child({testId:hi.id,runId:th}),wE=new kd({logger:rh,reporter:new hd(s),runType:"test-run",runId:th,testMetadata:hi,suiteMetadata:void 0});try{let Ys=await AN({testDefinition:hi,project:c,testInputs:mi,quarantined:DN,quarantinedReason:kN,orgId:p,runId:th,devicePixelRatio:m,apiClient:s,runGroupTracer:bo,generator:gt,retriesOverride:l,urlOverride:u,envName:d,customHeaders:g,regenerateGoldenFiles:j,logUpdate:(tu,UN)=>Bl({status:tu,testLogRef:eu,getRunningTestsCount:()=>En.size,getTotalTestsCount:()=>nr.length,additionalText:UN}),runSigIntHandlers:Ws,logger:rh,gitMetadata:O,cacheOptions:B,usageTracker:wE});Bl({status:Ys.status,testLogRef:eu,getRunningTestsCount:()=>En.size,getTotalTestsCount:()=>nr.length}),rn.push(Ys)}catch(Ys){let tu=`Encountered unexpected fatal error when running test '${hi.name}': ${Ys.message}`;b.error(tu),rh.error({err:Ys},tu),await Yn("Fatal error occurred.")}finally{clearInterval(FN),To[vr].done=!0,delete To[vr]}await wE.flush(e)})(Zc)}}await Promise.allSettled(Object.values(To).map(De=>De.promise));let Ks=rn.some(De=>!De.quarantined&&De.status==="FAILED")?"FAILED":"PASSED";return process.off("SIGINT",qs),Sa&&clearTimeout(Sa),await bo.finish({logger:fa,status:Ks}),f&&await mN({logger:fa,callbacks:{createDebugDataReaderForRunAttempt:(De,Tr)=>new Yd(v,De,Tr)},format:f,params:{projectConfigPath:c.configFilePath,suiteName:c.config.name,startedAt:pi,finishedAt:new Date,runs:rn,testsToSkip:Ke,quarantinedTestsToSkip:tn,quarantinedTestReasons:se},folder:T}),J()}import{installPackage as s5}from"@antfu/install-pkg";import{cloneDeep as l5}from"lodash-es";import c5 from"semver";async function xN(){let t=await TE();c5.lt(Nr,t)&&b.warn(`The current CLI version (${Nr}) is not the latest. It's recommended to run the upgrade command using momentic@latest.`),await s5(`momentic@${t}`,{silent:!1,dev:!0})}function _N(t){let e=l5(t.config),r={...e.ai?.agentConfig,...Gu},n={...e.ai,agentConfig:r};e.ai=n,$o(e,t.configFilePath)}nh||X.warn("Sentry is not enabled in this environment due to unsupported node version");iI({serviceName:"cli"});var PN=process.argv.some(t=>t.includes("--log-level"))&&process.argv.some(t=>t.includes("debug")),IN=t=>{PN&&b.dimmed(t)};PN&&xA(X);var Vt=new u5;Vt.name("momentic").description("Momentic CLI").version(Nr);Vt.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${$g.join(", ")}.`).action(async(t,e)=>{await tr(X),!e.all&&t.length===0&&(b.error("No browsers specified"),process.exit(1)),await CA({rawBrowsers:t,force:e.force,all:e.all})});Vt.addOption(new hr("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",t=>{t==="debug"&&b.info("Enabling debug logging"),b.setMinLevel(t.toLowerCase())});Vt.addOption(new hr("--verbose","enable verbose logging")).on("option:verbose",()=>{X.enableConsoleLogs(),b.setMinLevel(20)});var RE=Vt.command("checks").alias("check").description("Perform various project checks");RE.command("config").addOption(mr).action(async t=>{await tr(X),await _t({configFilePath:t.config})});RE.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(mr).addOption(BL).action(async t=>{await tr(X);let e=await _t({configFilePath:t.config});await wL({project:e,fix:t.fix})});RE.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(mr).action(async t=>{await tr(X);let e=await _t({configFilePath:t.config});await CL({project:e})});var ON=Vt.command("migrate").description("Migrate and upgrade tooling");ON.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(mr).action(async t=>{let e=await _t({configFilePath:t.config});await JL(e)});ON.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(en).addOption(mr).addOption(Zr).addOption(ui).action(async t=>{!t.yes&&!await Bt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?")&&process.exit(1);let e=await _t({configFilePath:t.config}),r=new et({baseUrl:t.server,apiKey:t.apiKey,logger:X}),{orgId:n}=await r.getAuthInfo();await QL({project:e,orgId:n,apiClient:r}),process.exit(0)});Vt.command("import").addOption(Zr).addOption(en).addOption(mr).addOption(ui).addArgument(WL).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n,config:o,yes:i}=e,a=await _t({configFilePath:o}),s=new et({baseUrl:n,apiKey:r,logger:X});!t||t.length===0?await IL({client:s,project:a,skipPrompts:i}):await OL({client:s,project:a,paths:t,skipPrompts:i}),process.exit(0)});Vt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new hr("--name <name>","Name of the project")).action(async t=>{await tr(X),b.info(`Welcome to the Momentic project setup wizard! \u{1F680}
4849
+ `),b.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),Qm.existsSync(us)&&(b.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let e=t.name??await hA("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app");await iC()||await Bt("A Git repository was not detected in the current directory. Momentic highly recommends initializing your project within a Git repository for seamless version control. Continue?")||process.exit(1),$o({name:e,include:Vd},us),b.success(`Initialized Momentic project file at ${Jm.resolve(us)}`)});Vt.command("app").addOption(Zr).addOption(en).addOption(ui).addOption(aE).addOption(mr).addOption(lE).addOption(cE).addOption(uE).action(async t=>{await tr(X);let{apiKey:e,yes:r,server:n,pixelRatio:o,disableCache:i,saveCache:a,regenerateCache:s}=t,c=await _t({configFilePath:t.config,nameFilter:void 0}),{errors:l,parsingErrors:u,failedTestFilePaths:d,failedModuleFilePaths:p,parsingErrorDetails:m}=await km({project:c,fix:!1});u>0?(qc({parsingErrors:u,parsingErrorDetails:m,failedTestFilePaths:d,failedModuleFilePaths:p}),process.exit(1)):l>0&&(b.error(`Found ${l} errors`),b.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1)),r_(X);let g=new et({baseUrl:n,apiKey:e,logger:X});await Jg({client:g,skipPrompts:r});let h=g5(import.meta.url),f=Jm.dirname(h),S=Jm.resolve(f,"..","static"),y=Jm.resolve(f,"..","assets"),E=o??yE();EE(E),await TL({momenticServerUrl:n,apiKey:e,serverPort:Fm,appPort:Fm,staticDir:S,assetsDir:y,devicePixelRatio:E,regenerateCache:s,noCache:i,alwaysSaveCache:a,initialProject:c});let T=`http://localhost:${Fm}`;await h5(T)});var LN=Vt.command("queue").description("Queue tests or suites to run on Momentic Cloud");LN.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Zr).addOption(en).addOption(tE).addOption(rE).addOption(ui).addArgument(qL).addOption(Hm).addOption(zm).addOption(Bm).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n,wait:o,waitTimeout:i,env:a,urlOverride:s}=e,c=Um(e.customHeaders),l=new et({baseUrl:n,apiKey:r,logger:X});(!t||!Array.isArray(t)||!t.length)&&(b.error("Must pass at least one suite to run."),process.exit(1));let{orgId:u}=await l.getAuthInfo();await iN({client:l,orgId:u,wait:o,suitePaths:t,waitTimeout:i,env:a,urlOverride:s,customHeaders:c}),await Eo()});LN.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Zr).addOption(en).addOption(ui).addOption(Bm).addOption(sE).addOption(Hm).addOption(zm).addOption(new hr("--all","Run all tests.").default(!1)).addOption(tE).addOption(rE).addArgument($L).action(async(t,e)=>{await tr(X);let{all:r,apiKey:n,env:o,server:i,inputCsv:a,urlOverride:s,wait:c,waitTimeout:l,yes:u}=e,d=Um(e.customHeaders);for(let h of t)(h.endsWith(".yaml")||Qm.existsSync(h))&&b.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let p=new et({baseUrl:i,apiKey:n,logger:X}),{orgId:m}=await p.getAuthInfo(),g;a&&(g=await bE(a)),await aN({client:p,orgId:m,tests:t,all:r,customHeaders:d,env:o,urlOverride:s,wait:c,waitTimeout:l,testInputMatrix:g,yes:u}),await Eo(),process.exit(0)});var f5=Vt.command("list").description("List test paths");f5.addOption(mr).addOption(di).addOption(oE).addOption(iE).addOption(new hr("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(dE).action(async(t,e)=>{let r=await _t({configFilePath:e.config,nameFilter:e.filter}),n=await te(r),o=await Hs({tests:t,momenticFiles:n,yes:!0,project:r,include:e.include,exclude:e.exclude,labels:e.labels,logger:new Li(40,{})});b.info(o.map(i=>i.relativeFilePath).join(`
4850
+ `)),process.exit(0)});var S5=Vt.command("run").alias("test").description("Run tests on the local machine");S5.addOption(Zr).addOption(en).addOption(mr).addOption(di).addOption(ui).addOption(Bm).addOption(sE).addOption(lE).addOption(cE).addOption(uE).addOption(zL).addOption(VL).addOption(HL).addOption(GL).addOption(jL).addOption(zm).addOption(Hm).addOption(aE).addOption(new hr("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new hr("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new hr("--wait-on-proxy <waitOnProxy>","HTTP proxy to use with the --wait-on command. Specify as https://username:pass@domain.com:2345")).addOption(new hr("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(Wn)).addOption(new hr("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(Wn)).addOption(new hr("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Wn)).addOption(new hr("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new hr("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(NL).addOption(DL).addOption(nE).addOption(kL).addOption(UL).addOption(FL).addOption(oE).addOption(iE).addOption(XL).addArgument(dE).action(async(t,e)=>{await tr(X),_A({shardIndex:e.shardIndex,shardCount:e.shardCount});let r=Um(e.customHeaders),n=await _t({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??n.config.parallel??1;MN().length<o*2&&b.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${MN().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),b.debug({projectName:n.config.name},"Identified project config");let{errors:i,parsingErrors:a,parsingErrorDetails:s,failedTestFilePaths:c,failedModuleFilePaths:l}=await km({project:n,fix:!1});a>0?(qc({parsingErrors:a,parsingErrorDetails:s,failedTestFilePaths:c,failedModuleFilePaths:l}),process.exit(1)):i>0&&(b.error(`Found ${i} errors`),b.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let u=new et({baseUrl:e.server,apiKey:e.apiKey,logger:X});b.debug("Checking API key and dependencies");let{orgId:d,userId:p}=await Jg({client:u,skipPrompts:e.yes});b.debug("API key check and browser installation complete");let m=e.outputDir??n.config.outputDir,g=e.reporterDir??n.config.reporterDir,h=p5(),f=X.child({cliVersion:Nr,orgId:d,userId:p,runGroupId:h}),S=await Vr(X,u,n);f.info({gitMetadata:S,config:n.config,nodeVersion:process.versions.node},"Got local metadata");let y;e.inputCsv&&(y=await bE(e.inputCsv));let E=e.pixelRatio??yE();EE(E);try{let T=await CN({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:E,tests:t,project:n,client:u,outputDir:m,uploadResults:e.uploadResults,reporterDir:g,customHeaders:r,envName:e.env,orgId:d,testInputMatrix:y,logger:f,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:S,cacheOptions:{regenerateCache:e.regenerateCache,alwaysSaveCache:e.saveCache,noCache:e.disableCache,bustOldestCachePercentage:e.bustOldestCachePercentage},recordVideo:e.recordVideo??n.config.recordVideo,runGroupId:h,timeoutMinutes:e.timeoutMinutes});await Eo(),T.failed>0?process.exit(1):process.exit(0)}catch(T){b.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),b.error(T),await Eo(),process.exit(1)}});var y5=Vt.command("apply").description("Apply an operation to local resources");y5.command("patch").addOption(Zr).addOption(en).addOption(mr).addOption(di).addOption(ui).addOption(new hr("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new hr("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async t=>{await tr(X);let{apiKey:e,server:r,config:n,yes:o}=t,i=await _t({configFilePath:n}),a=X,s=new et({baseUrl:r,apiKey:e,logger:a}),c=await te(i),l=c.tests[t.to]??Object.values(c.tests).find(d=>ze(d.name)===t.to.trim());l||(b.error(`No test matching '${t.to}' could be found in the current project.`),process.exit(1));let u=await s.fetchTestFragment(t.from);await RL({client:s,test:l,fragment:u,yes:o,entities:c,logger:X}),process.exit(0)});var NN=Vt.command("results").description("Merge and upload test results.");NN.command("merge").description("Merge test results files.").addOption(nE).addArgument(KL).action(async(t,e)=>{await tr(X);let{outputDir:r}=e;r||(b.error("Output directory is required."),process.exit(1)),Qm.existsSync(t)||(b.warn("Results path does not exist, skipping merge."),process.exit(0)),Qm.existsSync(r)&&b.warn(`Output directory ${r} already exists, removing before merging...`),cC(X,r,t)});NN.command("upload").description("Upload test results to Momentic cloud.").addOption(Zr).addOption(en).addArgument(YL).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n}=e,o=X,i=new et({baseUrl:n,apiKey:r,logger:o});await Kd({consoleLogger:b,resultsPath:t,client:i}),process.exit(0)});var AE=Vt.command("quarantine").description("Manage test quarantines");AE.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(Zr).addOption(en).addOption(mr).addOption(di).addOption(pE).addArgument(mE).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n,config:o,reason:i}=e,a=X,s=await _t({configFilePath:o}),c=new et({baseUrl:n,apiKey:r,logger:a}),l=await Vr(X,c,s);await ZL({test:t,reason:i,apiClient:c,project:s,logger:a,identity:l})});AE.command("list").description("List quarantined tests.").addOption(Zr).addOption(en).addOption(mr).addOption(di).action(async t=>{let{apiKey:e,server:r,config:n}=t,o=X,i=await _t({configFilePath:n}),a=new et({baseUrl:r,apiKey:e,logger:o});await rN({apiClient:a,project:i})});AE.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(Zr).addOption(en).addOption(mr).addOption(di).addOption(pE).addArgument(mE).action(async(t,e)=>{await tr(X);let{apiKey:r,server:n,config:o,reason:i}=e,a=X,s=await _t({configFilePath:o}),c=new et({baseUrl:n,apiKey:r,logger:a}),l=await Vr(X,c,s);await nN({test:t,reason:i,apiClient:c,project:s,identity:l})});Vt.command("upgrade").description("Upgrade your configuration to the latest recommended settings").addOption(mr).addOption(di).action(async t=>{let e=await _t({configFilePath:t.config,nameFilter:t.filter});b.info("Updating Momentic version in package.json..."),await xN(),b.info("Updating project configuration..."),_N(e),b.success("Your project configuration was successfully updated to the latest recommended settings."),b.info("You can optionally run tests with the `--regenerate-cache` flag to entirely rebuild caches with the newer configuration. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.")});async function E5(){IN("Main program started");try{await Vt.parseAsync(process.argv),await Eo()}catch(t){let e={};try{e.playwrightVersion=d5("npx playwright --version").toString()}catch(r){X.error({err:r},"Error fetching debug information")}X.error({err:t,debugInfo:e},"Uncaught error in CLI"),Xs(t,e),b.error(t),await Eo(),process.exit(1)}}m5.setMaxListeners(25);process.on("warning",t=>{X.warn({err:t},`Node warning received on CLI: ${t.message}`)});IN("CLI parsing setup complete");E5();
4851
4851
  //# sourceMappingURL=cli.js.map
4852
- //# debugId=e53eea05-eeb0-5ef4-b24a-5fc5e9a1ea42
4852
+ //# debugId=caf37916-b13c-5d5d-bd34-16124b2fedc0